diff --git a/.github/workflows/docs-links.yml b/.github/workflows/docs-links.yml
index b712a39..2b46971 100644
--- a/.github/workflows/docs-links.yml
+++ b/.github/workflows/docs-links.yml
@@ -5,7 +5,7 @@ name: Docs links
on:
pull_request:
- branches: [main]
+ branches: [main, v1]
paths:
- "learning/**"
- "scripts/check-docs-links.mjs"
diff --git a/.github/workflows/e2e-guards.yml b/.github/workflows/e2e-guards.yml
index c545832..c0a4b2c 100644
--- a/.github/workflows/e2e-guards.yml
+++ b/.github/workflows/e2e-guards.yml
@@ -4,7 +4,7 @@ name: E2E guards
on:
pull_request:
- branches: [main]
+ branches: [main, v1]
push:
branches: [main]
diff --git a/.github/workflows/pr-gate.yml b/.github/workflows/pr-gate.yml
index 62373aa..f836e29 100644
--- a/.github/workflows/pr-gate.yml
+++ b/.github/workflows/pr-gate.yml
@@ -2,7 +2,7 @@ name: PR gate
on:
pull_request:
- branches: [main]
+ branches: [main, v1]
permissions:
contents: read
@@ -11,7 +11,7 @@ jobs:
gate:
uses: thebridgedev/auth-core/.github/workflows/merge-gate.yml@main
with:
- # bun workspace with a root bun.lock: frozen install.
- working-directory: .
- install-command: bun install --frozen-lockfile --ignore-scripts
+ # bun, no tracked lockfile: prove every pinned version resolves.
+ working-directory: bridge-react
+ install-command: bun install --ignore-scripts
setup-bun: true
diff --git a/.github/workflows/test-install.yml b/.github/workflows/test-install.yml
index 62f0e44..a12044a 100644
--- a/.github/workflows/test-install.yml
+++ b/.github/workflows/test-install.yml
@@ -1,9 +1,9 @@
-# Test that the packed package installs cleanly with React 18 and React 19
+# Test that the packed package installs and loads with React 18 and React 19
name: Test install
on:
pull_request:
- branches: [main]
+ branches: [main, v1]
push:
branches: [main]
@@ -26,39 +26,20 @@ jobs:
- name: Build and pack package
run: |
bun install
- bun run build
+ bun run build:bridge
bun run package
mv nebulr-group-bridge-react-*.tgz install-test-pkg.tgz
- # TBP-665 — the main entry and `/flags` must share one flag registry in
- # the BUILT output (a per-entry build gave each its own copy).
- - name: Built dist shares one flag registry
- run: cd bridge-react && bun test ./test-dist/shared-registry.dist.tsx
-
- name: Install with React ${{ matrix.react-version }}
run: |
mkdir -p install-test
cd install-test
npm init -y
+ npm pkg set type=module
npm install react@^${{ matrix.react-version }} react-dom@^${{ matrix.react-version }}
npm install ../install-test-pkg.tgz
echo "Install with react@${{ matrix.react-version }} succeeded"
- - name: Installed package shares one flag registry (ESM + CJS)
+ - name: The installed package loads
working-directory: install-test
- run: |
- cat > check.mjs <<'EOF'
- import { createRequire } from 'node:module';
- const require = createRequire(import.meta.url);
- const inst = { flag: () => ({ passed: true, value: true }) };
- const mainEsm = await import('@nebulr-group/bridge-react');
- const flagsEsm = await import('@nebulr-group/bridge-react/flags');
- mainEsm.setBridgeFlagsInstance(inst);
- const mainCjs = require('@nebulr-group/bridge-react');
- const flagsCjs = require('@nebulr-group/bridge-react/flags');
- mainCjs.setBridgeFlagsInstance(inst);
- const ok = flagsEsm.getBridgeFlagsInstance() === inst && flagsCjs.getBridgeFlagsInstance() === inst;
- console.log(ok ? 'shared registry: ok' : 'shared registry: SPLIT');
- process.exit(ok ? 0 : 1);
- EOF
- node check.mjs
+ run: node -e "import('@nebulr-group/bridge-react').then((m) => { if (typeof m.BridgeProvider !== 'function') process.exit(1); console.log('loads'); })"
diff --git a/.gitignore b/.gitignore
index f42fc69..255d79e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -78,3 +78,7 @@ project_descriptions/
# Environment files
.env
.env.*
+bun.lock
+
+# Playwright output
+test-results/
diff --git a/.lesshst b/.lesshst
deleted file mode 100644
index 4d1c30b..0000000
--- a/.lesshst
+++ /dev/null
@@ -1 +0,0 @@
-.less-history-file:
diff --git a/.npmignore b/.npmignore
deleted file mode 100644
index fa2a663..0000000
--- a/.npmignore
+++ /dev/null
@@ -1,44 +0,0 @@
-# Source files
-src/
-tsconfig.json
-rollup.config.js
-
-# Documentation
-*.md
-!README.md
-learning/
-DEMO_APP_PLAN.md
-DOCUMENTATION_SUMMARY.md
-IMPLEMENTATION_PLAN.md
-QUICK_REFERENCE.md
-
-# Development files
-node_modules/
-.git/
-.gitignore
-.npmignore
-
-# IDE
-.vscode/
-.idea/
-*.swp
-*.swo
-*~
-
-# OS
-.DS_Store
-Thumbs.db
-
-# Logs
-*.log
-npm-debug.log*
-yarn-debug.log*
-yarn-error.log*
-
-# Testing
-coverage/
-.nyc_output/
-
-# Example apps
-example-app/
-
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e644650..9941feb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,34 @@
# Changelog
+## [1.0.0-alpha.1] - unreleased
+
+Needs `@nebulr-group/bridge-auth-core` 1.0.0-alpha.8. A new major line, for the new Bridge: the React counterpart of `@nebulr-group/bridge-svelte` 1.0.0-alpha.8, with the same pages, settings and wording, so the guides of either package map to the other. `latest` stays on 0.x.
+
+### Changed (breaking)
+
+- **One setting, the issuer.** `` replaces the app id, API base and hosted-page addresses. Every endpoint is read from the issuer's metadata. The issuer must be `https`, except `http://localhost` on your own machine.
+- **Every security step lives in `@nebulr-group/bridge-auth-core`**: tokens, PKCE, email links, hand-off, storage and revocation. This package is the React layer over it.
+- **Router-agnostic.** `` takes your router's location and navigate function (React Router, TanStack Router, Wouter); without one it uses the browser's history. The `./react-router` and `./tanstack-router` entry points are gone.
+- **The `./flags` entry point is gone.** Everything is exported from the package root; the default look is `@nebulr-group/bridge-react/styles`.
+- **ESM only**, React 18 or 19.
+
+### Added
+
+- **``**: makes the page's client, sends email links to their pages, guards every navigation with route rules (`public`, `featureFlag` with `any`/`all`, `redirectTo`, `defaultAccess`), and guards again when the session or the flags change. Gates are flags, never roles. A signed-in workspace whose app is not active (`bridge-app-active` off) goes to the plan page.
+- **Sign-in pages from one route**: `} />` serves sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, handoff, magic-link, passkey-setup and callback. Components: `SignInForm` (password, sign-in link, passkeys, the workspace step), `SignUpForm` (also from an invite), `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `WorkspaceChooser`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `HostedSignIn` and `HostedCallback` (hosted mode), `HandoffSignIn` (hand-off mode), `SignOutButton`, `ProfileName`.
+- **A paused sign-in says how long to wait**: "Too many attempts. Try again in N minutes.", and a locked account says so, in each of the 12 languages.
+- **Session storage**: `storage: 'local'` (default) or `'memory'`, where the session never reaches the browser's storage and a sign-up's email link finishes in the tab that started it.
+- **Hooks**: `useSession`, `useUser`, `useSignedIn`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useFlag`, `useFlagsStatus`, `useCanManageBilling`, `useCanManageTeam`, `useBilling`, `usePlans`, `useUsage`, `useQuota`, `useLiveStatus`, `useBridge`, `useBridgeRouter`, `useTranslator`. Resources refresh when the person or workspace changes and within a second of a Live notice.
+- **Flags**: `` with `fallback` that learns whether the plan is why a feature is off, and an `upgrade` prompt; `requireFlag()` for code outside components.
+- **Billing**: `` on `/subscription/*`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `CheckoutNotice`, `QuotaBanner`, and the upgrade dialog a 402 from your API opens through `bridgeFetch`.
+- **The team panel**: `TeamPanel` with members, invites (send, resend, revoke), roles, the workspace and the profile, on Bridge's team endpoints; admin actions follow `bridge-team-manage`.
+- **Copy in 12 languages** (`locale`), with your own wording per key (`messages`).
+- **``**: an in-app link through your router, so a click does not reload the page.
+
+### Not in this alpha
+
+- Server helpers. React has no server side; an API checks the person's token with `@nebulr-group/bridge-auth-core/server`, or the Express and NestJS plugins.
+
## [0.9.1] - 2026-11-10
### Fixed
diff --git a/README.md b/README.md
index b6e5899..6c3f0c7 100644
--- a/README.md
+++ b/README.md
@@ -16,177 +16,99 @@
# The Bridge for React
-`@nebulr-group/bridge-react` adds sign-in, workspaces and roles, feature flags, Stripe subscriptions and plan limits to a React app, with React Router or TanStack Router.
+`@nebulr-group/bridge-react` adds sign-in in your own pages, workspaces, flag-based route guards, plans and checkout, the team panel and live updates to a React 18 or 19 app, with one `.env` line, a provider and two routes. It works with React Router, TanStack Router, Wouter or no router at all.
-**[The Bridge](https://thebridge.dev/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)** is a hosted backend for SaaS apps. It gives you sign-in (passwords, magic links, passkeys, social login and SSO), multi-tenant workspaces with roles, Stripe subscriptions with plan limits, and feature flags, all managed from one dashboard. Your AI coding assistant can set it up for you through the [Bridge MCP server](https://thebridge.dev/docs/ai-assistants/mcp/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react).
+> **This is the 1.0 alpha**, built on `@nebulr-group/bridge-auth-core` 1.0 and the new Bridge API. It installs from the `alpha` tag; `latest` stays on 0.x until 1.0.0. It runs in the browser and signs people in with email and password, sign-in links and passkeys. Its components, props and settings match `@nebulr-group/bridge-svelte` 1.0.
-> **Let your AI assistant set it up.** Connect the [Bridge MCP server](https://thebridge.dev/docs/ai-assistants/mcp/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react) to Claude, Cursor, Copilot or Gemini CLI and ask it to add Bridge to your app. Not using MCP? Run `npx @nebulr-group/bridge-cli guide add-login` in your project: it detects your framework from `package.json` and prints the steps for your assistant to follow. `npx @nebulr-group/bridge-cli doctor` checks the result.
+**[The Bridge](https://thebridge.dev/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)** is a hosted backend for SaaS apps: sign-in, multi-tenant workspaces, Stripe subscriptions with plan limits, and feature flags, managed from one dashboard.
-## Quick links
-- [Quickstart Guide](learning/quickstart/quickstart.md) – Get started quickly with Bridge in your React app
-- [Examples](learning/examples/examples.md) – Detailed examples of Bridge features
+## Install
-## Table of contents
-- [Installation](#installation)
-- [Configuration](#configuration)
-- [Authentication](#authentication)
-- [Feature Flags](#feature-flags)
-- [Demo Application](#demo-application)
-- [E2E Tests](#e2e-tests)
-- [Publishing & Release](#publishing--release)
-- [Contributing](#contributing)
-- [License](#license)
-
-## Installation
-
-```bash
-bun add @nebulr-group/bridge-react
-# or
-npm install @nebulr-group/bridge-react
+```sh
+npm install @nebulr-group/bridge-react@alpha
```
-## Configuration
-
-The whole integration, with React Router. Every page Bridge needs, it serves.
+## The whole integration
-```env
-# .env — a production app needs only the first line
-VITE_BRIDGE_APP_ID=your-app-id
-VITE_BRIDGE_API_BASE_URL=https://api-stage.thebridge.dev # stage / local only
-```
-
-```tsx
-// main.tsx
-import { BridgeProvider } from '@nebulr-group/bridge-react';
-import '@nebulr-group/bridge-react/styles';
-
-createRoot(document.getElementById('root')!).render(
-
-
-
-);
+```sh
+# .env: the issuer from your app's settings in Bridge
+VITE_BRIDGE_ISSUER=https://…/identity-access/apps/
```
```tsx
-// App.tsx
-import { BridgeAuthRoutes, BridgeBillingRoutes } from '@nebulr-group/bridge-react/react-router';
-
-
- } /> {/* every sign-in page */}
- } /> {/* plans, paywall, checkout returns */}
- …your routes…
-
+// src/App.tsx, inside ; import '@nebulr-group/bridge-react/styles' once in main.tsx
+import { BridgeAuthRoutes, BridgeProvider, type BridgeConfig } from '@nebulr-group/bridge-react';
+import { Route, Routes, useLocation, useNavigate } from 'react-router';
+
+const config: BridgeConfig = {
+ issuer: import.meta.env.VITE_BRIDGE_ISSUER,
+ rules: [{ match: '/', public: true }],
+};
+
+export function App() {
+ const location = useLocation();
+ const navigate = useNavigate();
+ return (
+ void navigate(to, options) }}>
+
+ } />
+ } />
+
+
+ );
+}
```
-TanStack Router: `createRoute({ getParentRoute: () => rootRoute, path: 'auth/$', component: BridgeAuthRoutes })` with the components from `@nebulr-group/bridge-react/tanstack-router`. Both routers are optional peer dependencies; install only the one you use. Without a router, `` reads `window.location`.
-
-**Settings resolve as explicit option > environment > default.** An empty variable counts as unset.
-
-| Vite | Create React App | When to set it |
-|---|---|---|
-| `VITE_BRIDGE_APP_ID` | `REACT_APP_BRIDGE_APP_ID` | Always. Missing, Bridge refuses to start and names the variable |
-| `VITE_BRIDGE_API_BASE_URL` | `REACT_APP_BRIDGE_API_BASE_URL` | Only for a non-production app. Unset means production |
-| `VITE_BRIDGE_HOSTED_URL` | `REACT_APP_BRIDGE_HOSTED_URL` | Only for a local or self-hosted Bridge; on Bridge's domains it follows the API address |
-| `VITE_BRIDGE_DEBUG` | `REACT_APP_BRIDGE_DEBUG` | `true` for console logging |
-
-`callbackUrl`, `defaultRedirectRoute` and `loginRoute` can also come from `…_BRIDGE_CALLBACK_URL`, `…_BRIDGE_DEFAULT_REDIRECT_ROUTE` and `…_BRIDGE_LOGIN_ROUTE`. Everything else (`billing`, `locale`, `messages`, `returnTo`, `devBadge`) is set on the `config` prop.
-
-Customising Bridge's pages, lowest rung first: `--bridge-*` CSS tokens; `frame(page, children)` and `heading(page)` render props; taking over one page by passing an element (` }} />`); or headless on `getBridgeAuth()`. Plan limits need no page code: a `402 QUOTA_EXCEEDED` from your backend opens the upgrade dialog `` mounts; `` and `useQuota(metric)` are the next two levels. The rules are on one page: [learning/mechanisms.md](learning/mechanisms.md).
-
-## Authentication
+In your app's settings in Bridge, add your app's address as a browser address and `https:///auth` as its email-links address. See the [Quickstart](learning/quickstart/quickstart.md).
-See:
-- Quickstart – authentication: `learning/quickstart/quickstart.md#authentication`
-- Examples – authentication: `learning/examples/examples.md#authentication`
+## What it gives you
-The library provides:
-- Login and logout helpers
-- Protected route patterns
-- Automatic token renewal
-- Access to user profile information
-
-## Feature Flags
+| Area | Pieces |
+|---|---|
+| Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, magic-link, passkey-setup, handoff, callback), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
+| Gates | route `rules`, `FeatureFlag`, `useFlag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
+| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `bridgeFetch` |
+| Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `ConfirmDialog`, `WorkspaceForm`, `ProfileForm` |
+| State | `useSession`, `useUser`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useBilling`, `usePlans`, `useUsage`, `useLiveStatus`, `getBridge()` |
+| Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
+| Hosted mode | `hosted: {}` in the config: `/auth/sign-in` sends people to the page Bridge hosts for the app, and `/auth/callback` (`HostedCallback`) finishes the sign-in when they come back. Register the page's origin as a browser address and `https:///auth/callback` as a sign-in return |
+| Several sign-in pages | `linkAddress` in the config: which of the app's registered email-links addresses its emails link to |
-See:
-- Examples – Feature Flags: `learning/examples/examples.md#feature-flags`
+There is no server side in this package: your API checks tokens with `@nebulr-group/bridge-auth-core/server`, or with The Bridge's Express or NestJS plugin.
-Supported patterns:
-- Client-side flag checks and conditional rendering
-- Negation for inverse conditions
-- Cached vs live flag checks
-- Route protection using flags
+All the guides: [learning/](learning/README.md).
-## Demo Application
+## Demo application
-The demo app contains runnable examples mirroring the docs.
+`demo/` is a small helpdesk on the plugin (Vite and React Router), and what the Playwright suite drives. It imports the plugin from source.
-```bash
-# From repo root
+```sh
+# in a container, from the repo root
bun install
-bun run dev
+VITE_BRIDGE_ISSUER=https://…/identity-access/apps/ bun run dev
```
-The demo showcases:
-- Feature flags
-- Team management
-- Authentication flows
-- Payment and subscription patterns
-- Integration examples
-
-## E2E Tests
-
-E2E tests use Playwright. Run them from the repo root.
-
-1. **Configure env:** Copy `config/.env.test.local.example` to `config/.env.test.local` and fill in the values (test data API key, etc.).
-2. **Pre-setup:** The first step of `test:e2e` runs a pre-setup script that creates/gets the test app and writes `VITE_BRIDGE_APP_ID` into `demo/.env.test.local` so the demo starts with the correct app.
-3. **Install browsers (once):** `bunx playwright install`
-4. **Run tests:**
- - `bun run test:e2e` — local (starts demo on port 3001, runs Playwright)
- - `bun run test:e2e:stage` — stage
- - `bun run test:e2e:prod` — prod
- - `bun run test:e2e:headed` — local with browser visible
- - `bun run test:e2e:report` — open last HTML report
-
-## Publishing & Release
+## End-to-end tests (Playwright)
-Bridge React is published to npm via GitHub Actions.
+```sh
+bunx playwright test
+```
-### Releasing a new version
-1. Update the version in `bridge-react/bridge-react/package.json`
-2. Commit and push your changes
-3. Create a PR and merge into `main`
-4. Tag the release using semantic versioning (`vX.Y.Z`):
+By default the suite starts a local issuer (`e2e/harness/fake-issuer.ts`: auth-core's fake issuer over HTTP, with a small control API the tests use to set the scene) and the demo pointed at it, and runs every spec one at a time. To run against a real issuer, a local Bridge or a stage:
-```bash
-git tag v0.1.0
-git push origin v0.1.0
+```sh
+E2E_ISSUER=https://…/identity-access/apps/ bunx playwright test
```
-## Contributing
-
-Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
+`E2E_BASE_URL` points at a demo that is already running. Steps that set the scene (making people, setting flags, reading emailed links) need the local issuer; against a real issuer those specs are skipped or say what is missing.
-## Learn more
+## Publishing and releases
-- [Quickstart](https://thebridge.dev/docs/quickstart/react/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
-- [Authentication](https://thebridge.dev/docs/auth/react/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
-- [Sign-in inside your app](https://thebridge.dev/docs/sdk-auth/react/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
-- [Feature flags](https://thebridge.dev/docs/feature-flags/react/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
-- [Branding](https://thebridge.dev/docs/branding/react/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
-- [Live updates](https://thebridge.dev/docs/live-updates/react/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
-- [Subscriptions and plan limits](https://thebridge.dev/docs/billing/how-it-works/?utm_source=github&utm_medium=readme&utm_campaign=bridge-react)
+The 1.0 line lives on the `v1` branch and is published as `1.0.0-alpha.N` on the `alpha` tag. `main` stays on 0.x.
-## Other Bridge packages
+## Contributing
-| Package | For |
-|---|---|
-| [`@nebulr-group/bridge-svelte`](https://www.npmjs.com/package/@nebulr-group/bridge-svelte) | SvelteKit |
-| [`@nebulr-group/bridge-nextjs`](https://www.npmjs.com/package/@nebulr-group/bridge-nextjs) | Next.js |
-| [`@nebulr-group/bridge-angular`](https://www.npmjs.com/package/@nebulr-group/bridge-angular) | Angular |
-| [`@nebulr-group/bridge-nestjs`](https://www.npmjs.com/package/@nebulr-group/bridge-nestjs) | NestJS |
-| [`@nebulr-group/bridge-express`](https://www.npmjs.com/package/@nebulr-group/bridge-express) | Express |
-| [`@nebulr-group/bridge-cli`](https://www.npmjs.com/package/@nebulr-group/bridge-cli) | CLI for people and AI agents |
-| [`@nebulr-group/bridge-auth-core`](https://www.npmjs.com/package/@nebulr-group/bridge-auth-core) | Any JavaScript app (core) |
+See the [Contributing Guide](CONTRIBUTING.md).
## License
diff --git a/bridge-react.code-workspace b/bridge-react.code-workspace
deleted file mode 100644
index 7012ccd..0000000
--- a/bridge-react.code-workspace
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "folders": [
- {
- "path": "."
- },
- {
- "path": "../bridge-nextjs"
- },
- {
- "path": "../../../../my-react-app"
- }
- ],
- "settings": {}
-}
\ No newline at end of file
diff --git a/bridge-react/README.md b/bridge-react/README.md
index 3cade1f..f0b581d 100644
--- a/bridge-react/README.md
+++ b/bridge-react/README.md
@@ -16,69 +16,67 @@
# The Bridge for React
-`@nebulr-group/bridge-react` adds sign-in, workspaces and roles, feature flags, Stripe subscriptions and plan limits to a React app, with React Router or TanStack Router.
+`@nebulr-group/bridge-react` adds sign-in in your own pages, workspaces, flag-based route guards, plans and checkout, the team panel and live updates to a React 18 or 19 app, with one `.env` line, a provider and two routes. It works with React Router, TanStack Router, Wouter or no router at all.
-**[The Bridge](https://thebridge.dev/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)** is a hosted backend for SaaS apps. It gives you sign-in (passwords, magic links, passkeys, social login and SSO), multi-tenant workspaces with roles, Stripe subscriptions with plan limits, and feature flags, all managed from one dashboard. Your AI coding assistant can set it up for you through the [Bridge MCP server](https://thebridge.dev/docs/ai-assistants/mcp/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react).
+> **This is the 1.0 alpha**, built on `@nebulr-group/bridge-auth-core` 1.0 and the new Bridge API. It installs from the `alpha` tag; `latest` stays on 0.x until 1.0.0. It runs in the browser and signs people in with email and password, sign-in links and passkeys. Its components, props and settings match `@nebulr-group/bridge-svelte` 1.0.
-> **Let your AI assistant set it up.** Connect the [Bridge MCP server](https://thebridge.dev/docs/ai-assistants/mcp/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react) to Claude, Cursor, Copilot or Gemini CLI and ask it to add Bridge to your app. Not using MCP? Run `npx @nebulr-group/bridge-cli guide add-login` in your project: it detects your framework from `package.json` and prints the steps for your assistant to follow. `npx @nebulr-group/bridge-cli doctor` checks the result.
+**[The Bridge](https://thebridge.dev/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)** is a hosted backend for SaaS apps: sign-in, multi-tenant workspaces, Stripe subscriptions with plan limits, and feature flags, managed from one dashboard.
## Install
-```bash
-npm install @nebulr-group/bridge-react @nebulr-group/bridge-auth-core
+```sh
+npm install @nebulr-group/bridge-react@alpha
```
## The whole integration
-```env
-VITE_BRIDGE_APP_ID=your-app-id
+```sh
+# .env: the issuer from your app's settings in Bridge
+VITE_BRIDGE_ISSUER=https://…/identity-access/apps/
```
```tsx
-// main.tsx
-import { BridgeProvider } from '@nebulr-group/bridge-react';
-import '@nebulr-group/bridge-react/styles';
-
-
-
-
-```
-
-```tsx
-// App.tsx — React Router
-import { BridgeAuthRoutes, BridgeBillingRoutes } from '@nebulr-group/bridge-react/react-router';
-
-} />
-} />
+// src/App.tsx, inside ; import '@nebulr-group/bridge-react/styles' once in main.tsx
+import { BridgeAuthRoutes, BridgeProvider, type BridgeConfig } from '@nebulr-group/bridge-react';
+import { Route, Routes, useLocation, useNavigate } from 'react-router';
+
+const config: BridgeConfig = {
+ issuer: import.meta.env.VITE_BRIDGE_ISSUER,
+ rules: [{ match: '/', public: true }],
+};
+
+export function App() {
+ const location = useLocation();
+ const navigate = useNavigate();
+ return (
+ void navigate(to, options) }}>
+
+ } />
+ } />
+
+
+ );
+}
```
-TanStack Router: import the same components from `@nebulr-group/bridge-react/tanstack-router` and mount them on `auth/$` and `subscription/$` routes. The routers are optional peer dependencies.
-
-Options you pass win over `VITE_BRIDGE_*` / `REACT_APP_BRIDGE_*`, which win over the defaults. Take over any one page by passing an element (`pages={{ login: }}`); restyle everything with the `--bridge-*` CSS tokens.
-
-How the pieces fit together: [How Bridge works](https://github.com/thebridgedev/bridge-react/blob/main/learning/mechanisms.md).
-
-## Learn more
-
-- [Quickstart](https://thebridge.dev/docs/quickstart/react/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
-- [Authentication](https://thebridge.dev/docs/auth/react/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
-- [Sign-in inside your app](https://thebridge.dev/docs/sdk-auth/react/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
-- [Feature flags](https://thebridge.dev/docs/feature-flags/react/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
-- [Branding](https://thebridge.dev/docs/branding/react/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
-- [Live updates](https://thebridge.dev/docs/live-updates/react/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
-- [Subscriptions and plan limits](https://thebridge.dev/docs/billing/how-it-works/?utm_source=npm&utm_medium=readme&utm_campaign=bridge-react)
+In your app's settings in Bridge, add your app's address as a browser address and `https:///auth` as its email-links address. See the [Quickstart](https://github.com/thebridgedev/bridge-react/blob/v1/learning/quickstart/quickstart.md).
-## Other Bridge packages
+## What it gives you
-| Package | For |
+| Area | Pieces |
|---|---|
-| [`@nebulr-group/bridge-svelte`](https://www.npmjs.com/package/@nebulr-group/bridge-svelte) | SvelteKit |
-| [`@nebulr-group/bridge-nextjs`](https://www.npmjs.com/package/@nebulr-group/bridge-nextjs) | Next.js |
-| [`@nebulr-group/bridge-angular`](https://www.npmjs.com/package/@nebulr-group/bridge-angular) | Angular |
-| [`@nebulr-group/bridge-nestjs`](https://www.npmjs.com/package/@nebulr-group/bridge-nestjs) | NestJS |
-| [`@nebulr-group/bridge-express`](https://www.npmjs.com/package/@nebulr-group/bridge-express) | Express |
-| [`@nebulr-group/bridge-cli`](https://www.npmjs.com/package/@nebulr-group/bridge-cli) | CLI for people and AI agents |
-| [`@nebulr-group/bridge-auth-core`](https://www.npmjs.com/package/@nebulr-group/bridge-auth-core) | Any JavaScript app (core) |
+| Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, magic-link, passkey-setup, handoff, callback), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
+| Gates | route `rules`, `FeatureFlag`, `useFlag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
+| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `bridgeFetch` |
+| Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `ConfirmDialog`, `WorkspaceForm`, `ProfileForm` |
+| State | `useSession`, `useUser`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useBilling`, `usePlans`, `useUsage`, `useLiveStatus`, `getBridge()` |
+| Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
+| Hosted mode | `hosted: {}` in the config: `/auth/sign-in` sends people to the page Bridge hosts for the app, and `/auth/callback` (`HostedCallback`) finishes the sign-in when they come back. Register the page's origin as a browser address and `https:///auth/callback` as a sign-in return |
+| Several sign-in pages | `linkAddress` in the config: which of the app's registered email-links addresses its emails link to |
+
+There is no server side in this package: your API checks tokens with `@nebulr-group/bridge-auth-core/server`, or with The Bridge's Express or NestJS plugin.
+
+All the guides: [the learning docs](https://github.com/thebridgedev/bridge-react/tree/v1/learning).
## License
diff --git a/bridge-react/bunfig.toml b/bridge-react/bunfig.toml
deleted file mode 100644
index e437022..0000000
--- a/bridge-react/bunfig.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-[test]
-preload = ["./test/happydom.setup.ts"]
diff --git a/bridge-react/package.json b/bridge-react/package.json
index e23770b..0015c32 100644
--- a/bridge-react/package.json
+++ b/bridge-react/package.json
@@ -1,119 +1,83 @@
{
- "name": "@nebulr-group/bridge-react",
- "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",
- "types": "dist/index.d.ts",
- "exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "import": "./dist/index.esm.js",
- "require": "./dist/index.cjs.js",
- "default": "./dist/index.cjs.js"
- },
- "./flags": {
- "types": "./dist/flags/index.d.ts",
- "import": "./dist/flags/index.esm.js",
- "require": "./dist/flags/index.cjs.js",
- "default": "./dist/flags/index.cjs.js"
- },
- "./react-router": {
- "types": "./dist/react-router/index.d.ts",
- "import": "./dist/react-router/index.esm.js",
- "require": "./dist/react-router/index.cjs.js",
- "default": "./dist/react-router/index.cjs.js"
- },
- "./tanstack-router": {
- "types": "./dist/tanstack-router/index.d.ts",
- "import": "./dist/tanstack-router/index.esm.js",
- "require": "./dist/tanstack-router/index.cjs.js",
- "default": "./dist/tanstack-router/index.cjs.js"
- },
- "./styles": "./dist/styles.css"
- },
- "license": "MIT",
- "author": "Iman Pouya",
- "files": [
- "dist/",
- "LICENSE",
- "README.md"
- ],
- "repository": {
- "type": "git",
- "url": "https://github.com/thebridgedev/bridge-react"
- },
- "bugs": {
- "url": "https://github.com/thebridgedev/bridge-react/issues"
- },
- "homepage": "https://thebridge.dev/docs/quickstart/react/",
- "scripts": {
- "build": "rm -rf ./dist && rollup -c --bundleConfigAsCjs && bun run copy-styles",
- "build:watch": "rollup -c --bundleConfigAsCjs --watch",
- "copy-styles": "cp src/styles.css dist/styles.css",
- "test": "bun test",
- "test:dist": "bun run build && bun test ./test-dist/shared-registry.dist.tsx",
- "prepublishOnly": "bun run build",
- "prepack": "bun run build && bun run copy-files",
- "copy-files": "cp ../LICENSE ./LICENSE",
- "publish-package": "bun run build && bun run copy-files && bunx npm publish --access public"
- },
- "keywords": [
- "react",
- "react-router",
- "tanstack-router",
- "passkeys",
- "magic-link",
- "the-bridge",
- "bridge",
- "authentication",
- "auth",
- "login",
- "sso",
- "feature-flags",
- "stripe",
- "subscriptions",
- "billing",
- "plan-limits",
- "multi-tenant",
- "rbac",
- "saas"
- ],
- "peerDependencies": {
- "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
- "@nebulr-group/bridge-auth-core": ">=0.8.0 <1.0.0",
- "react-router": ">=6.4.0 <8.0.0",
- "@tanstack/react-router": "^1.0.0"
- },
- "peerDependenciesMeta": {
- "react-router": {
- "optional": true
- },
- "@tanstack/react-router": {
- "optional": true
- }
- },
- "dependencies": {
- "@simplewebauthn/browser": "^13.0.0",
- "jose": "^6.0.10",
- "jwt-decode": "^4.0.0",
- "zustand": "^4.5.0"
- },
- "devDependencies": {
- "@happy-dom/global-registrator": "^20.10.6",
- "@nebulr-group/bridge-auth-core": "0.8.0",
- "@rollup/plugin-terser": "^0.4.4",
- "@rollup/plugin-typescript": "^11.1.6",
- "@tanstack/react-router": "^1",
- "@testing-library/dom": "^10.4.1",
- "@testing-library/react": "^16.3.2",
- "@types/node": "^24.9.2",
- "@types/react": "^18.2.0",
- "happy-dom": "^20.10.6",
- "react-router": "^6.28.0",
- "rollup": "^4.14.1",
- "tslib": "^2.6.2",
- "typescript": "^5.4.0"
- }
+ "name": "@nebulr-group/bridge-react",
+ "version": "1.0.0-alpha.1",
+ "description": "The Bridge for React: sign-in in your own pages, workspaces, flag-based route guards, plans and checkout, the team panel and live updates, on one setting: the issuer.",
+ "author": "Iman Pouya",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/thebridgedev/bridge-react.git"
+ },
+ "bugs": {
+ "url": "https://github.com/thebridgedev/bridge-react/issues"
+ },
+ "homepage": "https://thebridge.dev/docs/quickstart/react/",
+ "type": "module",
+ "main": "./dist/index.js",
+ "module": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js",
+ "default": "./dist/index.js"
+ },
+ "./styles": {
+ "types": "./dist/styles.d.ts",
+ "import": "./dist/styles.css",
+ "default": "./dist/styles.css"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "dist",
+ "!dist/**/*.test.*",
+ "README.md",
+ "LICENSE"
+ ],
+ "sideEffects": [
+ "**/*.css"
+ ],
+ "scripts": {
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/styles.css src/styles.d.ts dist/",
+ "check": "tsc -p tsconfig.json --noEmit",
+ "test:unit": "vitest run",
+ "prepack": "bun run build && cp ../LICENSE ./LICENSE",
+ "package": "bun run prepack && bun pm pack --destination ../"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0"
+ },
+ "dependencies": {
+ "@nebulr-group/bridge-auth-core": "1.0.0-alpha.8"
+ },
+ "devDependencies": {
+ "@testing-library/react": "^16.3.0",
+ "@types/react": "^19.0.0",
+ "@types/react-dom": "^19.0.0",
+ "jose": "^6.2.3",
+ "jsdom": "^26.1.0",
+ "react": "^19.0.0",
+ "react-dom": "^19.0.0",
+ "typescript": "^5.9.0",
+ "vitest": "^4.1.4"
+ },
+ "keywords": [
+ "react",
+ "the-bridge",
+ "bridge",
+ "authentication",
+ "auth",
+ "sign-in",
+ "passkeys",
+ "magic-link",
+ "feature-flags",
+ "stripe",
+ "subscriptions",
+ "billing",
+ "multi-tenant",
+ "workspaces",
+ "saas"
+ ]
}
diff --git a/bridge-react/rollup.config.js b/bridge-react/rollup.config.js
deleted file mode 100644
index 2d79850..0000000
--- a/bridge-react/rollup.config.js
+++ /dev/null
@@ -1,68 +0,0 @@
-import terser from "@rollup/plugin-terser";
-import typescript from "@rollup/plugin-typescript";
-
-const external = [
- "react",
- "react-dom",
- "react/jsx-runtime",
- "jwt-decode",
- "zustand",
- "jose",
- "@nebulr-group/bridge-auth-core",
- // Optional peer — dynamically imported by only for hosted
- // Stripe Checkout. Consumers install it themselves; keep it external.
- "@stripe/stripe-js",
- // Passkey ceremonies (TBP-743 / TBP-515 S3): a regular dependency, loaded
- // on first use.
- "@simplewebauthn/browser",
- // Optional peers (TBP-743) — only the router-adapter entries import them, so
- // an app without that router never resolves them.
- "react-router",
- "@tanstack/react-router",
-];
-
-// ONE build with both entries (TBP-665). The main entry (auth + payments +
-// flags, full surface) and the flags-only entry
-// (`@nebulr-group/bridge-react/flags`, auth-free, TBP-200) used to be two
-// separate rollup configs, so each bundle inlined its own copy of every module
-// they share — including the flag registry and the runtime's status stores.
-// `` registered the flag instance in the main copy, and a
-// `useFlag` imported from `/flags` read the other copy and returned the
-// default forever. Built together, shared modules land in `dist/chunks/` and
-// both entries import the same instance. The `/flags` entry still pulls in
-// only the modules it reaches, so it stays auth-free.
-//
-// Entry file names are unchanged, so package.json `main` / `module` /
-// `exports` resolve exactly as before.
-export default {
- input: {
- index: "src/index.ts",
- "flags/index": "src/flags/index.ts",
- // Router adapters (TBP-743): separate entries, so neither router is a
- // dependency of the main entry.
- "react-router/index": "src/react-router/index.tsx",
- "tanstack-router/index": "src/tanstack-router/index.tsx",
- },
- output: [
- {
- dir: "dist",
- format: "cjs",
- entryFileNames: "[name].cjs.js",
- chunkFileNames: "chunks/[name]-[hash].cjs.js",
- exports: "named",
- },
- {
- dir: "dist",
- format: "es",
- entryFileNames: "[name].esm.js",
- chunkFileNames: "chunks/[name]-[hash].esm.js",
- },
- ],
- plugins: [
- typescript({
- tsconfig: "./tsconfig.json",
- }),
- terser(),
- ],
- external,
-};
diff --git a/bridge-react/src/client/hooks/use-bridge.ts b/bridge-react/src/client/hooks/use-bridge.ts
deleted file mode 100644
index e964f5e..0000000
--- a/bridge-react/src/client/hooks/use-bridge.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-
-/**
- * Live Channel Unification (TBP-288/320) — `useBridge()` hook.
- *
- * Ported from bridge-svelte's `core/use-bridge.ts`. Svelte's version reads from
- * Svelte context with a singleton fallback; React has no equivalent ambient
- * context for the bridge surface, so this hook returns the module-level
- * singleton `bridge` (per the §5.4 export map: "functions/surface on the
- * singleton"). The object identity is stable, so returning it from a hook is
- * render-safe.
- *
- * Naming note: auth-core also exports a `useBridge` (the billing/quota factory).
- * bridge-nextjs's `useBridge()` is the unified read surface; consumers who want
- * the auth-core factory should import it directly from
- * `@nebulr-group/bridge-auth-core` as `useBridge` (aliased there).
- */
-import { bridge, type BridgeSurface } from '../../core/bridge';
-
-/**
- * Return the unified bridge surface (`bridge.app` / `bridge.tenant` /
- * `bridge.user` / `bridge.attributes` / `bridge.events`). Safe to call from any
- * component or plain module.
- */
-export function useBridge(): BridgeSurface {
- return bridge;
-}
diff --git a/bridge-react/src/client/tracking/pii-hashing.ts b/bridge-react/src/client/tracking/pii-hashing.ts
deleted file mode 100644
index 579b14d..0000000
--- a/bridge-react/src/client/tracking/pii-hashing.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Client-side PII hashing for ad-platform advanced matching.
- *
- * Normalization MUST match the server-side util at
- * `bridge-api/microservices/account/nebulr-api/utils/pii-hashing.util.ts`:
- * trim → lowercase → SHA-256 → hex.
- *
- * Any divergence between client and server hashing silently hurts match rates.
- * Tests must assert byte-identical output across both sides for the same input.
- */
-
-export async function sha256Email(
- email: string | null | undefined
-): Promise {
- if (!email) return undefined;
- const normalized = email.trim().toLowerCase();
- if (!normalized) return undefined;
- return sha256Hex(normalized);
-}
-
-async function sha256Hex(input: string): Promise {
- if (typeof globalThis.crypto?.subtle?.digest !== 'function') {
- // SSR / non-browser context without WebCrypto — skip hashing.
- // Callers treat undefined as "advanced matching unavailable" and fall back to plain pixel.
- return undefined as unknown as string;
- }
- const encoder = new TextEncoder();
- const data = encoder.encode(input);
- const buf = await globalThis.crypto.subtle.digest('SHA-256', data);
- return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
-}
diff --git a/bridge-react/src/client/tracking/reddit-tracking.ts b/bridge-react/src/client/tracking/reddit-tracking.ts
deleted file mode 100644
index 62c3ba9..0000000
--- a/bridge-react/src/client/tracking/reddit-tracking.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-/**
- * Reddit / GA4 conversion tracking via GTM dataLayer.
- *
- * Emits standard events (SignUp, Lead, PageVisit, Purchase) with optional
- * advanced-matching (hashed email) and a shared `conversion_id` that pairs
- * with server-side CAPI events for Reddit's deduplication.
- *
- * Ported verbatim from bridge-svelte — the hashing rules and dataLayer
- * contract must stay consistent across all framework plugins so the same
- * GTM setup works regardless of which plugin the consuming app uses.
- *
- * GTM-side: tags MUST read the `conversion_id` dataLayer variable and forward
- * it to the Reddit Pixel tag as the event dedup key. Same for
- * `user_data.email_address` (advanced matching).
- */
-
-export type RedditConversionEvent = 'SignUp' | 'Lead' | 'PageVisit' | 'Purchase';
-
-export interface RedditUserData {
- /** Pre-hashed (SHA-256 hex of trim+lowercase). Use `sha256Email()` before passing. */
- email_address?: string;
- phone_number?: string;
-}
-
-export interface RedditEcommerceItem {
- item_id: string;
- item_name: string;
- item_category?: string;
- price: number;
- quantity: number;
-}
-
-export interface RedditEcommerce {
- value: number;
- currency: string;
- items: RedditEcommerceItem[];
-}
-
-export interface PushConversionEventOptions {
- user_data?: RedditUserData;
- ecommerce?: RedditEcommerce;
- /**
- * How the user signed up or logged in. Surfaces as a GA4 custom dimension.
- * e.g. 'email' | 'passkey' | 'google' | 'linkedin'
- */
- signup_method?: string;
- /**
- * UUID shared between this pixel event and the server-side CAPI call.
- * Reddit dedupes on this value — without it, pixel + CAPI would double-count.
- */
- conversion_id?: string;
-}
-
-declare global {
- interface Window {
- dataLayer?: Record[];
- }
-}
-
-export interface RedditTrackingGate {
- /**
- * Return true to allow the event, false to suppress. Lets consuming apps
- * gate on things like "is this the right app?" or "is tracking enabled in env?".
- * When undefined, all events are pushed (assumes caller handles gating).
- */
- (): boolean;
-}
-
-let _gate: RedditTrackingGate | undefined;
-
-/**
- * Install an app-level gate. Called once at app bootstrap (e.g. from
- * BridgeProvider or the app's root layout). When the gate returns false, all
- * pushConversionEvent calls no-op.
- */
-export function configureRedditTracking(gate: RedditTrackingGate | undefined): void {
- _gate = gate;
-}
-
-function getDataLayer(): Record[] | undefined {
- if (typeof window === 'undefined') return undefined;
- return window.dataLayer;
-}
-
-/**
- * Push a conversion event to dataLayer for GTM (Reddit Pixel + GA4).
- *
- * No-ops when not in a browser, dataLayer is missing, or the gate returns false.
- */
-export function pushConversionEvent(
- event: RedditConversionEvent,
- options?: PushConversionEventOptions
-): void {
- if (_gate && !_gate()) return;
-
- const dataLayer = getDataLayer();
- if (!dataLayer || !Array.isArray(dataLayer)) return;
-
- const payload: Record = { event };
-
- if (options?.user_data && Object.keys(options.user_data).length > 0) {
- payload.user_data = options.user_data;
- }
- if (options?.ecommerce) {
- // Reddit/GA4 best practice: clear ecommerce before pushing a new one
- dataLayer.push({ ecommerce: null });
- payload.ecommerce = options.ecommerce;
- }
- if (options?.signup_method != null && options.signup_method !== '') {
- payload.signup_method = options.signup_method;
- }
- if (options?.conversion_id != null && options.conversion_id !== '') {
- payload.conversion_id = options.conversion_id;
- }
-
- dataLayer.push(payload);
-}
-
-/** @deprecated Use pushConversionEvent. Kept for backward compatibility. */
-export const pushRedditEvent = pushConversionEvent;
diff --git a/bridge-react/src/components/BridgeProvider.test.tsx b/bridge-react/src/components/BridgeProvider.test.tsx
new file mode 100644
index 0000000..c2a003b
--- /dev/null
+++ b/bridge-react/src/components/BridgeProvider.test.tsx
@@ -0,0 +1,142 @@
+// @vitest-environment jsdom
+/**
+ * `` end to end against auth-core's fake issuer: the route
+ * guard, email links, a sign-in request in the address, and the auth pages
+ * from one route.
+ */
+import { memoryStorage } from '@nebulr-group/bridge-auth-core';
+import { createFakeIssuer } from '@nebulr-group/bridge-auth-core/testing';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { StrictMode, useState, type ReactNode } from 'react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { resetClient, startClient } from '../core/client.js';
+import { resolveConfig, type BridgeConfig } from '../core/config.js';
+import type { BridgeRouter } from '../core/router.js';
+import { BridgeAuthRoutes } from './auth/BridgeAuthRoutes.js';
+import { BridgeProvider } from './BridgeProvider.js';
+
+const PASSWORD = 'correct horse battery';
+
+function setup(extra: Omit = {}) {
+ const fake = createFakeIssuer();
+ fake.addPerson({ email: 'alice@acme.test', password: PASSWORD, firstName: 'Alice', workspaces: [{ id: 'ws-acme', name: 'Acme', role: 'OWNER' }] });
+ fake.setFlags({ 'bridge-app-active': true, reports: false });
+ const config: BridgeConfig = { issuer: fake.issuer, ...extra };
+ // The provider reuses the client already made for the same issuer and storage: this one talks to the fake.
+ const client = startClient(resolveConfig(config), { fetch: fake.fetch, storage: memoryStorage(), autoRefresh: false, locks: null, tabChannel: null, live: false });
+ return { fake, client, config };
+}
+
+/** A router kept in React state, with every navigation recorded. */
+function harness(config: BridgeConfig, start: string, page: (path: string) => ReactNode) {
+ const visits: string[] = [];
+ let go: (to: string) => void = () => undefined;
+ function App() {
+ const [at, setAt] = useState(() => new URL(start, 'http://localhost'));
+ go = (to) => setAt(new URL(to, 'http://localhost'));
+ const router: BridgeRouter = {
+ location: { pathname: at.pathname, search: at.search, hash: at.hash },
+ navigate: (to) => {
+ visits.push(to);
+ setAt(new URL(to, 'http://localhost'));
+ },
+ };
+ return (
+ }>
+
The payment may still have gone through. Check your subscription in a moment; if it has not changed, try again.
+
+ Back to subscription
+
+ >
+ )}
+ >
+ );
+
+ return (
+
+ {frame ? frame(p, content) :
{content}
}
+
+ );
+}
+
+export default BridgeBillingRoutes;
diff --git a/bridge-react/src/components/billing/CheckoutNotice.tsx b/bridge-react/src/components/billing/CheckoutNotice.tsx
new file mode 100644
index 0000000..cfafa2c
--- /dev/null
+++ b/bridge-react/src/components/billing/CheckoutNotice.tsx
@@ -0,0 +1,126 @@
+/**
+ * Confirms a checkout the person just came back from, and says how it went.
+ * `` shows it on its pages; to land a checkout anywhere
+ * else, put it on that page:
+ *
+ * ```tsx
+ *
+ * ```
+ *
+ * It renders nothing unless the address is a return from checkout. It then
+ * confirms the checkout once, shows the outcome, takes the checkout's
+ * parameters off the address and fetches the billing facts again. `children`
+ * (a function of the outcome) replaces the text.
+ */
+import { readCheckoutReturn, type BillingFacts } from '@nebulr-group/bridge-auth-core';
+import { useEffect, useRef, useState, type HTMLAttributes, type ReactNode } from 'react';
+import { getBridge } from '../../core/client.js';
+import { errorMessage } from '../../core/i18n.js';
+import { billing } from '../../core/resources.js';
+import { useBridgeRouter, useTranslator } from '../../react/hooks.js';
+
+// One confirmation per checkout, however many notices are on the page.
+let lastConfirmation: { readonly session: string; readonly facts: Promise } | null = null;
+
+export type CheckoutOutcome =
+ | { readonly state: 'confirming' }
+ | { readonly state: 'success'; readonly planName: string | null }
+ | { readonly state: 'failed'; readonly error: string };
+
+export interface CheckoutNoticeProps extends Omit, 'children'> {
+ /** Show a close button once the outcome is known. @default true */
+ readonly dismissible?: boolean;
+ /** Called once the checkout is confirmed, with the new facts. */
+ readonly onConfirmed?: (facts: BillingFacts) => void;
+ /** Replaces the text. */
+ readonly children?: (outcome: CheckoutOutcome) => ReactNode;
+}
+
+export function CheckoutNotice({ dismissible = true, onConfirmed, children, className, ...rest }: CheckoutNoticeProps) {
+ const t = useTranslator();
+ const router = useBridgeRouter();
+ const [outcome, setOutcome] = useState(null);
+ // The latest callbacks, without running the confirmation again when they change.
+ const latest = useRef({ onConfirmed, router, t });
+ latest.current = { onConfirmed, router, t };
+
+ useEffect(() => {
+ const checkout = readCheckoutReturn(window.location.href);
+ if (checkout === null) return;
+ let alive = true;
+ setOutcome({ state: 'confirming' });
+ let confirmation = lastConfirmation;
+ const first = confirmation === null || confirmation.session !== checkout.session;
+ if (confirmation === null || confirmation.session !== checkout.session) {
+ confirmation = { session: checkout.session, facts: getBridge().billing.confirmCheckout(checkout.session) };
+ lastConfirmation = confirmation;
+ }
+ confirmation.facts
+ .then(
+ (facts) => {
+ if (!alive) return;
+ setOutcome({ state: 'success', planName: facts.plan?.name ?? null });
+ latest.current.onConfirmed?.(facts);
+ },
+ (error: unknown) => {
+ if (alive) setOutcome({ state: 'failed', error: errorMessage(error, latest.current.t, 'error.generic') });
+ },
+ )
+ .finally(() => {
+ if (!first) return;
+ // The checkout's parameters come off the address, through the router so it stays in step.
+ const url = new URL(window.location.href);
+ url.searchParams.delete('stripe_success');
+ url.searchParams.delete('session_id');
+ latest.current.router.navigate(`${url.pathname}${url.search}${url.hash}`, { replace: true });
+ void billing.refresh();
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ if (outcome === null) return null;
+ return (
+
+
+
+ {children ? (
+ children(outcome)
+ ) : outcome.state === 'confirming' ? (
+ Confirming your payment…
+ ) : outcome.state === 'success' ? (
+ <>
+ {outcome.planName ? `You're on ${outcome.planName} now` : 'Your new plan is active'}
+ Your payment went through and the new plan is active.
+ >
+ ) : (
+ <>
+ We couldn't confirm your payment
+ {outcome.error} The payment may still have gone through; check your plan again in a moment.
+ >
+ )}
+
+
+ {canManage
+ ? 'Your last payment failed. Please update your payment method to continue.'
+ : 'Your last payment failed. Ask the workspace owner to update the payment method.'}
+
+
+
- );
-}
-
-export default RealtimeDevBadge;
diff --git a/bridge-react/src/components/flags/FeatureFlag.tsx b/bridge-react/src/components/flags/FeatureFlag.tsx
new file mode 100644
index 0000000..aba99d2
--- /dev/null
+++ b/bridge-react/src/components/flags/FeatureFlag.tsx
@@ -0,0 +1,77 @@
+/**
+ * Shows its children when a flag is on, and `fallback` when it is off.
+ *
+ * `fallback` learns why the feature is off: `reason` is `'plan'` when the
+ * flag's rule needs a plan feature the workspace lacks (with `entitlement`
+ * naming it), `'off'` otherwise, and `openUpgrade()` opens the upgrade
+ * dialog. With `upgrade` and no `fallback`, a feature off because of the plan
+ * shows a small upgrade prompt in its place.
+ *
+ * ```tsx
+ *
+ *
+ * }>…
+ * ```
+ *
+ * (`key` is React's own prop, so the flag's key is `flagKey`.)
+ */
+import type { ReactNode } from 'react';
+import type { BridgeMessages } from '../../core/config.js';
+import { openUpgrade } from '../../core/upgrade.js';
+import { useBridge, useFlags, useFlagsStatus, useTranslator } from '../../react/hooks.js';
+
+export interface FeatureFlagOffInfo {
+ /** `plan`: an upgrade would turn it on. `off`: anything else. Undefined while results load. */
+ readonly reason: 'plan' | 'off' | undefined;
+ /** With `plan`: the plan feature the rule needs. */
+ readonly entitlement: string | null;
+ /** Bridge's own words for which part of the rule decided, when it says. */
+ readonly why: string | null;
+ /** Opens the upgrade dialog. Call it from a click. */
+ readonly openUpgrade: () => void;
+}
+
+export interface FeatureFlagProps {
+ readonly flagKey: string;
+ /** The value while Bridge gave none. @default false */
+ readonly defaultValue?: T;
+ /** Show an upgrade prompt when the plan is why it is off and there is no `fallback`. */
+ readonly upgrade?: boolean;
+ /** What to show when it is on: nodes, or a function of the flag's value. */
+ readonly children?: ReactNode | ((value: T) => ReactNode);
+ /** What to show when it is off: nodes, or a function of the value and why it is off. */
+ readonly fallback?: ReactNode | ((value: T, off: FeatureFlagOffInfo) => ReactNode);
+ readonly messages?: BridgeMessages;
+}
+
+export function FeatureFlag({ flagKey, defaultValue = false as T, upgrade = false, children, fallback, messages }: FeatureFlagProps) {
+ const t = useTranslator(messages);
+ const client = useBridge();
+ useFlags();
+ const status = useFlagsStatus();
+
+ const value = client === null ? defaultValue : client.flags.get(flagKey, defaultValue);
+ const on = typeof value === 'boolean' ? value : value !== defaultValue && value !== null && value !== undefined;
+ if (on) return <>{typeof children === 'function' ? (children as (value: T) => ReactNode)(value) : children}>;
+
+ const why = client?.flags.reason(flagKey) ?? null;
+ const entitlement = why?.entitlement ?? null;
+ const loaded = status === 'ready' || status === 'error';
+ const off: FeatureFlagOffInfo = {
+ reason: !loaded ? undefined : entitlement !== null ? 'plan' : 'off',
+ entitlement,
+ why: why?.why ?? null,
+ openUpgrade: () => openUpgrade({ kind: 'feature', flag: flagKey, entitlement }),
+ };
+ if (fallback !== undefined) return <>{typeof fallback === 'function' ? (fallback as (value: T, off: FeatureFlagOffInfo) => ReactNode)(value, off) : fallback}>;
+ if (upgrade && off.reason === 'plan') {
+ return (
+
+ );
+ }
+ return null;
+}
+
+export default FeatureFlag;
diff --git a/bridge-react/src/components/live/LiveStatusBadge.tsx b/bridge-react/src/components/live/LiveStatusBadge.tsx
new file mode 100644
index 0000000..076c094
--- /dev/null
+++ b/bridge-react/src/components/live/LiveStatusBadge.tsx
@@ -0,0 +1,26 @@
+/**
+ * A small badge with the Live connection's status, for development builds:
+ * `open` (live), `polling` (no socket; checking every few seconds),
+ * `connecting`, `closed` or `off`.
+ */
+import type { HTMLAttributes } from 'react';
+import { useLiveStatus } from '../../react/hooks.js';
+
+const LABELS: Record = {
+ open: 'Live',
+ polling: 'Live (polling)',
+ connecting: 'Connecting…',
+ closed: 'Live closed',
+ off: 'Live off',
+};
+
+export function LiveStatusBadge(props: HTMLAttributes) {
+ const status = useLiveStatus();
+ return (
+
+ {LABELS[status] ?? status}
+
+ );
+}
+
+export default LiveStatusBadge;
diff --git a/bridge-react/src/components/sdk-auth/BridgeAuthRoutes.tsx b/bridge-react/src/components/sdk-auth/BridgeAuthRoutes.tsx
deleted file mode 100644
index 777897d..0000000
--- a/bridge-react/src/components/sdk-auth/BridgeAuthRoutes.tsx
+++ /dev/null
@@ -1,250 +0,0 @@
-/**
- * TBP-743 (port of bridge-svelte TBP-696) — every sign-in page from one route.
- *
- * // React Router
- * import { BridgeAuthRoutes } from '@nebulr-group/bridge-react/react-router';
- * } />
- *
- * // TanStack Router
- * import { BridgeAuthRoutes } from '@nebulr-group/bridge-react/tanstack-router';
- * createRoute({ getParentRoute: () => rootRoute, path: 'auth/$', component: BridgeAuthRoutes })
- *
- * // No router: mounted wherever the app renders it for paths under `base`
- * import { BridgeAuthRoutes } from '@nebulr-group/bridge-react';
- *
- *
- * Serves login, signup, oauth-callback, set-password/:token, forgot-password,
- * magic-link, setup-passkey/:token and workspaces. Which sign-in methods show
- * (magic link, passkeys, SSO) comes from the app's auth config at runtime, so
- * an operator toggles them without a deploy.
- *
- * Customising, in rungs:
- * 1. `--bridge-*` CSS tokens restyle the forms.
- * 2. `frame(page, children)` replaces everything around the form on every
- * page; `heading(page)` replaces the form heading on each page's main step.
- * 3. Take over one page by passing an element:
- * }} />
- * Every other page keeps working.
- * 4. Headless: build on `getBridgeAuth()`.
- */
-import { useEffect, useRef, type ReactNode } from 'react';
-import type { MessageOverrides } from '@nebulr-group/bridge-auth-core';
-import { readReturnTo, withReturnTo } from '@nebulr-group/bridge-auth-core';
-import { getBridgeAuth, useBridgeStore } from '../../core/bridge-instance';
-import { bridgeAuthBase, parseBridgeAuthRoute, type BridgeAuthPage, type BridgeAuthRoute } from '../../core/auth-routes';
-import { billingRoutes } from '../../core/billing-routes';
-import { getTranslator } from '../../i18n';
-import { useWindowRouteLocation, type BridgeRouteLocation } from '../../routing/location';
-import { CallbackHandler } from '../auth/CallbackHandler';
-import { AuthFormWrapper } from './shared/AuthFormWrapper';
-import { LoginForm } from './LoginForm';
-import { SignupForm } from './SignupForm';
-import { ForgotPassword } from './ForgotPassword';
-import { MagicLink } from './MagicLink';
-import { PasskeySetup } from './PasskeySetup';
-import { WorkspaceSelector } from './WorkspaceSelector';
-
-export type { BridgeAuthPage };
-
-export interface BridgeAuthRoutesProps {
- /**
- * Everything around the form, on every page. Receives the page name and the
- * form to render. Replaces the default centred container entirely.
- */
- frame?: (page: BridgeAuthPage, children: ReactNode) => ReactNode;
- /**
- * The form heading, per page. Shown on each page's main step only — the
- * login credentials step, the signup form, the set-password form — so it
- * never stacks above a sub-step's own heading ("Check your email").
- */
- heading?: (page: BridgeAuthPage) => ReactNode;
- /**
- * Take over a page by passing an element: it renders instead of Bridge's
- * page, without the frame. Every other page keeps working. For the
- * email-link pages pass a function to receive the token:
- * `pages={{ 'set-password': ({ token }) => }}`.
- */
- pages?: Partial ReactNode)>>;
- /** Rendered for an address under the mount point that names no page. */
- notFound?: ReactNode;
- /** Where a completed sign-in, passkey setup or workspace switch lands when
- * there is no `?redirectUri=` deep link to return to. @default '/' */
- redirectTo?: string;
- /** Per-key copy overrides, passed to every form. */
- messages?: MessageOverrides;
- /**
- * The mount point, when no router adapter supplies the location — e.g.
- * `'/auth'`. Defaults to the directory of `loginRoute` (`/auth` for
- * `/auth/login`), else `/auth`.
- */
- base?: string;
- /**
- * The current location, from a router adapter. The `/react-router` and
- * `/tanstack-router` entries pass it; leave it out to read `window.location`.
- */
- location?: BridgeRouteLocation;
-}
-
-function defaultBase(loginRoute: string | null): string {
- if (loginRoute) {
- const dir = loginRoute.replace(/\/+$/, '').replace(/\/[^/]*$/, '');
- if (dir) return dir;
- }
- return '/auth';
-}
-
-export function BridgeAuthRoutes(props: BridgeAuthRoutesProps) {
- const loginRoute = useBridgeStore((s) => s.loginRoute);
- const windowLocation = useWindowRouteLocation(props.base ?? defaultBase(loginRoute));
- return ;
-}
-
-function AuthRoutesBody({
- frame,
- heading,
- pages,
- notFound,
- redirectTo = '/',
- messages,
- location,
-}: BridgeAuthRoutesProps & { location: BridgeRouteLocation }) {
- const t = getTranslator(messages);
- const loginRoute = useBridgeStore((s) => s.loginRoute);
- const isAuthenticated = useBridgeStore((s) => !!s.tokens?.accessToken);
-
- const rest = location.rest;
- const route = parseBridgeAuthRoute(rest);
- const base = bridgeAuthBase(location.pathname, rest);
- const loginHref = `${base}/login`;
- const signupHref = `${base}/signup`;
- // Hosted mode is "no loginRoute" — the same switch uses.
- const hosted = !loginRoute;
-
- const afterSignIn = () => location.navigate(readReturnTo(location.search) ?? redirectTo);
-
- // A magic link returns to the page it was requested from. redeems
- // it but has no `onLogin`, so the sign-in it completes is picked up here.
- // Only a transition counts: a user already signed in when the page opened is
- // not bounced away.
- const wasAuthenticated = useRef(isAuthenticated);
- useEffect(() => {
- if (isAuthenticated && !wasAuthenticated.current && route?.page === 'magic-link') afterSignIn();
- wasAuthenticated.current = isAuthenticated;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isAuthenticated, route?.page]);
-
- // The workspace list needs a session. A signed-out visitor is sent to sign
- // in and back.
- useEffect(() => {
- if (route?.page === 'workspaces' && !hosted && !isAuthenticated) {
- location.navigate(withReturnTo(loginHref, `${location.pathname}${location.search}`), { replace: true });
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [route?.page, hosted, isAuthenticated, loginHref]);
-
- if (!route) {
- if (rest === null) return null; // not under the mount point: nothing to serve
- return (
-
- {notFound ??
Page not found.
}
-
- );
- }
-
- const page = route.page;
-
- // Rung 3: the app's own element owns the page outright.
- if (pages && pages[page] !== undefined) {
- return (
-
- );
- }
-
- // The OAuth callback exchanges the code and navigates on; it has no form.
- // In hosted mode it is the one page that is not hosted.
- if (page === 'oauth-callback') {
- return (
-
-
-
- );
- }
-
- const headingSlot = heading ? heading(page) : undefined;
-
- let body: ReactNode = null;
- if (hosted && !(page === 'workspaces' && isAuthenticated)) {
- // Hosted mode: every sign-in page points at the hosted login instead. A
- // signed-in user switching workspace is not signing in, so that stays.
- let href: string | null = null;
- try {
- const auth = getBridgeAuth();
- href = page === 'signup' ? auth.createSignupUrl() : auth.createLoginUrl();
- } catch {
- href = null;
- }
- body = (
-
-
Sign-in for this app happens on its hosted login page, not here.
- {href ? (
-
- {t(page === 'signup' ? 'signup.submit' : 'login.submit')}
-
- ) : null}
-
- );
- } else if (page === 'login') {
- body = ;
- } else if (page === 'signup') {
- body = ;
- } else if (page === 'set-password') {
- body = ;
- } else if (page === 'forgot-password') {
- body = ;
- } else if (page === 'magic-link') {
- body = ;
- } else if (page === 'setup-passkey' && route.token) {
- body = (
- location.navigate(loginHref)}
- messages={messages}
- />
- );
- } else if (page === 'workspaces' && isAuthenticated) {
- body = (
-
- location.navigate(readReturnTo(location.search) ?? redirectTo)}
- messages={messages}
- />
-
- );
- }
-
- return (
-
- {frame ? frame(page, body) :
{body}
}
-
- );
-}
-
-export default BridgeAuthRoutes;
diff --git a/bridge-react/src/components/sdk-auth/ForgotPassword.tsx b/bridge-react/src/components/sdk-auth/ForgotPassword.tsx
deleted file mode 100644
index 9b7cbf8..0000000
--- a/bridge-react/src/components/sdk-auth/ForgotPassword.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import type { HTMLAttributes, ReactNode } from 'react';
-import { useState } from 'react';
-import type { MessageOverrides } from '@nebulr-group/bridge-auth-core';
-import { getBridgeAuth } from '../../core/bridge-instance';
-import { getTranslator } from '../../i18n';
-import { authErrorMessage } from './shared/auth-error';
-import { AuthFormWrapper } from './shared/AuthFormWrapper';
-import { Alert } from './shared/Alert';
-import { Spinner } from './shared/Spinner';
-import { PasswordToggleIcon } from './shared/icons';
-
-interface Props extends Omit, 'onError'> {
- /** When provided, switches to "set new password" mode. */
- token?: string;
- onComplete?: () => void;
- onError?: (error: Error) => void;
- loginHref?: string;
- /** Heading text. Pass `null`/`''` to render no heading and use your own page title. */
- heading?: string | null;
- /**
- * The heading as a node, replacing the built-in one on the main step only
- * (the form). Result states keep their own heading, so two never stack.
- * `` passes its per-page heading here (TBP-743).
- */
- headingSlot?: ReactNode;
- /** Step description. Pass `null`/`''` to render nothing and use your own subtitle (TBP-631). */
- description?: string | null;
- /** Per-key copy overrides for this component only (TBP-630). */
- messages?: MessageOverrides;
-}
-
-export function ForgotPassword({
- token,
- onComplete,
- onError,
- loginHref = '/auth/login',
- heading,
- headingSlot,
- description,
- messages,
- className,
- style,
- ...rest
-}: Props) {
- const t = getTranslator(messages);
- const isSetMode = !!token;
-
- const [email, setEmail] = useState('');
- const [password, setPassword] = useState('');
- const [confirmPassword, setConfirmPassword] = useState('');
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState(null);
- const [emailSent, setEmailSent] = useState(false);
- const [passwordReset, setPasswordReset] = useState(false);
- const [showPasswords, setShowPasswords] = useState(false);
-
- const builtInHeading = isSetMode ? t('forgot.headingSet') : t('forgot.headingRequest');
- const wrapperHeading =
- passwordReset || emailSent ? null : heading !== undefined ? heading : builtInHeading;
-
- // TBP-631 — same shape as the heading above: the description belongs to the
- // send-link step only. `undefined` means "not overridden" and falls through to
- // the built-in; `null` is an explicit suppression from the host and must be
- // respected, which is why this cannot collapse to `description ?? builtIn`.
- const wrapperDescription =
- isSetMode || passwordReset || emailSent
- ? null
- : description !== undefined
- ? description
- : t('forgot.description');
-
- async function handleSendLink(e: React.FormEvent) {
- e.preventDefault();
- if (loading) return;
- setError(null);
- setLoading(true);
- try {
- await getBridgeAuth().sendResetPasswordLink(email);
- setEmailSent(true);
- } catch (err: any) {
- setError(authErrorMessage(err, t, 'forgot.error.send'));
- onError?.(err);
- } finally {
- setLoading(false);
- }
- }
-
- async function handleSetPassword(e: React.FormEvent) {
- e.preventDefault();
- if (loading) return;
- setError(null);
-
- if (password !== confirmPassword) {
- setError(t('forgot.error.mismatch'));
- return;
- }
- if (password.length < 8) {
- setError(t('forgot.error.tooShort'));
- return;
- }
-
- setLoading(true);
- try {
- await (getBridgeAuth() as any).updatePassword(token!, password);
- setPasswordReset(true);
- onComplete?.();
- } catch (err: any) {
- setError(authErrorMessage(err, t, 'forgot.error.update'));
- onError?.(err);
- } finally {
- setLoading(false);
- }
- }
-
- return (
-
- {error && {error}}
-
- {isSetMode ? (
- passwordReset ? (
- <>
-
- >
- )}
-
- );
-}
-
-export default ForgotPassword;
diff --git a/bridge-react/src/components/sdk-auth/LoginForm.tsx b/bridge-react/src/components/sdk-auth/LoginForm.tsx
deleted file mode 100644
index eff7e77..0000000
--- a/bridge-react/src/components/sdk-auth/LoginForm.tsx
+++ /dev/null
@@ -1,461 +0,0 @@
-import type { FederationConnection, MessageOverrides } from '@nebulr-group/bridge-auth-core';
-import type { HTMLAttributes, ReactNode } from 'react';
-import { useEffect, useState } from 'react';
-import {
- ensureAppConfig,
- getBridgeAuth,
- useBridgeStore,
-} from '../../core/bridge-instance';
-import { getTranslator } from '../../i18n';
-import { AuthFormWrapper } from './shared/AuthFormWrapper';
-import { Alert } from './shared/Alert';
-import { Spinner } from './shared/Spinner';
-import { MfaChallenge } from './MfaChallenge';
-import { MfaSetup } from './MfaSetup';
-import { TenantSelector } from './TenantSelector';
-import { SsoButton } from './SsoButton';
-import { SsoProviderIcon } from './SsoProviderIcon';
-import { PasskeyLogin } from './PasskeyLogin';
-import { PasskeyRequestSetupLink } from './PasskeyRequestSetupLink';
-import { authErrorMessage, isOriginNotAllowed } from './shared/auth-error';
-import { MagicLinkIcon, PasswordToggleIcon } from './shared/icons';
-
-interface Props extends Omit, 'onError'> {
- showSignupLink?: boolean;
- signupHref?: string;
- showForgotPassword?: boolean;
- forgotPasswordHref?: string;
- showMagicLink?: boolean;
- magicLinkHref?: string;
- showPasskeys?: boolean;
- /**
- * Where "no passkey on this device" sends the person. Unset (the default),
- * the form asks for their email in place and mails a setup link, like
- * bridge-svelte — `` serves `setup-passkey/` only,
- * so there is no bare setup page to send them to.
- */
- passkeySetupHref?: string;
- onLogin?: () => void;
- onError?: (error: Error) => void;
- onSsoClick?: (connectionType: string) => void;
- /** Heading text. Pass `null`/`''` to render no heading and use your own page title. */
- heading?: string | null;
- headingSlot?: ReactNode;
- ssoConnections?: FederationConnection[];
- ssoMode?: 'redirect' | 'popup';
- footer?: ReactNode;
- /** Per-key copy overrides for this component only (TBP-630). Fanned out to
- * the MFA / passkey / forgot-password sub-views this form renders, so an app
- * overrides a phrase once rather than once per step. */
- messages?: MessageOverrides;
-}
-
-function buildSsoConnections(appConfig: any): FederationConnection[] {
- if (!appConfig) return [];
- const out: FederationConnection[] = [];
- if (appConfig.googleSsoEnabled) out.push({ id: 'google', type: 'google', name: 'Google' });
- if (appConfig.azureAdSsoEnabled) out.push({ id: 'azure', type: 'ms-azure-ad', name: 'Microsoft' });
- if (appConfig.linkedinSsoEnabled) out.push({ id: 'linkedin', type: 'linkedin', name: 'LinkedIn' });
- if (appConfig.githubSsoEnabled) out.push({ id: 'github', type: 'github', name: 'GitHub' });
- if (appConfig.facebookSsoEnabled) out.push({ id: 'facebook', type: 'facebook', name: 'Facebook' });
- if (appConfig.appleSsoEnabled) out.push({ id: 'apple', type: 'apple', name: 'Apple' });
- return out;
-}
-
-export function LoginForm({
- showSignupLink,
- signupHref,
- showForgotPassword,
- forgotPasswordHref = '/auth/forgot-password',
- showMagicLink,
- magicLinkHref = '/auth/magic-link',
- showPasskeys,
- passkeySetupHref,
- onLogin,
- onError,
- onSsoClick,
- heading = '',
- headingSlot,
- ssoConnections = [],
- ssoMode = 'redirect',
- footer,
- messages,
- className,
- style,
- ...rest
-}: Props) {
- const t = getTranslator(messages);
- const authState = useBridgeStore((s) => s.authState);
- const appConfig = useBridgeStore((s) => s.appConfig);
-
- const [email, setEmail] = useState('');
- const [password, setPassword] = useState('');
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState(null);
- /**
- * The auth state `error` was raised in (TBP-669). A failure that leaves the
- * state where it was — an older auth-core keeps `credentials-validated`
- * after a failed token exchange — must show the error, not the settling
- * spinner; an error left over from an earlier attempt must not hijack a
- * later sign-in that moved the state on. See the settling branch.
- */
- const [errorAtState, setErrorAtState] = useState(null);
- const [showPassword, setShowPassword] = useState(false);
-
- /**
- * Record an error together with the state it was raised in. Read from the
- * store, not the render's `authState`: a catch runs after the awaited call
- * moved the state on, and the closure's copy is from before it.
- */
- function raise(message: string) {
- setError(message);
- setErrorAtState(useBridgeStore.getState().authState as string);
- }
-
- /**
- * TBP-669 — an origin refusal inside MFA, workspace selection, a passkey or
- * an SSO sign-in ends the sign-in: auth-core returns to `unauthenticated`,
- * which unmounts the child that caught the error (and the passkey / SSO
- * buttons show no error of their own). LoginForm keeps the message so the
- * credentials form can show it. Other child errors stay with the child.
- */
- function handleChildError(err: Error) {
- if (isOriginNotAllowed(err)) raise(authErrorMessage(err, t, 'login.error.invalidCredentials'));
- onError?.(err);
- }
-
- // Inline step machine — mirrors bridge-svelte. Forgot-password renders in
- // place of the credentials form (not a separate route) so the spec's
- // "click forgot → no email/password inputs → click back-to-login → email
- // input visible again" round-trip works without a navigation.
- const [step, setStep] = useState<'credentials' | 'forgot-password' | 'passkey-request'>('credentials');
- const [fpEmailSent, setFpEmailSent] = useState(false);
- const [fpLoading, setFpLoading] = useState(false);
-
- function goBackToCredentials() {
- setStep('credentials');
- setFpEmailSent(false);
- setError(null);
- }
-
- async function handleForgotSubmit(e: React.FormEvent) {
- e.preventDefault();
- if (fpLoading) return;
- setError(null);
- setFpLoading(true);
- try {
- await getBridgeAuth().sendResetPasswordLink(email);
- setFpEmailSent(true);
- } catch (err: any) {
- raise(authErrorMessage(err, t, 'forgot.error.send'));
- onError?.(err);
- } finally {
- setFpLoading(false);
- }
- }
-
- const effectiveSso =
- ssoConnections.length > 0 ? ssoConnections : buildSsoConnections(appConfig);
- const effectiveShowMagicLink = showMagicLink ?? appConfig?.magicLinkEnabled ?? false;
- const effectiveShowPasskeys = showPasskeys ?? appConfig?.passkeysEnabled ?? false;
- const effectiveShowForgotPassword = showForgotPassword ?? true;
- const effectiveShowSignupLink = showSignupLink ?? appConfig?.signupEnabled ?? true;
-
- useEffect(() => {
- void ensureAppConfig();
-
- // Magic link token detection — same flow as svelte
- if (typeof window === 'undefined') return;
- const params = new URLSearchParams(window.location.search);
- const magicToken = params.get('bridge_magic_link_token');
- if (!magicToken) return;
-
- params.delete('bridge_magic_link_token');
- const newSearch = params.toString();
- const newUrl = window.location.pathname + (newSearch ? `?${newSearch}` : '');
- window.history.replaceState({}, '', newUrl);
-
- setLoading(true);
- (getBridgeAuth() as any)
- .authenticateWithMagicLinkToken(magicToken)
- .catch((err: any) => {
- raise(authErrorMessage(err, t, 'magicLink.error.auth'));
- onError?.(err);
- })
- .finally(() => setLoading(false));
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- useEffect(() => {
- if (authState === 'authenticated') onLogin?.();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authState]);
-
- async function handleSubmit(e: React.FormEvent) {
- e.preventDefault();
- if (loading) return;
- setError(null);
- setLoading(true);
- try {
- await getBridgeAuth().authenticate(email, password);
- } catch (err: any) {
- raise(authErrorMessage(err, t, 'login.error.invalidCredentials'));
- onError?.(err);
- setLoading(false);
- }
- }
-
- if (authState === 'mfa-required') return ;
- if ((authState as any) === 'mfa-setup-required') return ;
- if (authState === 'tenant-selection')
- return ;
-
- // Settling: the session is real and the host app has not navigated yet.
- //
- // This test is `!== 'unauthenticated'` rather than an explicit list of
- // `authenticated | credentials-validated` on purpose. Those two used to fall
- // through to the credentials form below, so somebody who had just typed their
- // password correctly was shown the password form again — which reads as a
- // refusal, and the reasonable response is to type it again (TBP-635). The
- // window opens when the token exchange resolves and closes only when the
- // consumer's router lands, because LoginForm fires `onLogin` and deliberately
- // does not navigate.
- //
- // Listing the two states would fix the two we know about and leave the next
- // `AuthState` member falling into the same hole. Inverting the test means the
- // credentials form renders ONLY for `unauthenticated`, and anything else lands
- // on a spinner — wrong-but-harmless instead of wrong-and-alarming.
- //
- // `login.submitting` is reused rather than given its own key: it already says
- // "Signing in…" in all twelve locales.
- //
- // TBP-669: the one exception is a failure raised in the current state. With
- // an auth-core that leaves the state at `credentials-validated` when the
- // token exchange fails (a 403 "Origin not allowed" on stage), this branch
- // showed "Signing in…" forever and the error never rendered. An error raised
- // at this very state falls through to the credentials form, which shows it.
- if (authState !== 'unauthenticated' && !(error && errorAtState === authState)) {
- return (
-
-
-
- {t('login.submitting')}
-
-
- );
- }
-
- // No passkey on this device: ask for the email and mail a setup link, in
- // place (mirrors bridge-svelte's `passkey-request` step).
- if (step === 'passkey-request') {
- return ;
- }
-
- if (step === 'forgot-password') {
- return (
-
- {error && {error}}
-
- {fpEmailSent ? (
- <>
- {t('forgot.emailSent')}
-
- )
- )}
-
- );
-}
-
-export default LoginForm;
diff --git a/bridge-react/src/components/sdk-auth/MagicLink.tsx b/bridge-react/src/components/sdk-auth/MagicLink.tsx
deleted file mode 100644
index b8599b7..0000000
--- a/bridge-react/src/components/sdk-auth/MagicLink.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import type { HTMLAttributes, ReactNode } from 'react';
-import { useEffect, useState } from 'react';
-import type { MessageOverrides, Translator } from '@nebulr-group/bridge-auth-core';
-import { getBridgeAuth } from '../../core/bridge-instance';
-import { getTranslator } from '../../i18n';
-import { authErrorMessage } from './shared/auth-error';
-import { AuthFormWrapper } from './shared/AuthFormWrapper';
-import { Alert } from './shared/Alert';
-import { Spinner } from './shared/Spinner';
-
-interface Props extends Omit, 'onError'> {
- onSent?: () => void;
- onError?: (error: Error) => void;
- loginHref?: string;
- /** Heading text. Pass `null`/`''` to render no heading and use your own page title. */
- heading?: string | null;
- /**
- * The heading as a node, replacing the built-in one on the main step only
- * (the form). Result states keep their own heading, so two never stack.
- * `` passes its per-page heading here (TBP-743).
- */
- headingSlot?: ReactNode;
- /** Step description. Pass `null`/`''` to render nothing and use your own subtitle (TBP-631). */
- description?: string | null;
- /** Per-key copy overrides for this component only (TBP-630). */
- messages?: MessageOverrides;
-}
-
-function formatExpiry(t: Translator, seconds: number): string {
- if (seconds >= 60) {
- const count = Math.floor(seconds / 60);
- return t(count === 1 ? 'magicLink.expiryMinute' : 'magicLink.expiryMinutes', { count });
- }
- return t('magicLink.expirySeconds', { count: seconds });
-}
-
-export function MagicLink({
- onSent,
- onError,
- loginHref = '/auth/login',
- heading,
- headingSlot,
- description,
- messages,
- className,
- style,
- ...rest
-}: Props) {
- const t = getTranslator(messages);
- const [email, setEmail] = useState('');
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState(null);
- const [sent, setSent] = useState(false);
- const [expiresIn, setExpiresIn] = useState(0);
-
- // `undefined` means "not passed" and falls through to the catalogue; `null`
- // is an explicit suppression from the host and must survive (TBP-631), which
- // is why this cannot collapse to `heading ?? t(...)`.
- const wrapperHeading = heading !== undefined ? heading : t('magicLink.heading');
- const wrapperDescription =
- description !== undefined ? description : t('magicLink.description');
-
- async function handleSend(e: React.FormEvent) {
- e.preventDefault();
- if (loading) return;
- setError(null);
- setLoading(true);
- try {
- const result = await (getBridgeAuth() as any).sendMagicLink(email);
- setExpiresIn(result.expiresIn);
- setSent(true);
- onSent?.();
- } catch (err: any) {
- setError(authErrorMessage(err, t, 'magicLink.error.send'));
- onError?.(err);
- } finally {
- setLoading(false);
- }
- }
-
- // TBP-682: the emailed link returns to the page the request was made from,
- // so this component must redeem the token as well as send it. Without this
- // effect a link requested here lands back here and does nothing — the token
- // sits in the address bar and the user stays signed out. Mirrors LoginForm,
- // which has always redeemed on mount.
- //
- // Safe under StrictMode's dev-only double-invoke without a ref guard, for the
- // same reason LoginForm is: the token is removed from the URL synchronously,
- // before the redeem is started, so the second run finds no token and returns
- // at the guard above it.
- useEffect(() => {
- if (typeof window === 'undefined') return;
-
- const params = new URLSearchParams(window.location.search);
- const magicToken = params.get('bridge_magic_link_token');
- if (!magicToken) return;
-
- // Drop the token from the URL before redeeming, so a reload or a shared
- // link cannot replay it.
- params.delete('bridge_magic_link_token');
- const newSearch = params.toString();
- const newUrl = window.location.pathname + (newSearch ? `?${newSearch}` : '');
- window.history.replaceState({}, '', newUrl);
-
- setLoading(true);
- setError(null);
- (getBridgeAuth() as any)
- .authenticateWithMagicLinkToken(magicToken)
- .catch((err: any) => {
- setError(authErrorMessage(err, t, 'magicLink.error.auth'));
- onError?.(err);
- })
- .finally(() => setLoading(false));
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- return (
-
- {error && {error}}
-
- {sent ? (
- <>
-
- {t('magicLink.sent', { expiry: formatExpiry(t, expiresIn) })}
-
- {loginHref && (
-
- )
- );
-
- return (
- // In the success state the "Check your email" heading below is the title, so
- // suppress the form heading to avoid two stacked headings.
-
- {success ? (
- <>
-
- );
-}
-
-export default Alert;
diff --git a/bridge-react/src/components/sdk-auth/shared/AuthFormWrapper.tsx b/bridge-react/src/components/sdk-auth/shared/AuthFormWrapper.tsx
deleted file mode 100644
index 995b17f..0000000
--- a/bridge-react/src/components/sdk-auth/shared/AuthFormWrapper.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { HTMLAttributes, ReactNode } from 'react';
-
-interface AuthFormWrapperProps extends HTMLAttributes {
- /** Heading text. Pass `null` or `''` to render no heading. */
- heading?: string | null;
- headingSlot?: ReactNode;
- /**
- * Step description, the `
` under the heading.
- * Pass `null` or `''` to render nothing at all — no empty paragraph holding
- * vertical space (TBP-631).
- *
- * Independent of `heading`: suppressing one never affects the other. An app
- * that writes its own page title and subtitle suppresses both; an app that
- * writes only the title suppresses only the heading.
- *
- * Before TBP-631 these lived in each component's markup, outside this
- * wrapper's heading guard, so `heading={null}` could not reach them and a host
- * page ended up printing its own subtitle followed by Bridge's — the same
- * sentence twice, in two voices.
- */
- description?: string | null;
- /**
- * Description as a node, for copy that carries markup — `SignupForm` needs
- * `{email}` inside its sentence, which a plain string prop
- * cannot express. Takes precedence over `description`, mirroring how
- * `headingSlot` relates to `heading`.
- */
- descriptionSlot?: ReactNode;
- children?: ReactNode;
-}
-
-export function AuthFormWrapper({
- heading,
- headingSlot,
- description,
- descriptionSlot,
- children,
- className,
- style,
- ...rest
-}: AuthFormWrapperProps) {
- return (
-
- {headingSlot ?? (heading ?
{heading}
: null)}
- {descriptionSlot ??
- (description ?
{description}
: null)}
- {children}
-
- );
-}
-
-export default AuthFormWrapper;
diff --git a/bridge-react/src/components/sdk-auth/shared/Spinner.tsx b/bridge-react/src/components/sdk-auth/shared/Spinner.tsx
deleted file mode 100644
index fc3f710..0000000
--- a/bridge-react/src/components/sdk-auth/shared/Spinner.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import type { HTMLAttributes } from 'react';
-
-interface SpinnerProps extends HTMLAttributes {
- size?: number;
-}
-
-export function Spinner({ size = 24, className, style, ...rest }: SpinnerProps) {
- return (
-
- );
-}
-
-export default Spinner;
diff --git a/bridge-react/src/components/sdk-auth/shared/auth-error.ts b/bridge-react/src/components/sdk-auth/shared/auth-error.ts
deleted file mode 100644
index 423cb96..0000000
--- a/bridge-react/src/components/sdk-auth/shared/auth-error.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * TBP-669 — what an SDK auth component shows when a Bridge call fails.
- *
- * Bridge refuses sign-in from an origin missing from the app's allowed origins
- * with `403 {"message":"Origin not allowed"}` — on password sign-in, on the
- * token exchange that finishes a magic-link or passkey sign-in, on MFA, signup
- * and passkey options. The components used to show that bare string (or, on
- * the magic-link path, nothing at all: see LoginForm's settling branch). A
- * developer could not tell it was a one-line fix in Bridge admin.
- *
- * Works with any auth-core in the peer range: auth-core versions with TBP-669
- * throw an error with `code: 'ORIGIN_NOT_ALLOWED'` and already log the console
- * line; older ones throw a plain `HttpError` (status 403, that message), which
- * is recognised here and logged here. Mirrors bridge-svelte's
- * `sdk-auth/shared/auth-error.ts`.
- */
-import { en, type MessageKey, type Translator } from '@nebulr-group/bridge-auth-core';
-import {
- ORIGIN_NOT_ALLOWED_DOCS_URL,
- originNotAllowedHint,
- pageOrigin,
-} from '../../../utils/allowed-origins';
-
-// Present in auth-core's catalogues from TBP-669 on; English fallback before.
-const ORIGIN_KEY = 'error.originNotAllowed';
-
-/** True only for Bridge's origin-allowlist refusal — every other 403 keeps its own message. */
-export function isOriginNotAllowed(err: unknown): boolean {
- if (!err || typeof err !== 'object') return false;
- const e = err as { code?: unknown; status?: unknown; message?: unknown; body?: unknown };
- if (e.code === 'ORIGIN_NOT_ALLOWED') return true;
- if (e.status !== 403) return false;
- const bodyMessage = (e.body as { message?: unknown } | undefined)?.message;
- const message = typeof bodyMessage === 'string' ? bodyMessage : e.message;
- return typeof message === 'string' && message.trim().toLowerCase() === 'origin not allowed';
-}
-
-/** The form copy: translated when the installed auth-core has the key, English otherwise. */
-export function originNotAllowedMessage(t: Translator, origin: string | undefined = pageOrigin()): string {
- if (ORIGIN_KEY in en) return t(ORIGIN_KEY as MessageKey, { origin: origin ?? "this page's origin" });
- return originNotAllowedHint(origin);
-}
-
-const reported = new Set();
-
-/** One console line per origin per page load, unless auth-core already printed it. */
-function reportOnce(err: unknown): void {
- if ((err as { code?: unknown }).code === 'ORIGIN_NOT_ALLOWED') return; // auth-core logged it
- const origin = pageOrigin();
- const key = origin ?? '';
- if (reported.has(key)) return;
- reported.add(key);
- console.error(`[bridge] Origin not allowed. ${originNotAllowedHint(origin)} Docs: ${ORIGIN_NOT_ALLOWED_DOCS_URL}`);
-}
-
-/** Test seam. */
-export function _resetOriginReports(): void {
- reported.clear();
-}
-
-/**
- * The message an auth component shows for `err`: the origin fix for the
- * allowlist refusal, otherwise the error's own message, otherwise the
- * component's translated fallback.
- */
-export function authErrorMessage(err: unknown, t: Translator, fallbackKey: MessageKey): string {
- if (isOriginNotAllowed(err)) {
- reportOnce(err);
- return originNotAllowedMessage(t);
- }
- const message = (err as { message?: unknown } | null)?.message;
- return typeof message === 'string' && message !== '' ? message : t(fallbackKey);
-}
diff --git a/bridge-react/src/components/sdk-auth/shared/icons.tsx b/bridge-react/src/components/sdk-auth/shared/icons.tsx
deleted file mode 100644
index 98fbde7..0000000
--- a/bridge-react/src/components/sdk-auth/shared/icons.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * Icons the sign-in forms draw (TBP-899). The same SVGs as bridge-svelte, so
- * the four SDKs' sign-in screens look the same: the show-password eye, the
- * passkey and magic-link method icons.
- */
-
-const STAR =
- 'M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z';
-
-/** Show-password toggle: an open eye, or a struck-through one while the password shows. */
-export function PasswordToggleIcon({ visible }: { visible: boolean }) {
- return visible ? (
-
- ) : (
-
- );
-}
-
-export function PasskeyIcon() {
- return (
-
- );
-}
-
-export function MagicLinkIcon() {
- return (
-
- );
-}
diff --git a/bridge-react/src/components/shared/Alert.tsx b/bridge-react/src/components/shared/Alert.tsx
new file mode 100644
index 0000000..ed19ffe
--- /dev/null
+++ b/bridge-react/src/components/shared/Alert.tsx
@@ -0,0 +1,17 @@
+import type { HTMLAttributes, ReactNode } from 'react';
+
+export interface AlertProps extends HTMLAttributes {
+ readonly variant?: 'error' | 'info' | 'success';
+ readonly children?: ReactNode;
+}
+
+export function Alert({ variant = 'error', children, ...rest }: AlertProps) {
+ if (children === undefined || children === null || children === false || children === '') return null;
+ return (
+
+ {children}
+
+ );
+}
+
+export default Alert;
diff --git a/bridge-react/src/components/shared/AuthFormWrapper.tsx b/bridge-react/src/components/shared/AuthFormWrapper.tsx
new file mode 100644
index 0000000..83fb606
--- /dev/null
+++ b/bridge-react/src/components/shared/AuthFormWrapper.tsx
@@ -0,0 +1,28 @@
+/**
+ * The frame of every sign-in form: an optional heading and description, then
+ * the form. Pass `heading={null}` and `description={null}` when your page
+ * writes its own title; each is suppressed on its own. A string heading is
+ * drawn as the form's `
`; any other node replaces it as given.
+ */
+import type { HTMLAttributes, ReactNode } from 'react';
+
+export interface AuthFormWrapperProps extends Omit, 'children'> {
+ /** Heading: text for the form's `
`, or your own node. `null` or `''` renders none. */
+ readonly heading?: ReactNode;
+ /** The line under the heading: text, or your own node. `null` or `''` renders none. */
+ readonly description?: ReactNode;
+ readonly children?: ReactNode;
+ readonly [data: `data-${string}`]: string | number | boolean | null | undefined;
+}
+
+export function AuthFormWrapper({ heading, description, children, ...rest }: AuthFormWrapperProps) {
+ return (
+
- );
-}
-
-export default BridgeBillingRoutes;
diff --git a/bridge-react/src/components/subscription/BridgeCheckoutNotice.tsx b/bridge-react/src/components/subscription/BridgeCheckoutNotice.tsx
deleted file mode 100644
index 531c0f9..0000000
--- a/bridge-react/src/components/subscription/BridgeCheckoutNotice.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-/**
- * TBP-945 (port of bridge-svelte TBP-813) — the "you're on Pro now" banner
- * after a checkout.
- *
- * A completed checkout (or a Free pick) lands on `billing.successRoute`, the
- * subscription page by default, which shows this banner itself. To land
- * somewhere else and still say so, put it on that page or in the layout:
- *
- *
- *
- * It renders nothing until a checkout has just completed, shows once, and is
- * gone after a reload. `children` replaces the text and receives the result;
- * for a message of your own anywhere else, read `useCheckoutResult()`.
- */
-import { useEffect, useState, type ReactNode } from 'react';
-import type { Plan } from '@nebulr-group/bridge-auth-core';
-import { useBridgeStore } from '../../core/bridge-instance';
-import {
- clearCheckoutResult,
- getCheckoutResult,
- subscribeCheckoutResult,
- type BridgeCheckoutResult,
-} from '../../core/checkout-result';
-import { useBillingSnapshot } from './use-billing-snapshot';
-
-/** What `children` receives: the result, with the plan name when it is known. */
-export type BridgeCheckoutNoticeContext = Omit & { planName: string | null };
-
-export interface BridgeCheckoutNoticeProps {
- /** Optional class on the banner. */
- className?: string;
- /** Show a close button. @default true */
- dismissible?: boolean;
- /** Replaces the banner's text. Receives the result, with the plan name when known. */
- children?: (result: BridgeCheckoutNoticeContext) => ReactNode;
-}
-
-export function BridgeCheckoutNotice({ className = '', dismissible = true, children }: BridgeCheckoutNoticeProps) {
- const [shown, setShown] = useState(null);
- const billingPlanName = useBillingSnapshot()?.state?.plan.name ?? null;
- const storePlan = useBridgeStore((s) => s.subscription.status?.plan) as unknown;
-
- useEffect(() => {
- // Take the result as soon as it is set, so it shows once, including on a
- // page that is already open when a Free pick lands back on it.
- const take = () => {
- const value = getCheckoutResult();
- if (!value) return;
- setShown(value);
- queueMicrotask(clearCheckoutResult);
- };
- take();
- return subscribeCheckoutResult(take);
- }, []);
-
- if (!shown) return null;
-
- const planName =
- shown.planName ||
- billingPlanName ||
- (storePlan && typeof storePlan === 'object' ? ((storePlan as Plan).name ?? null) : null);
-
- return (
-
-
-
- {children ? (
- children({ ...shown, planName })
- ) : (
- <>
-
- {planName ? `You're on ${planName} now` : 'Your new plan is active'}
-
-
- {shown.kind === 'checkout'
- ? 'Your payment went through and the new plan is active.'
- : 'The change takes effect right away.'}
-
- >
- )}
-
- {dismissible ? (
-
- ) : null}
-
- );
-}
-
-export default BridgeCheckoutNotice;
diff --git a/bridge-react/src/components/subscription/BridgePaywall.tsx b/bridge-react/src/components/subscription/BridgePaywall.tsx
deleted file mode 100644
index d49921a..0000000
--- a/bridge-react/src/components/subscription/BridgePaywall.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * Billing 2.0 — ported from bridge-svelte's `BridgePaywall.svelte` (via bridge-nextjs).
- *
- * Fullscreen plan-selection paywall. Drop into the root layout to gate
- * unsubscribed users before they reach the app. While the subscription status
- * is known and the tenant has no plan selected (and the app hasn't opted out
- * via `paymentsAutoRedirect: false`), it renders a fullscreen modal with
- * `` inside; otherwise it renders its children.
- *
- * Data source mirrors svelte: the Stripe-direct subscription slice
- * (`useBridgeStore((s) => s.subscription)` + `loadSubscription()`), NOT the
- * auth-core billing surface — same source `` uses, so the gate
- * and the picker stay in lockstep.
- *
- * Reactive translation (§5.1): svelte `$derived($subscriptionStore.*)` → Zustand
- * selector + `useMemo`; `onMount(loadSubscription)` → `useEffect`;
- * `{#if}/{:else}` → JSX; `{@render children?.()}` → `{children}`.
- *
- * Prop names hold the svelte public contract (`successRedirect` /
- * `cancelRedirect`) and pass straight through to ``, which
- * builds the absolute Stripe return URL (routing through the OAuth-callback
- * confirm-checkout handler) internally.
- */
-import { useEffect, useMemo, type ReactNode } from 'react';
-import type { Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core';
-import { ensureSubscription, useBridgeStore } from '../../core/bridge-instance';
-import { PlanSelector } from './PlanSelector';
-
-export interface BridgePaywallProps {
- /** Where to send the user after a successful Stripe payment. @default '/' */
- successRedirect?: string;
- /** Where to send the user if they cancel Stripe Checkout. @default '/' */
- cancelRedirect?: string;
- /** Called after free-plan or direct plan change (not the Stripe redirect path). Use for analytics side-effects. */
- onSelect?: (detail: { plan: Plan; price: PriceOfferSdk }) => void;
- /** Override the default "Choose a plan" heading. */
- heading?: ReactNode;
- children?: ReactNode;
-}
-
-export function BridgePaywall({
- successRedirect = '/',
- cancelRedirect = '/',
- onSelect,
- heading,
- children,
-}: BridgePaywallProps) {
- const subscription = useBridgeStore((s) => s.subscription);
- const { status, loading } = subscription;
-
- useEffect(() => {
- // 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
- // no plan selected. Respects paymentsAutoRedirect: false (opt-out flag).
- const showPaywall = useMemo(
- () =>
- !loading &&
- !!status?.shouldSelectPlan &&
- status?.paymentsAutoRedirect !== false,
- [loading, status],
- );
-
- if (!showPaywall) {
- return <>{children}>;
- }
-
- return (
-
-
- {heading ??
Choose a plan
}
-
-
-
- );
-}
-
-export default BridgePaywall;
diff --git a/bridge-react/src/components/subscription/BridgePaywallPage.tsx b/bridge-react/src/components/subscription/BridgePaywallPage.tsx
deleted file mode 100644
index 3f348bb..0000000
--- a/bridge-react/src/components/subscription/BridgePaywallPage.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * TBP-743 (port of bridge-svelte TBP-702) — a paywall page at an address of
- * the app's choosing, e.g. onboarding at /welcome:
- *
- * } />
- *
- *
- * `` already serves a paywall at /subscription/plan; this
- * is only for an app that wants its own. The paywall redirect has to know the
- * address before this page has ever been visited — that is what the config
- * line is for. Mounted anywhere else, this page says so in the dev console.
- *
- * A completed checkout lands on `billing.successRoute` (the subscription page,
- * with a confirmation banner, by default); a cancelled one comes back here.
- */
-import { useEffect, type ReactNode } from 'react';
-import type { Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core';
-import { ensureSubscription } from '../../core/bridge-instance';
-import { billingRoutes } from '../../core/billing-routes';
-import { isDevBuild } from '../../core/realtime-dev-badge';
-import { logger } from '../../utils/logger';
-import { PlanSelector } from './PlanSelector';
-
-export interface BridgePaywallPageProps {
- /** The page heading. @default 'Choose a plan' */
- heading?: ReactNode;
- /** Content between the heading and the plans — a welcome line, a checklist. */
- children?: ReactNode;
- /** Where a completed checkout lands. @default `billing.successRoute`, else the subscription page */
- successRedirect?: string;
- /** Where a cancelled checkout lands. @default this page */
- cancelRedirect?: string;
- /** Called after a free-plan or direct plan change (not the Stripe redirect path). */
- onSelect?: (detail: { plan: Plan; price: PriceOfferSdk }) => void;
-}
-
-export function BridgePaywallPage({
- heading = 'Choose a plan',
- children,
- successRedirect,
- cancelRedirect,
- onSelect,
-}: BridgePaywallPageProps) {
- const routes = billingRoutes();
- const here = typeof window !== 'undefined' ? window.location.pathname : '/';
-
- useEffect(() => {
- void ensureSubscription();
- if (isDevBuild() && routes.paywallRoute !== here) {
- logger.warn(
- `[bridge] is on ${here}, but plan-less workspaces are sent to ` +
- `${routes.paywallRoute ?? '(nowhere — the paywall redirect is off)'}. ` +
- `Add billing: { paywallRoute: '${here}' } to 's config.`,
- );
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- return (
-
- {typeof heading === 'string' ?
{heading}
: heading}
- {children}
-
-
- );
-}
-
-export default BridgePaywallPage;
diff --git a/bridge-react/src/components/subscription/BridgeQuotaBanner.tsx b/bridge-react/src/components/subscription/BridgeQuotaBanner.tsx
deleted file mode 100644
index a688f3c..0000000
--- a/bridge-react/src/components/subscription/BridgeQuotaBanner.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Billing 2.0 / Phase C / US-11 (TBP-263) — ported from bridge-svelte's
- * `BridgeQuotaBanner.svelte` (via bridge-nextjs).
- *
- * Live "approaching cap" / "over cap" notice for a single metric. Reads
- * auth-core's `useBridge().quota(metric)` so initial hydration + live
- * `quota.updated` pushes flow into the UI without any consumer wiring.
- *
- * Renders NOTHING while:
- * - the metric has no quota configured on the plan (server returns null), OR
- * - usage is below 80% of the limit (warningLevel === null).
- *
- * Three visible states: approaching (80-94%) → 'warn', critical (95-99%) →
- * 'critical', over-cap (used > limit) → 'critical' (different copy).
- *
- * Two role variants (admin / member): admins get an Upgrade CTA; members get
- * an informational variant. Reuses the BridgeBillingNotice severity tokens.
- *
- * Reactive translation (§5.1): svelte `$state(quota(metric))` +
- * `onMount(quotas.subscribe)` + `$effect(re-hydrate on metric change)` →
- * `useSyncExternalStore` over the quota store + a `metric`-keyed `useEffect`;
- * `$derived(...)` → `useMemo`.
- */
-import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
-import { useBridge, type QuotaSnapshot } from '@nebulr-group/bridge-auth-core';
-import { getBridgeAuth } from '../../core/bridge-instance';
-import { billingRoutes } from '../../core/billing-routes';
-
-type Chassis = 'rail';
-type Severity = 'warn' | 'critical';
-
-export interface BridgeQuotaBannerProps {
- /** Metric key to watch (e.g. 'ai_completions', 'bridge.active_users'). */
- metric: string;
- /**
- * Visual chassis variant. Only 'rail' is implemented in US-11; bar / card
- * variants land alongside the full design pack rollout.
- */
- chassis?: Chassis;
- /** Optional class applied to the root element. */
- className?: string;
- /** Override the default Upgrade CTA click handler. */
- onActionClick?: (snap: QuotaSnapshot) => void;
- /**
- * CTA destination for this instance. Overrides `billing.manageRoute`
- * config; `onActionClick` takes precedence over both.
- */
- actionHref?: string;
- /**
- * Optional display label override. Defaults to the snapshot's `.label` (raw
- * metric key for US-11; the framework wrapper will eventually supply a
- * humanized label).
- */
- label?: string;
-}
-
-export function BridgeQuotaBanner({
- metric,
- chassis = 'rail',
- className = '',
- onActionClick,
- actionHref,
- label,
-}: BridgeQuotaBannerProps) {
- const bridgeBilling = useBridge();
-
- // Subscribe to the quota store; re-read `quota(metric)` on every push. The
- // store's `quota(metric)` triggers lazy hydration on first call (store
- // dedupes repeats), so reading it inside getSnapshot drives initial fetch.
- const lastRef = useRef(undefined);
- const snapshot = useSyncExternalStore(
- (onChange) =>
- bridgeBilling.quotas.subscribe((m) => {
- if (m === metric) onChange();
- }),
- () => {
- const next = bridgeBilling.quota(metric);
- if (sameSnap(lastRef.current, next)) return lastRef.current;
- lastRef.current = next;
- return next;
- },
- () => lastRef.current,
- );
-
- // Role variant mirrors BridgeBillingNotice: CTA only for the workspace
- // owner (v1 canManageBilling() policy). Member variant renders otherwise.
- const [isBillingAdmin, setIsBillingAdmin] = useState(false);
-
- useEffect(() => {
- try {
- setIsBillingAdmin(getBridgeAuth().canManageBilling());
- } catch {
- // No BridgeAuth instance — render the member variant.
- }
- }, []);
-
- // Re-trigger hydration when the metric prop changes mid-mount (svelte
- // `$effect(() => { snapshot = quota(metric); })`).
- useEffect(() => {
- bridgeBilling.quota(metric);
- // bridgeBilling is the auth-core singleton — stable.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [metric]);
-
- const warningLevel = snapshot?.warningLevel ?? null;
- const overCap = snapshot ? snapshot.used > snapshot.limit : false;
- const visible = snapshot !== undefined && warningLevel !== null;
- const severity: Severity =
- warningLevel === 'critical' || overCap ? 'critical' : 'warn';
- const displayLabel = label ?? snapshot?.label ?? metric;
- const percent = useMemo(
- () =>
- snapshot && snapshot.limit > 0
- ? Math.min(100, Math.round((snapshot.used / snapshot.limit) * 100))
- : 0,
- [snapshot],
- );
-
- const copy = useMemo(
- () => getCopy(snapshot, isBillingAdmin, displayLabel, warningLevel),
- [snapshot, isBillingAdmin, displayLabel, warningLevel],
- );
-
- function handleAction(): void {
- if (!snapshot) return;
- if (onActionClick) {
- onActionClick(snapshot);
- return;
- }
- // Destination priority: `actionHref` prop → `billing.manageRoute` config
- // → '/subscription'. `getBridgeConfig()` returns null before the provider
- // initializes, so this can never throw.
- if (typeof window !== 'undefined') {
- window.location.href = actionHref ?? billingRoutes().manageRoute;
- }
- }
-
- if (!visible || !snapshot) return null;
-
- return (
-
-
- {copy.title}
- {copy.body}
-
-
-
-
- {copy.cta && isBillingAdmin && (
-
- )}
-
- );
-}
-
-function getCopy(
- snap: QuotaSnapshot | undefined,
- admin: boolean,
- displayLabel: string,
- warningLevel: QuotaSnapshot['warningLevel'] | null,
-): { title: string; body: string; cta?: string } {
- if (!snap) return { title: '', body: '' };
- const over = snap.used > snap.limit;
- const remaining = Math.max(0, snap.remaining);
- if (over) {
- return admin
- ? {
- title: `${displayLabel} over cap`,
- body: `You've used ${snap.used.toLocaleString()} of ${snap.limit.toLocaleString()}. Upgrade your plan to add headroom.`,
- cta: 'Upgrade',
- }
- : {
- title: `${displayLabel} over cap`,
- body: `Your workspace is over its ${displayLabel} cap. Contact your workspace owner.`,
- };
- }
- if (warningLevel === 'critical') {
- return admin
- ? {
- title: `${displayLabel} near cap`,
- body: `You've used ${snap.used.toLocaleString()} of ${snap.limit.toLocaleString()} (${remaining.toLocaleString()} left). Upgrade to avoid hitting the cap.`,
- cta: 'Upgrade',
- }
- : {
- title: `${displayLabel} near cap`,
- body: `Your workspace is approaching its ${displayLabel} cap. Contact your workspace owner.`,
- };
- }
- // approaching
- return admin
- ? {
- title: `${displayLabel} approaching cap`,
- body: `You've used ${snap.used.toLocaleString()} of ${snap.limit.toLocaleString()} (${remaining.toLocaleString()} left).`,
- cta: 'Upgrade',
- }
- : {
- title: `${displayLabel} approaching cap`,
- body: `Your workspace is approaching its ${displayLabel} cap.`,
- };
-}
-
-function sameSnap(a: QuotaSnapshot | undefined, b: QuotaSnapshot | undefined): boolean {
- if (a === b) return true;
- if (!a || !b) return false;
- return (
- a.used === b.used &&
- a.limit === b.limit &&
- a.remaining === b.remaining &&
- a.warningLevel === b.warningLevel &&
- a.label === b.label
- );
-}
-
-export default BridgeQuotaBanner;
diff --git a/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx b/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx
deleted file mode 100644
index 136288b..0000000
--- a/bridge-react/src/components/subscription/BridgeSubscriptionStatus.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Billing 2.0 / Phase A / US-2 (TBP-248) — ported from bridge-svelte's
- * `BridgeSubscriptionStatus.svelte` (via bridge-nextjs).
- *
- * Drop-in component that renders the workspace's current canonical plan name
- * + subscription status. Reads auth-core's billing `useBridge().subscription`
- * surface (the new billing-specific reactive surface — parallel to FF 2.0's
- * BridgeFlags). Do NOT confuse with the older `` which consumes
- * the Stripe-direct path via the bridge store's `subscription` slice.
- *
- * Reactive translation (§5.1): svelte `$state(useBridge().subscription.snapshot())`
- * + `onMount(() => subscription.subscribe(...))` → `useBridgeSnapshot(subscribe,
- * getSnapshot)`. The read on mount (`ensureBillingState()`) stays in a `useEffect`.
- *
- * 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 { ensureBillingState } from '../../core/billing-state';
-import { useBridgeSnapshot } from '../../hooks/use-bridge-readable';
-
-export interface BridgeSubscriptionStatusProps {
- /** Optional class applied to the root span. */
- className?: string;
-}
-
-export function BridgeSubscriptionStatus({
- className = '',
-}: BridgeSubscriptionStatusProps) {
- const subscription = useBridge().subscription;
-
- const snapshot = useBridgeSnapshot(
- (onChange) => subscription.subscribe(() => onChange()),
- () => subscription.snapshot(),
- );
-
- useEffect(() => {
- // 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 (
-
- {snapshot.loading ? (
- Loading…
- ) : snapshot.error ? (
- Subscription unavailable
- ) : snapshot.state ? (
- <>
- {snapshot.state.plan.name}
-
- {snapshot.state.status}
-
- >
- ) : (
- No subscription
- )}
-
- );
-}
-
-export default BridgeSubscriptionStatus;
diff --git a/bridge-react/src/components/subscription/BridgeUpgradeDialog.tsx b/bridge-react/src/components/subscription/BridgeUpgradeDialog.tsx
deleted file mode 100644
index f65853f..0000000
--- a/bridge-react/src/components/subscription/BridgeUpgradeDialog.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-/**
- * TBP-743 (port of bridge-svelte TBP-703/756) — the upgrade dialog.
- * `` mounts it; the app writes nothing.
- *
- * When the app's backend refuses a request because a plan limit is reached
- * (402, code QUOTA_EXCEEDED — bridge-nestjs's @RequireQuota), it opens, names
- * the metric and the numbers, and links to the refusal's `fix` path or
- * `billing.manageRoute` (default /subscription). A member who cannot manage
- * billing is told to contact the workspace owner instead, with no Upgrade link.
- *
- * With no refusal and a `feature` set, it opens in its feature variant ("This
- * feature isn't on your plan", naming the plans that include it). That happens
- * only after the person did something gated; a page that merely renders a
- * hidden feature never opens it.
- *
- * `billing.upgradeDialog: false` turns it off; a component there replaces it
- * and receives the same props. Decoration only: the backend already refused
- * the write. This explains why.
- */
-import { useEffect, useRef } from 'react';
-import type { BridgeUpgradeDialogProps } from '../../types/config';
-import { quotaMemberBody } from '../../core/billing-role';
-import { plansIncludingFeature } from '../../core/upgrade-dialog';
-
-export type { BridgeUpgradeDialogProps };
-
-export function BridgeUpgradeDialog({
- refusal,
- upgradeHref,
- canUpgrade,
- onClose,
- feature = null,
- plans = null,
-}: BridgeUpgradeDialogProps) {
- const dialogRef = useRef(null);
- const featureVariant = !refusal && feature != null;
- const isOpen = !!refusal || featureVariant;
-
- useEffect(() => {
- const dialog = dialogRef.current;
- if (!dialog) return;
- try {
- if (isOpen && !dialog.open) dialog.showModal();
- else if (!isOpen && dialog.open) dialog.close();
- } catch {
- // No modal support (an old browser, a test DOM): fall back to the attribute.
- if (isOpen) dialog.setAttribute('open', '');
- else dialog.removeAttribute('open');
- }
- }, [isOpen]);
-
- const hasNumbers = refusal?.used != null && refusal?.limit != null;
- const includedIn = plansIncludingFeature(plans, feature);
-
- const actions = canUpgrade ? (
-