diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ded0c5..e644650 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [0.9.1] - 2026-11-10 + +### Fixed + +- **Billing screens stay current without a reload.** The plan picker, the subscription badge, the billing notice and the subscription pages now re-read the plans and the current plan when the tab regains focus (more than 30 seconds after the last read), when the sign-in is renewed, and when a live plan, subscription or payment event arrives. A plan created, changed or removed in Bridge now appears without reloading the page. A background re-read never blanks what is on screen, a failed or empty read is tried once more, and an answer that arrives after signing out is dropped. (TBP-762) + +### Changed + +- **The agent guides follow "every gate is a flag".** The billing, flags and team guides open with the rule and end with `npx @nebulr-group/bridge-cli check gates`; the billing guide no longer says a paid feature should not be a flag, and no guide shows a role or plan check written into app code. (TBP-705) +- **Seat limits are in the team and billing guides**, with `seatsMetric` on the built-in team page and the setup command. (TBP-763) +- **The guides name the Bridge MCP tools** for plans and flags next to the CLI commands, and no longer tell agents to prefer the CLI. (TBP-576) +- **The live-updates page explains why live updates are off**: the status reasons, whose side each one is on, and a link to the troubleshooting page. (TBP-642, TBP-675) +- **A test now fails when a guide names something the package does not have**: an export, a component, a prop, a billing option or a `bridge.*` path. + +These bring the React package level with the Svelte package on billing refresh and the guides. + ## [0.9.0] - 2026-11-10 ### Changed diff --git a/bridge-react/package.json b/bridge-react/package.json index 3cc673e..e23770b 100644 --- a/bridge-react/package.json +++ b/bridge-react/package.json @@ -1,6 +1,6 @@ { "name": "@nebulr-group/bridge-react", - "version": "0.9.0", + "version": "0.9.1", "description": "The Bridge for React: sign-in, workspaces and roles, feature flags, Stripe subscriptions and plan limits, with React Router or TanStack Router.", "main": "dist/index.cjs.js", "module": "dist/index.esm.js", diff --git a/bridge-react/src/components/subscription/BridgeBillingNotice.tsx b/bridge-react/src/components/subscription/BridgeBillingNotice.tsx index 6927008..14746bb 100644 --- a/bridge-react/src/components/subscription/BridgeBillingNotice.tsx +++ b/bridge-react/src/components/subscription/BridgeBillingNotice.tsx @@ -27,7 +27,7 @@ import { } from '@nebulr-group/bridge-auth-core'; import { getBridgeAuth } from '../../core/bridge-instance'; import { billingRoutes } from '../../core/billing-routes'; -import { tokenStaleHandler } from '../../core/bridge-runtime'; +import { ensureBillingState } from '../../core/billing-state'; import { useBridgeSnapshot } from '../../hooks/use-bridge-readable'; type Chassis = 'bar' | 'rail' | 'card'; @@ -80,16 +80,9 @@ export function BridgeBillingNotice({ subscription.setError('Not authenticated'); return; } - if (!subscription.snapshot().state) { - void subscription.mount({ - apiBaseUrl: ctx.apiBaseUrl, - accessToken: ctx.accessToken, - appId: ctx.appId, - // TBP-762 — right after a checkout the sign-in is out of date; renew it - // and retry once instead of showing "Subscription unavailable". - onTokenStale: tokenStaleHandler(), - }); - } + // TBP-762 — through the billing store: renews an out-of-date sign-in, + // retries once, and re-reads on the store's refresh rule. + void ensureBillingState(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/bridge-react/src/components/subscription/BridgePaywall.tsx b/bridge-react/src/components/subscription/BridgePaywall.tsx index e62e748..d49921a 100644 --- a/bridge-react/src/components/subscription/BridgePaywall.tsx +++ b/bridge-react/src/components/subscription/BridgePaywall.tsx @@ -23,7 +23,7 @@ */ import { useEffect, useMemo, type ReactNode } from 'react'; import type { Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core'; -import { loadSubscription, useBridgeStore } from '../../core/bridge-instance'; +import { ensureSubscription, useBridgeStore } from '../../core/bridge-instance'; import { PlanSelector } from './PlanSelector'; export interface BridgePaywallProps { @@ -49,10 +49,9 @@ export function BridgePaywall({ const { status, loading } = subscription; useEffect(() => { - if (!status && !loading) { - void loadSubscription(); - } - // eslint-disable-next-line react-hooks/exhaustive-deps + // TBP-762 — read unless a read younger than 30 s exists; the billing + // store's refresh rule keeps it current from then on. + void ensureSubscription(); }, []); // Show paywall only once the subscription status is known and the tenant has diff --git a/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx b/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx index 6b67e9b..136288b 100644 --- a/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx +++ b/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx @@ -10,15 +10,15 @@ * * Reactive translation (§5.1): svelte `$state(useBridge().subscription.snapshot())` * + `onMount(() => subscription.subscribe(...))` → `useBridgeSnapshot(subscribe, - * getSnapshot)`. The one-shot `mount()` fetch stays in a `useEffect`. + * getSnapshot)`. The read on mount (`ensureBillingState()`) stays in a `useEffect`. * - * No live push in v1 — fetches once on mount (the realtime wiring lands with the - * provider's `attachToRealtimeClient`). + * Live: auth-core patches the store on billing pushes, and the billing store's + * refresh rule (TBP-762) re-reads it on sign-in renewal, live billing events + * and tab focus. */ import { useEffect } from 'react'; import { useBridge } from '@nebulr-group/bridge-auth-core'; -import { getBridgeAuth } from '../../core/bridge-instance'; -import { tokenStaleHandler } from '../../core/bridge-runtime'; +import { ensureBillingState } from '../../core/billing-state'; import { useBridgeSnapshot } from '../../hooks/use-bridge-readable'; export interface BridgeSubscriptionStatusProps { @@ -37,21 +37,10 @@ export function BridgeSubscriptionStatus({ ); useEffect(() => { - const ctx = getBridgeAuth().getApiContext(); - if (!ctx.accessToken) { - subscription.setError('Not authenticated'); - return; - } - void subscription.mount({ - apiBaseUrl: ctx.apiBaseUrl, - accessToken: ctx.accessToken, - appId: ctx.appId, - // TBP-762 — right after a checkout the sign-in is out of date; renew it - // and retry once instead of showing "Subscription unavailable". - onTokenStale: tokenStaleHandler(), - }); - // subscription is the auth-core singleton — stable across renders. - // eslint-disable-next-line react-hooks/exhaustive-deps + // TBP-762 — through the billing store: read unless a read younger than + // 30 s exists, renew an out-of-date sign-in, retry once, and stay current + // on the refresh rule (sign-in renewal, live billing events, tab focus). + void ensureBillingState(); }, []); return ( diff --git a/bridge-react/src/core/billing-refresh.ts b/bridge-react/src/core/billing-refresh.ts index db68c25..c43e08f 100644 --- a/bridge-react/src/core/billing-refresh.ts +++ b/bridge-react/src/core/billing-refresh.ts @@ -1,25 +1,165 @@ -// TBP-743 — re-read everything billing after something changed the plan (a -// plan pick, a checkout). Mirrors bridge-svelte's `refreshBilling()`: the plan -// list and current plan (the subscription slice `` reads) and -// the billing state (``, ``). -// Never throws: each read reports its own failure through its store. +// TBP-762 — the billing screens' refresh rule. Ported from bridge-svelte's +// `core/billing-store.ts`. +// +// The plan list and current plan (the store slice ``, +// `` and the subscription page read) and the canonical billing +// state (``, ``) are re-read +// together, on one rule: +// +// - when the sign-in is renewed (a new access token: refresh, sign-in, the +// re-mint a plan change causes); +// - on a live billing event (plan change, subscription or payment lifecycle); +// - when the tab regains focus and the last read is older than 30 seconds — +// how a plan created, changed or removed in Bridge reaches an open page; +// - one retry when a read fails. +// +// Screens call `ensureSubscription()` / `ensureBillingState()` on mount and +// read the stores. Only what some screen has asked for is re-read, so an app +// that never shows billing makes no extra calls. +// +// Before 0.9.1 nothing re-read the plan list after the first load: a plan added +// in Bridge did not appear until a reload. import { useBridge as useBillingBridge } from '@nebulr-group/bridge-auth-core'; -import { getBridgeAuth, loadSubscription } from './bridge-instance'; -import { tokenStaleHandler } from './bridge-runtime'; +import { + ensureSubscription, + getBridgeAuth, + loadSubscription, + subscriptionWanted, + useBridgeStore, +} from './bridge-instance'; +import { + BILLING_STALE_AFTER_MS, + billingStateReadToken, + billingStateWanted, + ensureBillingState, + refreshBillingState, +} from './billing-state'; +import { readEntitlements } from './startup-reads'; +import { logger } from '../utils/logger'; -export async function refreshBilling(): Promise { - await loadSubscription().catch(() => {}); +export { BILLING_STALE_AFTER_MS, ensureBillingState, refreshBillingState } from './billing-state'; + +function stateInStore(): boolean { try { - const ctx = getBridgeAuth().getApiContext(); - if (!ctx.accessToken) return; - await useBillingBridge().subscription.mount({ - apiBaseUrl: ctx.apiBaseUrl, - accessToken: ctx.accessToken, - appId: ctx.appId, - onTokenStale: tokenStaleHandler(), - }); + return useBillingBridge().subscription.snapshot().state !== null; } catch { - /* the badge re-reads on its own next mount */ + return false; + } +} + +/** + * Re-read everything billing after something changed the plan (a plan pick, a + * checkout, a live billing event): the plan list and current plan when a + * screen has asked for them, the billing state, and the plan's features (what + * `bridge:billing.entitlement.*` flag rules read; Bridge does not always push + * `entitlements.changed` for a plan change). Never rejects. + */ +export async function refreshBilling(): Promise { + try { + const reads: Promise[] = []; + if (subscriptionWanted()) reads.push(loadSubscription()); + if (billingStateWanted() || stateInStore()) reads.push(refreshBillingState()); + reads.push(readEntitlements()); + await Promise.all(reads); + } catch (err) { + // Bridge not initialised (tests): nothing to re-read. + logger.debug('[bridge-billing] refresh skipped:', err); + } +} + +/** On mount: read what has not been read, or was read more than 30 s ago. */ +export async function ensureBilling(maxAgeMs = BILLING_STALE_AFTER_MS): Promise { + try { + await Promise.all([ensureSubscription(maxAgeMs), ensureBillingState(maxAgeMs)]); + } catch (err) { + logger.debug('[bridge-billing] ensure skipped:', err); + } +} + +/** Live events after which the billing stores are re-read. */ +export const BILLING_REFRESH_EVENTS: ReadonlySet = new Set([ + 'subscription.plan_changed', + 'subscription.created', + 'subscription.updated', + 'subscription.canceled', + 'subscription.reactivated', + 'subscription.trial_started', + 'subscription.trial_converted', + 'subscription.trial_expired', + 'payment.succeeded', + 'payment.failed', + 'dunning.recovered', + 'dunning.exhausted', +]); + +/** The runtime calls this for every realtime billing event. Never throws. */ +export function billingEventReceived(kind: string): void { + if (!BILLING_REFRESH_EVENTS.has(kind)) return; + void refreshBilling(); +} + +/** + * A renewed sign-in: re-read what the screens asked for. The runtime has + * already re-read the billing state and the plan's features for a token that + * changes the session or the plan (TBP-941); a read that started with this + * token is not repeated. + */ +function signInRenewed(token: string): void { + const reads: Promise[] = []; + if (subscriptionWanted()) reads.push(loadSubscription()); + if ((billingStateWanted() || stateInStore()) && billingStateReadToken() !== token) { + reads.push(refreshBillingState()); } + void Promise.all(reads); +} + +let _stop: (() => void) | null = null; + +/** + * Install the sign-in-renewal and tab-focus triggers. Browser only; returns + * the stop function. Idempotent: a second call replaces the first. + * `` calls it on mount. + */ +export function startBillingRefresh(): () => void { + _stop?.(); + let lastToken = useBridgeStore.getState().tokens?.accessToken ?? null; + const offToken = useBridgeStore.subscribe((state) => { + const token = state.tokens?.accessToken ?? null; + if (token === lastToken) return; + lastToken = token; + if (token) signInRenewed(token); + }); + + const onFocus = () => { + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return; + try { + if (!getBridgeAuth().getApiContext().accessToken) return; + } catch { + return; + } + const reads: Promise[] = []; + if (subscriptionWanted()) reads.push(ensureSubscription(BILLING_STALE_AFTER_MS)); + if (billingStateWanted() || stateInStore()) reads.push(ensureBillingState(BILLING_STALE_AFTER_MS)); + void Promise.all(reads); + }; + const win = typeof window !== 'undefined' && typeof window.addEventListener === 'function' ? window : null; + const doc = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : null; + win?.addEventListener('focus', onFocus); + doc?.addEventListener('visibilitychange', onFocus); + + const stop = () => { + offToken(); + win?.removeEventListener('focus', onFocus); + doc?.removeEventListener('visibilitychange', onFocus); + if (_stop === stop) _stop = null; + }; + _stop = stop; + return stop; +} + +/** Test-only. */ +export function __resetBillingRefreshForTests(): void { + _stop?.(); + _stop = null; } diff --git a/bridge-react/src/core/billing-state.ts b/bridge-react/src/core/billing-state.ts new file mode 100644 index 0000000..b71376d --- /dev/null +++ b/bridge-react/src/core/billing-state.ts @@ -0,0 +1,189 @@ +// TBP-762 — reading the canonical billing state (`GET /billing/state`, what +// ``, `` and +// `bridge:billing.plan` flag rules read) through one place. Ported from +// bridge-svelte's `core/billing-store.ts`. +// +// - concurrent reads share one request; a call made during a read gets one +// more read after it (the caller asked because something changed); +// - only a first read shows "Loading…"; a re-read keeps the plan on screen; +// - a failed read is retried once; a failed re-read keeps the last answer; +// - an answer that arrives after sign-out or a workspace switch is dropped; +// - every read renews an out-of-date sign-in (`onTokenStale`). +// +// Kept apart from `billing-refresh.ts` so the startup reads can use it without +// an import cycle (the runtime imports both). + +import { + fetchBillingState, + useBridge as useBillingBridge, + type MountOptions, +} from '@nebulr-group/bridge-auth-core'; +import { billingRetryDelay, getBridgeAuth } from './bridge-instance'; +import { logger } from '../utils/logger'; + +const DEFAULT_API_BASE_URL = 'https://api.thebridge.dev'; + +/** A read older than this is re-read when the tab regains focus or a screen mounts. */ +export const BILLING_STALE_AFTER_MS = 30_000; + +/** + * The handler that renews an out-of-date sign-in, when the installed auth-core + * has it (0.8.0-beta.5+; older ones simply do not retry). + */ +function tokenStaleHandler(): (() => Promise) | undefined { + try { + const auth = getBridgeAuth() as ReturnType & { + tokenStaleHandler?: () => () => Promise; + }; + return typeof auth.tokenStaleHandler === 'function' ? auth.tokenStaleHandler() : undefined; + } catch { + return undefined; + } +} + +/** + * HTTP options for a billing read: the current token and the handler that + * renews an out-of-date one. Null when signed out or before Bridge is set up. + */ +export function billingReadOptions(): MountOptions | null { + try { + const ctx = getBridgeAuth().getApiContext(); + if (!ctx.accessToken) return null; + return { + apiBaseUrl: ctx.apiBaseUrl ?? DEFAULT_API_BASE_URL, + accessToken: ctx.accessToken, + appId: ctx.appId, + onTokenStale: tokenStaleHandler(), + }; + } catch { + return null; + } +} + +let _inflight: Promise | null = null; +let _again = false; +let _loadedAt = 0; +let _wanted = false; +let _readToken: string | null = null; + +/** True once a billing screen has asked for the billing state in this session. */ +export function billingStateWanted(): boolean { + return _wanted; +} + +/** The access token the latest billing-state read started with. */ +export function billingStateReadToken(): string | null { + return _readToken; +} + +/** Re-read the canonical billing state. Never rejects. */ +export function refreshBillingState(): Promise { + if (_inflight) { + _again = true; + return _inflight; + } + _inflight = (async () => { + try { + do { + _again = false; + await readStateOnce(); + } while (_again); + } finally { + _inflight = null; + } + })(); + return _inflight; +} + +/** + * What a billing screen calls on mount: read unless a read younger than + * `maxAgeMs` exists, and mark the billing state as wanted so the refresh rule + * keeps it current. Never rejects. + */ +export function ensureBillingState(maxAgeMs = BILLING_STALE_AFTER_MS): Promise { + _wanted = true; + if (_inflight) return _inflight; + try { + const sub = useBillingBridge().subscription; + if (_loadedAt > 0 && sub.snapshot().state && Date.now() - _loadedAt < maxAgeMs) { + return Promise.resolve(); + } + } catch { + return Promise.resolve(); + } + return refreshBillingState(); +} + +async function readStateOnce(): Promise { + let sub: ReturnType['subscription']; + try { + sub = useBillingBridge().subscription; + } catch { + return; // billing surface unavailable + } + const hadState = sub.snapshot().state !== null; + // Only a first read shows "Loading…"; a re-read keeps the plan on screen. + if (!hadState) { + sub.setError(null); + sub.setLoading(true); + } + try { + for (let attempt = 0; ; attempt++) { + const opts = billingReadOptions(); + if (!opts) { + if (!sub.snapshot().state) sub.setError('Not authenticated'); + return; + } + _readToken = opts.accessToken; + try { + const state = await fetchBillingState(opts, logger); + // Signed out or switched workspace meanwhile: not this session's plan. + if (tokenChangedWorkspace(opts.accessToken)) return; + sub.hydrate(state); + _loadedAt = Date.now(); + return; + } catch (err) { + if (attempt === 0) { + // The one retry. "Loading…" stays up meanwhile — a checkout that is + // still being confirmed is not an error. + await new Promise((r) => setTimeout(r, billingRetryDelay())); + continue; + } + const message = err instanceof Error ? err.message : 'Failed to load billing state'; + logger.warn('[bridge-billing] billing state read failed:', message); + if (!sub.snapshot().state) sub.setError(message); + return; + } + } + } finally { + if (!hadState) sub.setLoading(false); + } +} + +function workspaceOf(token: string | null | undefined): string | null { + if (!token) return null; + try { + const payload = token.split('.')[1]; + if (!payload) return null; + const json = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))) as { tid?: unknown }; + return typeof json.tid === 'string' ? json.tid : null; + } catch { + return null; + } +} + +/** True when the session now belongs to a different workspace (or none) than `token`. */ +function tokenChangedWorkspace(token: string): boolean { + const now = billingReadOptions()?.accessToken ?? null; + if (!now) return true; + return workspaceOf(now) !== workspaceOf(token); +} + +/** Test-only. */ +export function __resetBillingStateForTests(): void { + _inflight = null; + _again = false; + _loadedAt = 0; + _wanted = false; + _readToken = null; +} diff --git a/bridge-react/src/core/bridge-instance.ts b/bridge-react/src/core/bridge-instance.ts index 5b41d33..68fdbcb 100644 --- a/bridge-react/src/core/bridge-instance.ts +++ b/bridge-react/src/core/bridge-instance.ts @@ -150,10 +150,12 @@ export function initBridge(config: BridgeAuthConfig): BridgeAuth { }); _instance.on('auth:logout', () => { + resetSubscriptionReads(); useBridgeStore.setState({ tokens: null, profile: null, flags: {}, + subscription: { status: null, plans: null, loading: false, error: null }, }); }); @@ -175,6 +177,7 @@ export function initBridge(config: BridgeAuthConfig): BridgeAuth { }); _instance.on('auth:workspace-changed', (tokens) => { + resetSubscriptionReads(); useBridgeStore.setState({ tokens, flags: {}, @@ -247,28 +250,75 @@ export function waitForBridge(): Promise { } // ── Subscription ────────────────────────────────────────────────────────────── +// +// TBP-762 — one refresh rule for the plan list and the current plan (ported +// from bridge-svelte's `core/bridge-instance.ts`). +// +// Every screen used to fetch on its own, so a list loaded once was served for +// the life of the tab: a plan added in Bridge never appeared until a reload. +// Now: +// - concurrent calls share one read, and a call made while a read is in +// flight gets a second read after it — the caller asked because something +// changed, and the in-flight answer may predate that; +// - a read that fails, or answers with an empty plan list, is retried once; +// - a background re-read never blanks what is on screen: `loading` is only +// true while there is nothing to show, and a failed re-read keeps the last +// good answer instead of replacing it with an error; +// - an answer that arrives after sign-out or a workspace switch is dropped. +// `core/billing-refresh.ts` decides WHEN to re-read (sign-in renewal, live +// billing events, tab focus after 30 s); this is HOW. + +/** Delay before the one retry of a failed or empty read. */ +let _retryDelayMs = 1000; +/** @internal — test-only: shorten the retry delay. */ +export function __setBillingRetryDelay(ms: number): void { + _retryDelayMs = ms; +} +/** @internal — the delay before a billing read's one retry. */ +export function billingRetryDelay(): number { + return _retryDelayMs; +} +let _subInflight: Promise | null = null; +let _subAgain = false; let _subscriptionLoadedAt = 0; +let _subWanted = false; +/** Bumped on sign-out and workspace switch; a read started before is discarded. */ +let _subGeneration = 0; -export async function loadSubscription(): Promise { - useBridgeStore.setState((s) => ({ - subscription: { ...s.subscription, loading: true, error: null }, - })); - try { - const [status, plans] = await Promise.all([ - getBridgeAuth().getSubscriptionStatus(), - getBridgeAuth().getPlans(), - ]); - useBridgeStore.setState({ - subscription: { status, plans, loading: false, error: null }, - }); - _subscriptionLoadedAt = Date.now(); - } catch (err) { - const msg = err instanceof Error ? err.message : 'Failed to load subscription'; - useBridgeStore.setState((s) => ({ - subscription: { ...s.subscription, loading: false, error: msg }, - })); +function resetSubscriptionReads(): void { + _subGeneration += 1; + _subscriptionLoadedAt = 0; +} + +/** When the plan list and status were last read successfully (ms epoch), 0 if never. */ +export function subscriptionLoadedAt(): number { + return _subscriptionLoadedAt; +} + +/** True once any screen has asked for the plan list / status in this session. */ +export function subscriptionWanted(): boolean { + return _subWanted; +} + +/** Re-read the plan list and the current plan. Never rejects. */ +export function loadSubscription(): Promise { + _subWanted = true; + if (_subInflight) { + _subAgain = true; + return _subInflight; } + _subInflight = (async () => { + try { + do { + _subAgain = false; + await readSubscriptionOnce(); + } while (_subAgain); + } finally { + _subInflight = null; + } + })(); + return _subInflight; } /** @@ -277,12 +327,59 @@ export async function loadSubscription(): Promise { * between them does not re-read every time (mirrors bridge-svelte TBP-762). */ export function ensureSubscription(maxAgeMs = 30_000): Promise { - const { status, plans, loading } = useBridgeStore.getState().subscription; - if (loading) return Promise.resolve(); - if (status && plans && Date.now() - _subscriptionLoadedAt < maxAgeMs) return Promise.resolve(); + if (_subInflight) return _subInflight; + if (_subscriptionLoadedAt > 0 && Date.now() - _subscriptionLoadedAt < maxAgeMs) return Promise.resolve(); return loadSubscription(); } +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function readSubscriptionOnce(): Promise { + const generation = _subGeneration; + const current = useBridgeStore.getState().subscription; + const hasData = current.status !== null || current.plans !== null; + if (!hasData) { + useBridgeStore.setState((s) => ({ subscription: { ...s.subscription, loading: true, error: null } })); + } + + for (let attempt = 0; ; attempt++) { + try { + const [status, plans] = await Promise.all([ + getBridgeAuth().getSubscriptionStatus(), + getBridgeAuth().getPlans(), + ]); + if (generation !== _subGeneration) return; + // An empty list is more often a read that raced a change than an app + // with no plans: ask once more before believing it. + if ((plans?.length ?? 0) === 0 && attempt === 0) { + await wait(_retryDelayMs); + if (generation !== _subGeneration) return; + continue; + } + useBridgeStore.setState({ subscription: { status, plans, loading: false, error: null } }); + _subscriptionLoadedAt = Date.now(); + return; + } catch (err) { + if (generation !== _subGeneration) return; + if (attempt === 0) { + await wait(_retryDelayMs); + if (generation !== _subGeneration) return; + continue; + } + const msg = err instanceof Error ? err.message : 'Failed to load subscription'; + logger.warn('[bridge-instance] subscription read failed:', msg); + const latest = useBridgeStore.getState().subscription; + if (latest.status !== null || latest.plans !== null) { + // Keep the last good answer on screen; the next trigger re-reads. + useBridgeStore.setState((s) => ({ subscription: { ...s.subscription, loading: false } })); + } else { + useBridgeStore.setState((s) => ({ subscription: { ...s.subscription, loading: false, error: msg } })); + } + return; + } + } +} + // ── Stripe checkout return (TBP-723) ────────────────────────────────────────── // // On the Stripe return the access token still predates the payment, so its @@ -350,6 +447,11 @@ export function _resetBridgeInstance(): void { _appConfigPromise = null; _checkoutConfirmation = null; _subscriptionLoadedAt = 0; + _subInflight = null; + _subAgain = false; + _subWanted = false; + _subGeneration += 1; + _retryDelayMs = 1000; _resolveReady = null; useBridgeStore.setState({ tokens: null, diff --git a/bridge-react/src/core/bridge-runtime.ts b/bridge-react/src/core/bridge-runtime.ts index da75acc..e94884a 100644 --- a/bridge-react/src/core/bridge-runtime.ts +++ b/bridge-react/src/core/bridge-runtime.ts @@ -63,6 +63,7 @@ import { } from './guard-cache'; import { logger } from '../utils/logger'; import { reloadSessionBilling } from './startup-reads'; +import { billingEventReceived } from './billing-refresh'; const DEFAULT_API_BASE_URL = 'https://api.thebridge.dev'; @@ -620,22 +621,23 @@ export function startBridgeRuntime(options: StartBridgeRuntimeOptions = {}): voi 'subscription.plan_changed': (m) => { try { applySubscriptionPlanChanged(m); } catch { /* store updates shouldn't throw, defensive */ } authorizationChanged('subscription.plan_changed'); + billingChanged(m.kind); bridgeEvents._dispatch(m); }, - 'payment.failed': (m) => bridgeEvents._dispatch(m), - 'payment.succeeded': (m) => bridgeEvents._dispatch(m), - 'subscription.created': (m) => bridgeEvents._dispatch(m), - 'subscription.updated': (m) => bridgeEvents._dispatch(m), - 'subscription.canceled': (m) => bridgeEvents._dispatch(m), - 'subscription.reactivated': (m) => bridgeEvents._dispatch(m), - 'subscription.trial_started': (m) => bridgeEvents._dispatch(m), + 'payment.failed': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'payment.succeeded': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'subscription.created': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'subscription.updated': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'subscription.canceled': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'subscription.reactivated': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'subscription.trial_started': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, 'subscription.trial_ending_soon': (m) => bridgeEvents._dispatch(m), - 'subscription.trial_converted': (m) => bridgeEvents._dispatch(m), - 'subscription.trial_expired': (m) => bridgeEvents._dispatch(m), + 'subscription.trial_converted': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'subscription.trial_expired': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, 'dunning.entered': (m) => bridgeEvents._dispatch(m), 'dunning.retry_scheduled': (m) => bridgeEvents._dispatch(m), - 'dunning.recovered': (m) => bridgeEvents._dispatch(m), - 'dunning.exhausted': (m) => bridgeEvents._dispatch(m), + 'dunning.recovered': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, + 'dunning.exhausted': (m) => { billingChanged(m.kind); bridgeEvents._dispatch(m); }, 'quota.updated': (m) => bridgeEvents._dispatch(m), 'entitlements.changed': (m) => { // Only the payload-carrying variant has a map; the signal-only one is a no-op here. @@ -940,3 +942,16 @@ function decodeJwtPayload(token: string): Record | null { return null; } } + +/** + * TBP-762 — a live billing event re-reads the plan list, the current plan and + * the billing state (`core/billing-refresh.ts` owns the rule; lifecycle kinds + * it does not list are ignored there). Never throws. + */ +function billingChanged(kind: string): void { + try { + billingEventReceived(kind); + } catch { + /* billing store unavailable (tests) — the live patch still applied */ + } +} diff --git a/bridge-react/src/core/startup-reads.ts b/bridge-react/src/core/startup-reads.ts index 5e3c638..001560b 100644 --- a/bridge-react/src/core/startup-reads.ts +++ b/bridge-react/src/core/startup-reads.ts @@ -20,6 +20,7 @@ import { useBridge as useBillingBridge } from '@nebulr-group/bridge-auth-core'; import { getBridgeAuth } from './bridge-instance'; import { applyEntitlementsChanged } from './snapshot-stores'; +import { refreshBillingState } from './billing-state'; import { logger } from '../utils/logger'; const DEFAULT_API_BASE_URL = 'https://api.thebridge.dev'; @@ -182,21 +183,9 @@ async function readEntitlementsOnce(): Promise { * `` read). Never rejects. */ export async function readBillingState(): Promise { - try { - const ctx = getBridgeAuth().getApiContext(); - if (!ctx.accessToken) return; - await useBillingBridge().subscription.mount( - { - apiBaseUrl: ctx.apiBaseUrl ?? DEFAULT_API_BASE_URL, - accessToken: ctx.accessToken, - appId: ctx.appId, - onTokenStale: tokenStaleHandler(), - }, - logger, - ); - } catch (err) { - logger.debug('[bridge-startup] billing state read skipped:', err); - } + // TBP-762 — through the billing store's single read: concurrent reads share + // one request, a re-read keeps the plan on screen, a failure is retried once. + await refreshBillingState(); } /** Re-read what a new session is entitled to. Never rejects. */ diff --git a/bridge-react/src/providers/bridge-provider.tsx b/bridge-react/src/providers/bridge-provider.tsx index 3b900f7..ed7087e 100644 --- a/bridge-react/src/providers/bridge-provider.tsx +++ b/bridge-react/src/providers/bridge-provider.tsx @@ -21,6 +21,7 @@ import { appUsesBilling, billingRoutes, isPaywallExempt } from '../core/billing- import { installQuotaObserver, uninstallQuotaObserver } from '../core/bridge-fetch'; import { BridgeUpgradeMount } from '../components/subscription/BridgeUpgradeMount'; import { loadBeforeFirstRender, withinWait } from '../core/startup-reads'; +import { startBillingRefresh } from '../core/billing-refresh'; interface BridgeProviderProps { /** Your bridge application ID - can be provided directly or via config */ @@ -222,6 +223,10 @@ export const BridgeProvider: FC = ({ appId, config, childre startBridgeRuntime(); installQuotaObserver(); + // TBP-762 — the billing screens' refresh rule: re-read the plan list, + // current plan and billing state on a renewed sign-in and on tab focus + // after 30 s (live billing events are wired in the runtime). + const stopBillingRefresh = startBillingRefresh(); if (!flagsBundleRef.current) { try { flagsBundleRef.current = createBridgeFlags(); @@ -236,6 +241,7 @@ export const BridgeProvider: FC = ({ appId, config, childre flagsBundleRef.current = null; } uninstallQuotaObserver(); + stopBillingRefresh(); void stopBridgeRuntime(); }; }, []); diff --git a/bridge-react/test/billing-refresh.test.tsx b/bridge-react/test/billing-refresh.test.tsx new file mode 100644 index 0000000..0fda4de --- /dev/null +++ b/bridge-react/test/billing-refresh.test.tsx @@ -0,0 +1,321 @@ +/** + * TBP-762 — the billing screens stay current without a reload. + * + * Regression (bridge-react 0.9.0): the plan list and the billing state were + * read once, when a screen first mounted, and never again. A plan created, + * changed or removed in Bridge did not appear on an open plan picker until a + * reload, and a live subscription or payment event moved nothing but the + * event bus. bridge-svelte re-reads both on one rule (`core/billing-store.ts`): + * a renewed sign-in, a live billing event, and tab focus after 30 s; a failed + * or empty read is retried once; a re-read never blanks the screen. This is + * the React port. Bridge itself is faked: only the network and the auth-core + * calls are replaced. + * + * Revert-proof: on 0.9.0 there is no focus or visibility handler, no + * `startBillingRefresh`, the runtime's billing handlers only dispatch, and + * `loadSubscription()` neither shares reads nor retries. + */ +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test'; +import { act, cleanup, render, waitFor } from '@testing-library/react'; +import { BridgeAuth, useBridge, type Plan, type WebSocketLike } from '@nebulr-group/bridge-auth-core'; +import { PlanSelector } from '../src/components/subscription/PlanSelector'; +import { BridgeSubscriptionStatus } from '../src/components/subscription/BridgeSubscriptionStatus'; +import { + __setBillingRetryDelay, + _resetBridgeInstance, + getBridgeAuth, + initBridge, + loadSubscription, + useBridgeStore, +} from '../src/core/bridge-instance'; +import { __resetBillingRefreshForTests, startBillingRefresh } from '../src/core/billing-refresh'; +import { __resetBillingStateForTests } from '../src/core/billing-state'; +import { __resetBridgeRuntime, startBridgeRuntime, stopBridgeRuntime } from '../src/core/bridge-runtime'; +import { __resetStartupReadsForTests } from '../src/core/startup-reads'; + +const API = 'http://api.test.local'; + +const plan = (key: string, name: string, amount: number) => + ({ + key, + name, + trial: false, + prices: [{ id: `${key}-m`, amount, currency: 'usd', recurrenceInterval: 'month' }], + }) as unknown as Plan; + +const FREE = plan('free', 'Free', 0); +const PRO = plan('pro', 'Pro', 20); +const TEAM = plan('team', 'Team', 50); + +// What the fake Bridge answers right now. Tests change it to simulate an edit +// made in the Bridge dashboard while the app is open. +let serverPlans: Plan[]; +let serverBillingPlan: { slug: string; name: string }; +let plansFail: boolean; +let token: string | null; +let planReads: number; +let billingReads: number; +let now: number; +let originalFetch: typeof fetch; +const spies: Array<{ mockRestore(): void }> = []; +let stops: Array<() => void> = []; + +function advance(ms: number): void { + now += ms; +} + +async function focusTab(): Promise { + await act(async () => { + window.dispatchEvent(new Event('focus')); + }); +} + +beforeEach(() => { + __resetBridgeRuntime(); + _resetBridgeInstance(); + __resetBillingStateForTests(); + __resetStartupReadsForTests(); + __setBillingRetryDelay(0); + initBridge({ appId: 'app-1', apiBaseUrl: API } as never); + useBridge().subscription.hydrate(null as never); // no billing read yet + + serverPlans = [FREE, PRO]; + serverBillingPlan = { slug: 'free', name: 'Free' }; + plansFail = false; + token = 'tok-1'; + planReads = 0; + billingReads = 0; + now = 1_000_000; + useBridgeStore.setState({ tokens: { accessToken: token, refreshToken: 'r' } as never }); + + originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = new URL(String(input)); + if (url.pathname === '/billing/state') { + billingReads += 1; + return new Response(JSON.stringify({ plan: serverBillingPlan, status: 'active' }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + if (url.pathname === '/realtime/config') { + return new Response(JSON.stringify({ kind: 'noop' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); + } + return new Response('{}', { status: 404 }); + }) as typeof fetch; + + const auth = getBridgeAuth(); + const proto = BridgeAuth.prototype as unknown as Record; + spies.push( + spyOn(Date, 'now').mockImplementation(() => now), + spyOn(console, 'warn').mockImplementation(() => {}), + spyOn(auth, 'getApiContext').mockImplementation((() => ({ apiBaseUrl: API, appId: 'app-1', accessToken: token })) as never), + spyOn(proto as never, 'getSubscriptionStatus' as never).mockImplementation((async () => ({ plan: 'free' })) as never), + spyOn(proto as never, 'getPlans' as never).mockImplementation((async () => { + planReads += 1; + if (plansFail) throw new Error('network down'); + return [...serverPlans]; + }) as never), + ); +}); + +afterEach(async () => { + cleanup(); + for (const stop of stops.splice(0)) stop(); + __resetBillingRefreshForTests(); + for (const spy of spies.splice(0)) spy.mockRestore(); + globalThis.fetch = originalFetch; + await stopBridgeRuntime(); + __resetBridgeRuntime(); + __resetBillingStateForTests(); + _resetBridgeInstance(); +}); + +describe('the plan picker stays current (TBP-762)', () => { + it('a plan added in Bridge appears when the tab regains focus after 30 s, without a reload', async () => { + stops.push(startBillingRefresh()); + const { container } = render(); + await waitFor(() => expect(container.textContent).toContain('Pro')); + expect(container.textContent).not.toContain('Team'); + + serverPlans = [FREE, PRO, TEAM]; // the owner adds "Team" in the Bridge dashboard + advance(31_000); + await focusTab(); + + await waitFor(() => expect(container.textContent).toContain('Team')); + }); + + it('a focus within 30 s of the last read does not read again', async () => { + stops.push(startBillingRefresh()); + render(); + await waitFor(() => expect(planReads).toBe(1)); + advance(5_000); + await focusTab(); + await new Promise((r) => setTimeout(r, 10)); + expect(planReads).toBe(1); + }); + + it('a renewed sign-in re-reads the plan list', async () => { + stops.push(startBillingRefresh()); + const { container } = render(); + await waitFor(() => expect(planReads).toBe(1)); + + serverPlans = [FREE, PRO, TEAM]; + token = 'tok-2'; + act(() => useBridgeStore.setState({ tokens: { accessToken: token, refreshToken: 'r' } as never })); + + await waitFor(() => expect(container.textContent).toContain('Team')); + }); + + it('an app that never showed a billing screen makes no billing reads on focus', async () => { + stops.push(startBillingRefresh()); + advance(60_000); + await focusTab(); + await new Promise((r) => setTimeout(r, 10)); + expect(planReads).toBe(0); + expect(billingReads).toBe(0); + }); +}); + +describe('the subscription badge stays current (TBP-762)', () => { + it('re-reads the billing state on focus after 30 s and swaps the plan without a "Loading…" flash', async () => { + stops.push(startBillingRefresh()); + const { container } = render(); + await waitFor(() => expect(container.querySelector('.bss-plan')?.textContent).toBe('Free')); + + const seenLoading: boolean[] = []; + const off = useBridge().subscription.subscribe((s) => seenLoading.push(s.loading)); + serverBillingPlan = { slug: 'pro', name: 'Pro' }; + advance(31_000); + await focusTab(); + + await waitFor(() => expect(container.querySelector('.bss-plan')?.textContent).toBe('Pro')); + off(); + expect(seenLoading.includes(true)).toBe(false); + }); +}); + +describe('live billing events re-read the billing screens (TBP-762)', () => { + /** A socket that never opens — the test drives the billing handlers directly. */ + class InertWebSocket implements WebSocketLike { + readyState = 0; + onopen: ((ev: unknown) => void) | null = null; + onclose: ((ev: unknown) => void) | null = null; + onerror: ((ev: unknown) => void) | null = null; + onmessage: ((ev: { data: unknown }) => void) | null = null; + send(): void {} + close(): void { + this.readyState = 3; + } + } + + for (const kind of ['subscription.updated', 'subscription.created', 'payment.succeeded', 'subscription.plan_changed']) { + it(`${kind} re-reads the plan list and the billing state`, async () => { + let handlers: Record void> = {}; + const billingBridge = useBridge(); + spies.push( + spyOn(billingBridge, 'handle').mockImplementation(((h: Record void>) => { + handlers = h; + return () => {}; + }) as never), + spyOn(billingBridge, 'attachToRealtimeClient').mockImplementation((() => {}) as never), + ); + startBridgeRuntime({ + realtime: { websocketFactory: () => new InertWebSocket(), reportStatus: false, diagnose: false } as never, + }); + + const picker = render(); + const badge = render(); + await waitFor(() => expect(badge.container.querySelector('.bss-plan')?.textContent).toBe('Free')); + await waitFor(() => expect(planReads).toBe(1)); + const billingBefore = billingReads; + + serverPlans = [FREE, PRO, TEAM]; + serverBillingPlan = { slug: 'pro', name: 'Pro' }; + await act(async () => { + handlers[kind]({ kind, tenantId: 'ws-1', to: { slug: 'pro', name: 'Pro' }, status: 'active' }); + }); + + await waitFor(() => expect(picker.container.textContent).toContain('Team')); + await waitFor(() => expect(badge.container.querySelector('.bss-plan')?.textContent).toBe('Pro')); + expect(billingReads).toBeGreaterThan(billingBefore); + }); + } +}); + +describe('loadSubscription(): one read, retried once, never blanks the screen (TBP-762)', () => { + it('concurrent calls share one read, and a call during a read gets one more after it', async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const proto = BridgeAuth.prototype as unknown as Record; + spies.push( + spyOn(proto as never, 'getPlans' as never).mockImplementation((async () => { + planReads += 1; + await gate; + return [FREE, PRO]; + }) as never), + ); + const a = loadSubscription(); + const b = loadSubscription(); + const c = loadSubscription(); + release(); + await Promise.all([a, b, c]); + expect(planReads).toBe(2); + }); + + it('an empty plan list is asked for once more before it is believed', async () => { + let answers = [[], [FREE, PRO]]; + const proto = BridgeAuth.prototype as unknown as Record; + spies.push( + spyOn(proto as never, 'getPlans' as never).mockImplementation((async () => { + planReads += 1; + return answers.shift() ?? []; + }) as never), + ); + await loadSubscription(); + expect(planReads).toBe(2); + expect(useBridgeStore.getState().subscription.plans?.map((p) => p.key)).toEqual(['free', 'pro']); + answers = []; + }); + + it('a failed re-read keeps the last good plan list on screen, with no loading state', async () => { + await loadSubscription(); + expect(useBridgeStore.getState().subscription.plans).toHaveLength(2); + + plansFail = true; + const seenLoading: boolean[] = []; + const off = useBridgeStore.subscribe((s) => seenLoading.push(s.subscription.loading)); + await loadSubscription(); + off(); + + const sub = useBridgeStore.getState().subscription; + expect(sub.plans).toHaveLength(2); + expect(sub.error).toBeNull(); + expect(seenLoading.includes(true)).toBe(false); + expect(planReads).toBe(3); // the first read, then the failed re-read and its one retry + }); + + it('a first read that fails twice shows the error', async () => { + plansFail = true; + await loadSubscription(); + expect(planReads).toBe(2); + expect(useBridgeStore.getState().subscription.error).toBe('network down'); + }); + + it('an answer that arrives after sign-out is dropped', async () => { + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const proto = BridgeAuth.prototype as unknown as Record; + spies.push( + spyOn(proto as never, 'getPlans' as never).mockImplementation((async () => { + await gate; + return [FREE, PRO]; + }) as never), + ); + const read = loadSubscription(); + (getBridgeAuth() as unknown as { emitter: { emit(e: string, p?: unknown): void } }).emitter.emit('auth:logout'); + release(); + await read; + expect(useBridgeStore.getState().subscription.plans).toBeNull(); + }); +}); diff --git a/bridge-react/test/callback-redirect.test.tsx b/bridge-react/test/callback-redirect.test.tsx index 9c459d7..666fa9e 100644 --- a/bridge-react/test/callback-redirect.test.tsx +++ b/bridge-react/test/callback-redirect.test.tsx @@ -10,7 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { cleanup, render, waitFor } from '@testing-library/react'; import { CallbackHandler } from '../src/components/auth/CallbackHandler'; -import { _resetBridgeInstance, getBridgeAuth, initBridge } from '../src/core/bridge-instance'; +import { __setBillingRetryDelay, _resetBridgeInstance, getBridgeAuth, initBridge } from '../src/core/bridge-instance'; import { resetRouterAdapter, setRouterAdapter } from '../src/utils/router-adapter'; let replaceSpy: ReturnType; @@ -40,6 +40,7 @@ const HOSTILE: Array<[string, string]> = [ describe(' Stripe return redirect stays on origin', () => { beforeEach(() => { _resetBridgeInstance(); + __setBillingRetryDelay(0); // the fakes answer an empty plan list, which is retried once (TBP-762) initBridge({ appId: 'test-app' } as never); spies.push( spyOn(getBridgeAuth(), 'confirmStripeCheckout').mockImplementation((async () => undefined) as never), diff --git a/bridge-react/test/checkout-return-paywall.test.tsx b/bridge-react/test/checkout-return-paywall.test.tsx index 57b9253..bea9759 100644 --- a/bridge-react/test/checkout-return-paywall.test.tsx +++ b/bridge-react/test/checkout-return-paywall.test.tsx @@ -22,7 +22,7 @@ import { cleanup, render } from '@testing-library/react'; import { BridgeAuth } from '@nebulr-group/bridge-auth-core'; import { BridgeProvider } from '../src/providers/bridge-provider'; import { CallbackHandler } from '../src/components/auth/CallbackHandler'; -import { _resetBridgeInstance, confirmCheckout, initBridge } from '../src/core/bridge-instance'; +import { __setBillingRetryDelay, _resetBridgeInstance, confirmCheckout, initBridge } from '../src/core/bridge-instance'; import { __resetBridgeRuntime } from '../src/core/bridge-runtime'; import { resetRouterAdapter, setRouterAdapter } from '../src/utils/router-adapter'; @@ -87,6 +87,7 @@ async function until(cond: () => boolean, ms = 1000): Promise { const navigations = () => replaceSpy.mock.calls.map((c) => c[0] as string); beforeEach(() => { + __setBillingRetryDelay(0); // the fakes answer an empty plan list, which is retried once (TBP-762) originalLocation = window.location; serverHasPayment = false; confirmRecordsPlan = true; diff --git a/bridge-react/test/doc-currency.test.ts b/bridge-react/test/doc-currency.test.ts new file mode 100644 index 0000000..90a6f72 --- /dev/null +++ b/bridge-react/test/doc-currency.test.ts @@ -0,0 +1,310 @@ +// TBP-705 — the guides this repo serves to AI agents (mcp/, learning/, README.md, +// read from GitHub main by the Bridge MCP server) must not teach what the rule +// forbids. The owner's rule (2026-09-29): every gate in app code is a flag, and +// its rule says why — a privilege, a plan feature +// (`bridge:billing.entitlement. eq true`) or a rollout. App code never reads +// a role, a privilege list, the plan or a plan feature to decide what someone may +// see or do. Browser-only counting is a complete, first-class way to run limits. +// +// A sentence that tells the reader NOT to do it is allowed, and so is anything +// in the one section a guide may have whose heading says "Exceptions". +// +// The pattern list, the negation list and the Exceptions scoping MIRROR +// bridge-cli `src/gate-rules.ts` (DOC_FORBIDDEN / docGateViolations), which is +// the source of truth and also drives `bridge check gates`. Keep them the same: +// change it there first, then copy it here. +// +// Ported from bridge-svelte `src/doc-currency.test.ts` (TBP-705, TBP-763); keep +// the two in step. Lives in test/, outside the bundle. + +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; +import { describe, expect, it } from 'bun:test'; + +// ── Mirror of bridge-cli src/gate-rules.ts (docs part) ────────────────────── + +const DOC_FORBIDDEN: Array<[string, RegExp]> = [ + ['a role compared in code', /\b(?:user|session|claims|token|me|currentUser|profile|locals\.user|req\.user|\$user|\$profile)\??\.role\s*(?:===|!==|==|!=)/], + ['a role compared in code', /\brole\s*(?:===|!==|==|!=)\s*['"`]/i], + ['a role list checked in code', /\[\s*['"][A-Z_]+['"](?:\s*,\s*['"][A-Z_]+['"])*\s*\]\s*\.includes\(/], + ['a role checked in code', /\bhasRole\s*\(/], + ['a role decorator on a handler', /@RequireRole\s*\(/], + ['a role check on the page', /\brole check\b[^.\n]{0,30}\b(?:in|on) (?:the |your )?(?:page|component|code|handler|layout|controller)/i], + ['a role check on the page', /\bcheck\w*\b[^.\n]{0,30}\brole\b[^.\n]{0,30}\b(?:in|on) (?:the |your )?(?:page|component|code|layout)\b/i], + ['"target a role instead"', /target a role instead/i], + ['privileges read in code', /\bprivileges\s*\??\.\s*(?:includes|some|indexOf|has)\s*\(/], + ['a direct plan-feature check', / { + if (/^\s*(?:```|~~~)/.test(line)) inFence = !inFence; + const heading = inFence ? null : HEADING.exec(line); + if (heading) { + const level = heading[1].length; + if (exceptionLevel && level <= exceptionLevel) exceptionLevel = 0; + if (/exception/i.test(heading[2])) exceptionLevel = level; + return; + } + if (exceptionLevel) return; + for (const sentence of line.split(/(?<=[.!?])\s+/)) { + if (NEGATED.test(sentence)) continue; + for (const [rule, pattern] of DOC_FORBIDDEN) { + if (pattern.test(sentence)) out.push({ line: i + 1, rule, text: sentence.trim() }); + } + } + }); + return out; +} + +// ── This repo's agent-facing docs ─────────────────────────────────────────── + +const REPO = resolve(import.meta.dir, '../..'); + +function markdownFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return markdownFiles(path); + return name.endsWith('.md') ? [path] : []; + }); +} + +const read = (file: string) => readFileSync(file, 'utf8'); +const agentDocs = [ + ...markdownFiles(join(REPO, 'mcp')), + ...markdownFiles(join(REPO, 'learning')), + join(REPO, 'README.md'), + join(REPO, 'bridge-react', 'README.md'), +]; + +describe('no agent-facing guide teaches a direct role, privilege or plan check, or talks browser counting down — TBP-705', () => { + it('finds the guides (guards against scanning nothing)', () => { + expect(agentDocs.length).toBeGreaterThan(10); + expect(agentDocs).toContain(join(REPO, 'mcp', 'billing-prompt.md')); + }); + + it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => { + expect(docGateViolations(read(file))).toEqual([]); + }); + + // Owner 2026-09-29: the trust trade-off of browser counting belongs to human + // docs only. mcp/ and learning/ are served to agents; the README may say it once. + it('the browser-counting trust trade-off is not in mcp/ or learning/, and at most once in the README', () => { + const TRADE_OFF = /trusts the browser|could report less than/i; + const inAgentGuides = agentDocs + .filter((f) => f !== join(REPO, 'README.md')) + .filter((f) => TRADE_OFF.test(read(f))) + .map((f) => relative(REPO, f)); + expect(inAgentGuides).toEqual([]); + expect(read(join(REPO, 'README.md')).match(new RegExp(TRADE_OFF.source, 'gi'))?.length ?? 0).toBeLessThanOrEqual(1); + }); + + describe('goes red on a planted bad line', () => { + it.each([ + 'For admin-only pages, add a role check on the page: `if (user.role === "ADMIN")`.', + "Gate the page with `{#if $auth.user.role == 'ADMIN'}`.", + "Put `@RequireRole('ADMIN')` on the handler.", + 'Check the role in the component before rendering the button.', + "Show analytics when `tenant.plan === 'pro'`.", + "if (plan === 'pro') showAnalytics();", + 'const isPro = subscription.plan.key === "pro";', + '{ "conditions": [{ "attribute": "tenant.plan", "operator": "eq", "values": ["pro"] }] }', + 'Wrap the chart in ``.', + "Show the button when `$entitlements.can('exports')`.", + "Put `@RequireEntitlement('analytics')` on the handler.", + "const canManageTeam = ['OWNER', 'ADMIN'].includes(role);", + "Show the link when `privileges.includes('USER_WRITE')`.", + "{ path: '/reports/*', privilege: 'REPORTS_VIEW' }", + "{ path: '/reports/*', privilege: 'AUTHENTICATED', plans: ['pro'] }", + 'Browser counting is display, not enforcement.', + 'Only a backend can refuse a click over the limit.', + 'Offer "Browser only (demo-grade)" as the last option.', + 'A frontend-only app cannot enforce a limit.', + 'Counting in the browser is not production-ready.', + ])('%s', (bad) => { + expect(docGateViolations(bad)).not.toEqual([]); + }); + + it('and in a real guide file, not only in isolation', () => { + const planted = `${read(join(REPO, 'mcp', 'team-prompt.md'))}\nShow the Team link when \`['OWNER','ADMIN'].includes(role)\`.\n`; + const found = docGateViolations(planted); + expect(found.length).toBeGreaterThan(0); + for (const v of found) expect(v.text).toContain("['OWNER','ADMIN'].includes(role)"); + }); + }); + + describe("stays green on the rule's own sentences", () => { + it.each([ + '**Every gate in app code is a flag.** A link, a page, a button, an endpoint: if some people get it and others do not, the code asks a flag, and the flag\'s rule says why: a privilege (`privileges contains "USER_WRITE"`), a plan feature (`bridge:billing.entitlement.analytics eq true`) or a rollout.', + 'App code never reads a role, a privilege list, the plan or a plan feature to decide what someone may see or do.', + 'Control it with a flag rule, never with a role check written into the app\'s code.', + 'Never gate the Team link with `[\'OWNER\',\'ADMIN\'].includes(role)`.', + 'A role rule (`user.role eq "ADMIN"`) is fine when the developer means the role itself.', + "{ match: '/admin/*', featureFlag: 'admin-area', redirectTo: '/' }", + "{ path: '/health', privilege: 'ANONYMOUS' }", + 'Browser-only counting is a first-class, complete way to run limits.', + 'Never describe browser counting as demo-grade.', + ])('%s', (good) => { + expect(docGateViolations(good)).toEqual([]); + }); + + it('a direct plan-feature check inside the Exceptions section, and only there', () => { + const guide = [ + '## Gating', + 'Use ``.', + '## Exceptions', + 'When the developer asks for no flag, `` reads the plan directly.', + '### Details', + "`$entitlements.can('analytics')` is the same check in script.", + '## Next', + 'Wrap it in ``.', + ].join('\n'); + expect(docGateViolations(guide).map((v) => v.line)).toEqual([8]); + }); + }); +}); + +// ── TBP-763 — seats ───────────────────────────────────────────────────────── +// +// Owner decisions 2026-09-29: seats are a plan limit the app names (e.g. +// `seats`), kind gauge, counted by Bridge from membership (`--source +// membership`). There is no built-in `users` seat metric. The limit is enforced +// where invites start — `seatsMetric="seats"` on the built-in team page, or +// `@RequireQuota('seats')` on the app's own invite handler — because Bridge's +// invite API does not refuse at the limit. Never a flag or an entitlement. + +const SEAT_FORBIDDEN: Array<[string, RegExp]> = [ + ['`users` as the built-in seat metric', /\bseats?\b\**\s*\(\s*`(?:metric:\s*)?["']?users["']?`\s*\)/i], + ['`users` as the built-in seat metric', /@RequireQuota\(\s*['"]users['"]/], + ['`users` as the built-in seat metric', /--metric\s+users\b|"metric"\s*:\s*"users"|\bmetric:\s*["']users["']/], + ['seats gated with a flag or an entitlement', /\bseats?\b[^.\n]{0,60}(?: { + for (const sentence of line.split(/(?<=[.!?])\s+/)) { + if (NEGATED.test(sentence) || /\bno built-in\b/i.test(sentence)) continue; + for (const [rule, pattern] of SEAT_FORBIDDEN) { + if (pattern.test(sentence)) out.push({ line: i + 1, rule, text: sentence.trim() }); + } + } + }); + return out; +} + +const SEATS_CLI = 'bridge plan quota set --metric seats --limit N --policy hard --kind gauge --source membership'; + +describe('seats are a plan limit the app names, counted from membership — TBP-763', () => { + it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => { + expect(seatViolations(read(file))).toEqual([]); + }); + + it.each([['mcp/team-prompt.md'], ['mcp/billing-prompt.md']])('%s teaches the seat setup and both enforcement points', (file) => { + const guide = read(join(REPO, file)); + expect(guide).toContain(SEATS_CLI); + expect(guide).toContain('seatsMetric="seats"'); + expect(guide).toContain("@RequireQuota('seats')"); + expect(guide).toMatch(/invite API does not refuse at the limit/i); + expect(guide).toMatch(/built-in team page or the app's own invite handler|built-in team page, or the app's own invite handler/i); + expect(guide).toMatch(/never gate seats with a flag or an entitlement/i); + }); + + describe('goes red on a planted bad line', () => { + it.each([ + 'Seats (`metric: "users"`) are counted by Bridge from workspace members.', + '**Seats** (`users`) are a gauge Bridge keeps itself.', + "Put `@RequireQuota('users')` on your invite handler.", + 'bridge plan quota set free --metric users --limit 2 --policy hard', + 'Gate the invite button on seats with a flag rule.', + 'Put the seat count behind an entitlement.', + ])('%s', (bad) => { + expect(seatViolations(bad)).not.toEqual([]); + }); + }); + + describe('stays green on the guides’ own sentences', () => { + it.each([ + 'There is no built-in `users` metric.', + 'Never gate seats with a flag or an entitlement: a seat count is a limit.', + SEATS_CLI, + "`@RequireQuota('seats')` on that backend handler.", + ])('%s', (good) => { + expect(seatViolations(good)).toEqual([]); + }); + }); +}); + +// ── bridge-react: what the guides must say (TBP-705, TBP-576, TBP-642/675) ── + +describe('the guides open with the one rule and end with `check gates` — TBP-705', () => { + it.each([['mcp/billing-prompt.md'], ['mcp/feature-flags-prompt.md'], ['mcp/team-prompt.md']])('%s', (file) => { + const guide = read(join(REPO, file)); + const rule = guide.indexOf('## The one rule for app code'); + const firstOtherSection = guide.search(/^## (?!The one rule)/m); + expect(rule).toBeGreaterThan(-1); + expect(rule).toBeLessThan(firstOtherSection); // the first section, before "Decide first" + expect(guide).toContain('**Every gate in app code is a flag.**'); + expect(guide).toContain('npx @nebulr-group/bridge-cli check gates'); + }); + + it('the billing guide no longer says a paid feature must not be a flag', () => { + const guide = read(join(REPO, 'mcp', 'billing-prompt.md')); + expect(guide).not.toMatch(/entitlements are not feature flags/i); + expect(guide).not.toMatch(/gating a paid feature with a flag/i); + }); +}); + +describe('the flags guides name the MCP tools and do not steer agents to the CLI — TBP-576', () => { + it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => { + expect(read(file)).not.toMatch(/prefer the CLI/i); + }); + + it('mcp/feature-flags-prompt.md names the MCP tools for creating and flipping a flag', () => { + const guide = read(join(REPO, 'mcp', 'feature-flags-prompt.md')); + expect(guide).toContain('create_feature_flag'); + expect(guide).toContain('toggle_feature_flag'); + }); + + it('mcp/billing-prompt.md names the MCP tools for plans', () => { + const guide = read(join(REPO, 'mcp', 'billing-prompt.md')); + for (const tool of ['list_plans', 'create_plan', 'set_plan_quota', 'add_plan_feature']) expect(guide).toContain(tool); + }); +}); + +describe('live updates explain why they are off — TBP-642, TBP-675', () => { + it('learning/live-updates/live-updates.md documents the status reasons and links the troubleshooting page', () => { + const guide = read(join(REPO, 'learning', 'live-updates', 'live-updates.md')); + expect(guide).toContain('useRealtimeStatusDetail'); + for (const field of ['`reason`', '`side`', '`retrying`', '`docsUrl`', '`ref`']) expect(guide).toContain(field); + expect(guide).toContain('](/live-updates/troubleshooting/)'); + }); +}); diff --git a/bridge-react/test/guide-drift.test.ts b/bridge-react/test/guide-drift.test.ts new file mode 100644 index 0000000..cb9a9db --- /dev/null +++ b/bridge-react/test/guide-drift.test.ts @@ -0,0 +1,374 @@ +/** + * Guide drift — the guides this repo serves to AI agents (`mcp/`, `learning/`, + * the READMEs; the Bridge MCP server reads them from GitHub main) must only + * name things the package really has. An agent copies what a guide says: an + * import of an export that was renamed, a component that never shipped, or a + * prop or config option that does not exist turns into a build error or, worse, + * a silent no-op in the developer's app. + * + * What is checked, against the package's own TypeScript (no build needed): + * 1. every named import from `@nebulr-group/bridge-react` or one of its + * entries (`/flags`, `/react-router`, `/tanstack-router`) is exported by + * that entry; + * 2. every JSX tag in a code block or inline code is a component the package + * exports, a tag the guide defines itself, or one of the app/third-party + * names listed in NOT_OURS below; + * 3. every prop written on one of the package's components is a prop it + * takes; + * 4. every `useXxx` hook named in code is exported (or is React's or a + * router's, listed in NOT_OURS_HOOKS); + * 5. every `billing.