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 ( + }> +

{`${at.pathname}${at.search}`}

+ {page(at.pathname)} +
+ ); + } + render( + + + , + ); + return { visits, navigate: (to: string) => act(() => go(to)) }; +} + +const path = () => screen.getByTestId('path').textContent; + +afterEach(() => { + cleanup(); + resetClient(); +}); + +describe('the route guard', () => { + const rules = [{ match: '/', public: true }, { match: '/reports', featureFlag: 'reports' }]; + + it('sends a visitor to sign-in with the page to come back to, and lets them on public pages', async () => { + const { config } = setup({ rules }); + const { navigate } = harness({ ...config, rules }, '/settings', () => null); + await waitFor(() => expect(path()).toBe('/auth/sign-in?redirectUri=%2Fsettings')); + navigate('/'); + await waitFor(() => expect(path()).toBe('/')); + expect(screen.queryByTestId('loading')).toBeNull(); + }); + + it('keeps a page behind its flag, and sends a signed-in person on from sign-in', async () => { + const { client, config } = setup({ rules }); + await client.ready; + await client.signIn.start({ email: 'alice@acme.test', password: PASSWORD }); + const { navigate } = harness({ ...config, rules }, '/settings', () => null); + await waitFor(() => expect(path()).toBe('/settings')); + navigate('/reports'); + await waitFor(() => expect(path()).toBe('/')); + navigate('/auth/sign-in?redirectUri=%2Fsettings'); + await waitFor(() => expect(path()).toBe('/settings')); + }); + + it('sends a signed-out person to sign-in when the session ends', async () => { + const { client, config } = setup({ rules }); + await client.ready; + await client.signIn.start({ email: 'alice@acme.test', password: PASSWORD }); + harness({ ...config, rules }, '/settings', () => null); + await waitFor(() => expect(path()).toBe('/settings')); + await act(() => client.signOut()); + await waitFor(() => expect(path()).toBe('/auth/sign-in?redirectUri=%2Fsettings')); + }); +}); + +describe('email links and the auth pages', () => { + it('sends an email link to its page, keeping the token in the fragment', async () => { + const { config } = setup(); + const { visits } = harness(config, '/auth#bridge=reset-password&token=abc', () => null); + await waitFor(() => expect(visits).toContain('/auth/set-password#bridge=reset-password&token=abc')); + }); + + it('sends the bare auth base to sign-in', async () => { + const { config } = setup(); + harness(config, '/auth?lang=sv', () => null); + await waitFor(() => expect(path()).toBe('/auth/sign-in?lang=sv')); + }); + + it('serves each page from one route, and nothing for an unknown one', async () => { + const { config } = setup(); + const { navigate } = harness(config, '/auth/sign-in', () => } />); + await waitFor(() => expect(document.querySelector('[data-bridge-auth-route="sign-in"] #login-email')).not.toBeNull()); + navigate('/auth/forgot-password'); + await waitFor(() => expect(document.querySelector('[data-bridge-forgot-password="form"]')).not.toBeNull()); + navigate('/auth/nope'); + await waitFor(() => expect(screen.getByTestId('not-found')).not.toBeNull()); + }); +}); + +describe('a sign-in request in the address', () => { + const REQUEST = 'r'.repeat(43); + + it('is taken once, and the same page is loaded without it', async () => { + const { client, config } = setup({ handoff: { requests: true } }); + harness({ ...config, handoff: { requests: true } }, `/auth/sign-in?request=${REQUEST}&lang=sv`, () => null); + await waitFor(() => expect(path()).toBe('/auth/sign-in?lang=sv')); + expect(await client.request.current()).toBe(REQUEST); + }); + + it('is left alone on a page that does not sign in for requests', async () => { + const { client, config } = setup(); + harness(config, `/auth/sign-in?request=${REQUEST}`, () => null); + await waitFor(() => expect(screen.queryByTestId('loading')).toBeNull()); + expect(path()).toBe(`/auth/sign-in?request=${REQUEST}`); + expect(await client.request.current()).toBeNull(); + }); +}); diff --git a/bridge-react/src/components/BridgeProvider.tsx b/bridge-react/src/components/BridgeProvider.tsx new file mode 100644 index 0000000..60cd82c --- /dev/null +++ b/bridge-react/src/components/BridgeProvider.tsx @@ -0,0 +1,200 @@ +/** + * ``: wrap the app in it, once, around the router's pages. + * It makes the page's Bridge client, sends email links to their pages, + * guards every navigation with the route rules, runs the guard again when + * the session or the flags change (a sign-out in another tab, a workspace + * switch, a flag turned off), and renders the upgrade dialog a plan limit + * opens. + * + * ```tsx + * const config: BridgeConfig = { issuer: import.meta.env.VITE_BRIDGE_ISSUER, rules: [{ match: '/', public: true }] }; + * + * ``` + * + * Define `config` outside the component (or memoise it): a new object is a + * new configuration. + */ +import { readEmailLink, readReturnTo, type Bridge } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { startClient } from '../core/client.js'; +import { resolveConfig, type BridgeConfig, type ResolvedConfig } from '../core/config.js'; +import { decide, normalizePath, type GuardDecision } from '../core/guard.js'; +import { authPageAt, isUnder, pageForLink } from '../core/routes.js'; +import { browserLocation, browserNavigate, setRouter, type BridgeLocation, type BridgeRouter } from '../core/router.js'; +import { closeUpgrade } from '../core/upgrade.js'; +import { RouterContext } from '../react/context.js'; +import { useCanManageBilling, useFlags, useFlagsStatus, useSession, useUpgradeRequest, useWatch } from '../react/hooks.js'; +import UpgradeDialog from './billing/UpgradeDialog.js'; + +/** How long a navigation waits for Bridge before deciding as if nobody were signed in. */ +const READY_WAIT_MS = 8000; + +function within(promise: Promise, ms: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(undefined), ms); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + () => { + clearTimeout(timer); + resolve(undefined); + }, + ); + }); +} + +export interface BridgeProviderProps { + /** The settings. The one required one is `issuer`. */ + readonly config: BridgeConfig; + /** + * Your router's location and navigate function, so the router sees every + * navigation the package makes. @default the browser's history + */ + readonly router?: BridgeRouter; + /** Shown while the first navigation waits for Bridge. @default nothing */ + readonly loading?: ReactNode; + /** Shown when a page's flag is off and its redirect is the page itself. */ + readonly forbidden?: ReactNode; + readonly children?: ReactNode; +} + +/** Where a navigation must go before the guard decides, or null. */ +function preGuard(config: ResolvedConfig, location: BridgeLocation): string | null { + const path = normalizePath(location.pathname); + // An email link lands on the email-links address with its token in the fragment: on to its page. + const link = readEmailLink(location.hash); + if (link !== null) { + const page = `${config.authBase}/${pageForLink(link)}`; + if (path !== page) return `${page}${location.hash}`; + } + if (config.authBase !== '' && path === config.authBase) return `${config.authBase}/sign-in${location.search}`; + return null; +} + +/** Who the flag results are for: they are fetched again whenever it changes. */ +function sessionKey(client: Bridge): string { + const s = client.session.get(); + return s.status === 'signed-in' ? `${s.user.id}|${s.workspace?.id ?? ''}` : s.status; +} + +export function BridgeProvider({ config, router, loading = null, forbidden, children }: BridgeProviderProps) { + const resolved = useMemo(() => resolveConfig(config), [config]); + const client = useMemo(() => startClient(resolved), [resolved]); + + const browserAt = useWatch(browserLocation); + const active: BridgeRouter = router ?? { location: browserAt, navigate: browserNavigate }; + const location = active.location; + const navigateRef = useRef(active.navigate); + navigateRef.current = active.navigate; + const stableRouter = useMemo( + () => ({ location, navigate: (to, options) => navigateRef.current(to, options) }), + [location.pathname, location.search, location.hash], + ); + useLayoutEffect(() => { + setRouter(stableRouter); + }, [stableRouter]); + useEffect(() => () => setRouter(null), []); + + const session = useSession(); + useFlags(); + const flagsStatus = useFlagsStatus(); + + // The client's start: its metadata read and any kept session restored, or a time limit. + const [ready, setReady] = useState(false); + useEffect(() => { + let live = true; + setReady(false); + void within(client.ready, READY_WAIT_MS).then(() => { + if (live) setReady(true); + }); + return () => { + live = false; + }; + }, [client]); + + // A sign-in request in the address is taken once, then the page loads again without it: while it is unspent, + // anyone holding it could sign in on it. + const requestInAddress = resolved.signInRequests && new URLSearchParams(location.search).has('request'); + useEffect(() => { + if (!requestInAddress) return; + const params = new URLSearchParams(location.search); + const request = params.get('request') ?? ''; + let live = true; + void client.request + .use(request) + .catch(() => undefined) + .finally(() => { + if (!live) return; + params.delete('request'); + const query = params.toString(); + stableRouter.navigate(`${location.pathname}${query === '' ? '' : `?${query}`}${location.hash}`, { replace: true }); + }); + return () => { + live = false; + }; + }, [client, requestInAddress, location.search]); + + const before = preGuard(resolved, location); + useEffect(() => { + if (before !== null) stableRouter.navigate(before, { replace: true }); + }, [before]); + + // Flag results for this person and workspace: a page behind a flag waits for them (or a time limit). + const path = normalizePath(location.pathname); + const flagsNeeded = authPageAt(path, resolved.authBase) === null; + const key = ready ? sessionKey(client) : 'starting'; + const [flagsWaitedFor, setFlagsWaitedFor] = useState(null); + useEffect(() => { + if (!ready || !flagsNeeded || flagsStatus === 'ready' || flagsWaitedFor === key) return; + let live = true; + void within(client.flags.load(), READY_WAIT_MS).then(() => { + if (live) setFlagsWaitedFor(key); + }); + return () => { + live = false; + }; + }, [ready, flagsNeeded, flagsStatus, key, flagsWaitedFor, client]); + + const settled = ready && !requestInAddress && before === null && (!flagsNeeded || flagsStatus === 'ready' || flagsWaitedFor === key); + // A path under the auth base that is none of its pages is ``'s not-found, for everyone. + const unknownAuthPage = resolved.authBase !== '' && isUnder(path, resolved.authBase) && flagsNeeded; + const decision: GuardDecision | null = !settled + ? null + : unknownAuthPage + ? { type: 'allow' } + : decide(resolved, { + path: location.pathname, + target: `${path}${location.search}`, + session, + flags: client.flags, + returnTo: readReturnTo(location.search, resolved.returnToParam), + }); + + useEffect(() => { + if (decision?.type === 'sign-in' || decision?.type === 'redirect') stableRouter.navigate(decision.to, { replace: true }); + }, [decision?.type, decision?.type === 'sign-in' || decision?.type === 'redirect' ? decision.to : null]); + + // While the guard waits again (a reload of the flags after a sign-in), the page it allowed stays on screen. + const allowed = useRef(null); + if (decision?.type === 'allow') allowed.current = `${path}${location.search}`; + else if (decision !== null) allowed.current = null; + const showPage = decision?.type === 'allow' || (decision === null && allowed.current === `${path}${location.search}`); + + const request = useUpgradeRequest(); + const mayUpgrade = useCanManageBilling(); + const Dialog = resolved.upgradeDialog === true || resolved.upgradeDialog === false ? UpgradeDialog : resolved.upgradeDialog; + const upgradeHref = resolved.paywall ?? `${resolved.billingBase}/plan`; + + return ( + + {showPage ? children : decision?.type === 'forbidden' ? (forbidden ??

Forbidden

) : loading} + {resolved.upgradeDialog !== false && request !== null && ( + + )} +
+ ); +} + +export default BridgeProvider; diff --git a/bridge-react/src/components/ProfileName.tsx b/bridge-react/src/components/ProfileName.tsx deleted file mode 100644 index 614acf2..0000000 --- a/bridge-react/src/components/ProfileName.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import type { HTMLAttributes } from 'react'; -import { useBridgeStore } from '../core/bridge-instance'; - -/** - * Displays the current user's full name (or email fallback) when authenticated. - * Renders nothing when no profile is loaded. - * - * Ports `bridge-svelte/src/lib/client/components/ProfileName.svelte` (via - * bridge-nextjs). The data source is the bridge Zustand store — the component - * re-renders automatically when `auth:profile` fires. - */ -export function ProfileName({ - className, - style, - ...rest -}: HTMLAttributes): JSX.Element | null { - const profile = useBridgeStore((s) => s.profile); - const displayName = profile?.fullName || profile?.email || ''; - if (!displayName) return null; - return ( - - {displayName} - - ); -} - -export default ProfileName; diff --git a/bridge-react/src/components/auth/BridgeAuthRoutes.tsx b/bridge-react/src/components/auth/BridgeAuthRoutes.tsx new file mode 100644 index 0000000..6f1879b --- /dev/null +++ b/bridge-react/src/components/auth/BridgeAuthRoutes.tsx @@ -0,0 +1,126 @@ +/** + * Every sign-in page from one route: mount it on `/auth/*` in your router. + * + * ```tsx + * } /> + * ``` + * + * Serves sign-in, sign-up, verify-email, forgot-password, set-password, + * invite, workspaces, handoff, magic-link (a sign-in link's landing), + * passkey-setup (a passkey setup link's landing) and callback (hosted mode's + * return from Bridge's page). An unknown page renders `notFound`. + * + * Customising, in rungs: + * 1. `--bridge-*` CSS tokens restyle the forms. + * 2. `frame(page, form)` replaces everything around the form on every page; + * `heading(page)` replaces the form's heading on each page. + * 3. To own one page, add a route for it before `/auth/*` + * (`} />`): routers + * prefer the specific route, and the other pages keep working. + * 4. Headless: build on `getBridge()`. + */ +import { readReturnTo } from '@nebulr-group/bridge-auth-core'; +import type { ReactNode } from 'react'; +import { peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { normalizePath } from '../../core/guard.js'; +import { authPageAt, type AuthPage } from '../../core/routes.js'; +import { useBridgeConfig, useBridgeRouter, useSignedIn, useTranslator } from '../../react/hooks.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { ForgotPassword } from './ForgotPassword.js'; +import { HandoffSignIn } from './HandoffSignIn.js'; +import { HostedCallback } from './HostedCallback.js'; +import { HostedSignIn } from './HostedSignIn.js'; +import { InviteLanding } from './InviteLanding.js'; +import { MagicLinkLanding } from './MagicLinkLanding.js'; +import { PasskeySetupLanding } from './PasskeySetupLanding.js'; +import { SetPassword } from './SetPassword.js'; +import { SignInForm } from './SignInForm.js'; +import { SignUpForm } from './SignUpForm.js'; +import { VerifyEmail } from './VerifyEmail.js'; +import { WorkspaceChooser } from './WorkspaceChooser.js'; + +export interface BridgeAuthRoutesProps { + /** Where this route is mounted, when not at the config's `auth.base` (a second, framed set of pages). @default `auth.base` */ + readonly base?: string; + /** Replaces everything around the form, on every page. */ + readonly frame?: (page: AuthPage, form: ReactNode) => ReactNode; + /** Replaces the form's heading, per page. */ + readonly heading?: (page: AuthPage) => ReactNode; + readonly messages?: BridgeMessages; + /** Shown for a path under the auth base that is none of the pages. @default nothing */ + readonly notFound?: ReactNode; +} + +export function BridgeAuthRoutes({ base, frame, heading, messages, notFound = null }: BridgeAuthRoutesProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = useBridgeConfig() ?? peekConfig(); + const signedIn = useSignedIn(); + const page = authPageAt(normalizePath(router.location.pathname), (base ?? config?.authBase ?? '/auth').replace(/\/+$/, '')); + if (page === null) return <>{notFound}; + + const pageHeading = heading ? heading(page) : undefined; + const props = { heading: pageHeading, messages }; + + function afterSwitch() { + router.navigate(readReturnTo(router.location.search, config?.returnToParam) ?? config?.afterSignIn ?? '/'); + } + + let body: ReactNode; + switch (page) { + case 'sign-in': + body = config?.hosted ? : ; + break; + case 'callback': + body = ; + break; + case 'sign-up': + body = ; + break; + case 'verify-email': + body = ; + break; + case 'forgot-password': + body = ; + break; + case 'set-password': + body = ; + break; + case 'invite': + body = ; + break; + case 'magic-link': + body = ; + break; + case 'passkey-setup': + body = ; + break; + case 'handoff': + body = ; + break; + case 'workspaces': + body = signedIn ? ( + + + + ) : ( + + ); + break; + } + + // Keyed by page: moving between pages starts each one fresh, as a new route would. + const form = {body}; + return ( +
+ {frame ? frame(page, form) :
{form}
} +
+ ); +} + +function AuthPageBody({ children }: { children: ReactNode }) { + return <>{children}; +} + +export default BridgeAuthRoutes; diff --git a/bridge-react/src/components/auth/CallbackHandler.tsx b/bridge-react/src/components/auth/CallbackHandler.tsx deleted file mode 100644 index 3496253..0000000 --- a/bridge-react/src/components/auth/CallbackHandler.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useAuth } from '../../hooks/use-auth'; -import { confirmCheckout, getBridgeAuth, loadSubscription } from '../../core/bridge-instance'; -import { appUsesBilling, billingRoutes } from '../../core/billing-routes'; -import { markCheckoutComplete } from '../../core/checkout-result'; -import { getRouterAdapter } from '../../utils/router-adapter'; -import { sanitizeReturnTo, takeReturnTo } from '@nebulr-group/bridge-auth-core'; - -export interface CallbackHandlerProps { - /** Route to redirect to after a successful code exchange. @default '/' */ - successRoute?: string; - /** Route to redirect to when the callback fails. @default '/login' */ - loginRoute?: string; - /** Route to redirect to when a Stripe checkout confirmation fails. - * @default `billing.paymentErrorRoute` — '/subscription/error' */ - paymentErrorRoute?: string; -} - -/** - * Processes bridge OAuth callback on mount and redirects. - * - Reads `code` and `error` from the current URL - * - Exchanges code via `useAuth().handleCallback` (auth-core singleton) - * - Redirects to `successRoute` on success - * - Redirects to `loginRoute?error=...` on error - * - * Routes default to `/` (success) and `/login` (error); override via props. - * - * Renders nothing. - */ -export function CallbackHandler({ - successRoute = '/', - loginRoute = '/login', - paymentErrorRoute: paymentErrorRouteProp, -}: CallbackHandlerProps = {}) { - const paymentErrorRoute = paymentErrorRouteProp ?? billingRoutes().paymentErrorRoute; - const { handleCallback } = useAuth(); - const didRun = useRef(false); - - useEffect(() => { - if (didRun.current) return; - didRun.current = true; - - const params = new URLSearchParams(window.location.search); - const code = params.get('code'); - const callbackError = params.get('error'); - const sessionId = params.get('session_id'); - const stripeSuccess = params.has('stripe_success'); - const stripeCancel = params.has('stripe_cancel'); - // `redirect` rides on the Stripe return URL, so whoever wrote that link - // controls it. The default router adapter navigates with - // `window.location.replace`, so an unchecked `https://…` or `//host` value - // would bounce the user off-site from our own callback: an open redirect. - // auth-core's `sanitizeReturnTo` admits only a same-origin path; anything - // else falls back to the default, like a missing value does. - // Stripe may append its own ?session_id to the redirect destination — strip it. - const stripeRedirectTo = (sanitizeReturnTo(params.get('redirect')) ?? billingRoutes().manageRoute).split('?')[0]; - - const router = getRouterAdapter(); - - const buildUrl = (path: string, query?: Record) => { - if (!query || Object.keys(query).length === 0) return path; - const qs = new URLSearchParams(query).toString(); - return `${path}?${qs}`; - }; - - const redirect = (path: string, query?: Record) => { - router.replace(buildUrl(path, query)); - }; - - // Preserve allowlisted query params on success redirect (e.g. payment from post-payment callback) - const preserveParams = ['payment']; - const preservedQuery: Record = {}; - preserveParams.forEach((name) => { - const value = params.get(name); - if (value != null) preservedQuery[name] = value; - }); - - // TBP-723 — the paywall check for a Stripe return runs HERE, after the - // checkout is confirmed, not in 's mount effect (which - // skips the callback route). Same order as bridge-svelte's bootstrap: - // confirm → token refresh → paywall. With the refreshed token a paid - // tenant reads shouldSelectPlan:false and lands on its destination; a - // tenant that still has to pick a plan (e.g. a cancelled checkout) goes to - // the paywall, as the next page's bootstrap check would have sent it. - const redirectAfterCheckout = async (destination: string) => { - const routes = billingRoutes(); - const paywallRoute = routes.paywallRoute; - if (paywallRoute && destination !== paywallRoute) { - const bridge = getBridgeAuth(); - const should = await bridge - .shouldRedirectToPaywall() - .catch(() => false); // fail open, like the provider's check - // The default paywall applies only to an app that has plans. - const applies = - should && (!routes.paywallIsDefault || appUsesBilling(await bridge.getPlans().catch(() => null))); - if (applies) return redirect(paywallRoute); - } - return redirect(destination); - }; - - const process = async () => { - try { - // Stripe Checkout return — confirm the session with bridge-api (which - // verifies it with Stripe server-side), refresh tokens so the new JWT - // reads shouldSelectPlan:false, then redirect. Mirrors bridge-svelte's - // BridgeBootstrap callback handling. - if (stripeSuccess && sessionId) { - // confirmStripeCheckout (auth-core) verifies the session with bridge-api - // (which calls Stripe server-side) and refreshes tokens so the new JWT - // reads shouldSelectPlan:false. It throws on a non-OK response or network - // error → caught below → paymentErrorRoute. (TBP-369: shared with - // bridge-svelte so the HTTP + token-refresh logic lives in one place.) - // - // `confirmCheckout` registers the confirmation so the provider's - // paywall check waits for it instead of racing it (TBP-723). - await confirmCheckout(sessionId); - // Refresh the global subscription store so the destination page - // (e.g. PlanSelector on /subscription) renders the now-active plan - // instead of stale "select a plan" state. - await loadSubscription().catch(() => {}); - // TBP-945 (bridge-svelte TBP-813) — the landing page (the - // subscription page by default) says the checkout went through; no - // separate confirmation page. - markCheckoutComplete({ kind: 'checkout' }); - return await redirectAfterCheckout(stripeRedirectTo); - } - if (stripeCancel) { - return await redirectAfterCheckout(stripeRedirectTo); - } - - if (callbackError) { - return redirect(loginRoute, { error: callbackError }); - } - if (!code) { - return redirect(loginRoute, { error: 'no_code' }); - } - await handleCallback(code); - // TBP-629 — restore the deep link stashed before it - // sent this visitor to the hosted portal. One-shot and re-sanitized, and - // null when nothing was stashed — so an app with no deep linking lands - // on `successRoute` exactly as it always did. - // - // `preservedQuery` (today: `payment`) wins: it signals a just-completed - // checkout whose landing page the billing flow owns, and that is a - // deliberate destination rather than a remembered one. - const stashedReturnTo = takeReturnTo(); - if (Object.keys(preservedQuery).length > 0) { - return redirect(successRoute, preservedQuery); - } - return redirect(stashedReturnTo ?? successRoute); - } catch (err) { - const message = err instanceof Error ? err.message : 'auth_failed'; - // A Stripe-confirm failure shouldn't dump the user on the login page. - if (stripeSuccess) return redirect(paymentErrorRoute); - return redirect(loginRoute, { error: message }); - } - }; - - process(); - }, [successRoute, loginRoute, paymentErrorRoute, handleCallback]); - - return null; -} - -export default CallbackHandler; diff --git a/bridge-react/src/components/auth/ForgotPassword.tsx b/bridge-react/src/components/auth/ForgotPassword.tsx new file mode 100644 index 0000000..29911c4 --- /dev/null +++ b/bridge-react/src/components/auth/ForgotPassword.tsx @@ -0,0 +1,79 @@ +/** + * Asks for a reset link. Bridge answers the same whether or not the address + * has an account, so the page always says the email is on its way. + */ +import { useState, type FormEvent, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface ForgotPasswordProps extends HTMLAttributes { + /** Heading: text or your own node. `null` for none. */ + readonly heading?: ReactNode; + /** The line under the heading. `null` for none. */ + readonly description?: ReactNode; + readonly loginHref?: string; + readonly onSent?: (email: string) => void; + readonly messages?: BridgeMessages; +} + +export function ForgotPassword({ heading, description, loginHref, onSent, messages, ...rest }: ForgotPasswordProps) { + const t = useTranslator(messages); + const authBase = peekConfig()?.authBase ?? '/auth'; + const [email, setEmail] = useState(''); + const [loading, setLoading] = useState(false); + const [sent, setSent] = useState(false); + const [failure, setFailure] = useState(null); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (loading) return; + setFailure(null); + setLoading(true); + try { + await getBridge().password.forgot(email.trim()); + setSent(true); + onSent?.(email.trim()); + } catch (error) { + setFailure(errorMessage(error, t, 'forgot.error.send')); + } finally { + setLoading(false); + } + } + + return ( + + {failure && {failure}} + {sent ? ( + {t('forgot.emailSent')} + ) : ( +
void submit(event)}> +
+ + setEmail(e.target.value)} disabled={loading} /> +
+ +
+ )} +
+ + {t('action.backToSignIn')} + +
+
+ ); +} + +export default ForgotPassword; diff --git a/bridge-react/src/components/auth/HandoffSignIn.tsx b/bridge-react/src/components/auth/HandoffSignIn.tsx new file mode 100644 index 0000000..390f4db --- /dev/null +++ b/bridge-react/src/components/auth/HandoffSignIn.tsx @@ -0,0 +1,157 @@ +/** + * Hand-off mode: signs the person in for a program on their own machine, such + * as a command-line tool, and sends the code back to the program's loopback + * address. The program trades the code with its own verifier; no token ever + * reaches this page, and this page's own session is not touched. + * + * It renders only when the config has `handoff: { loopback: true }`, and it + * refuses any request whose return address is not + * `http://127.0.0.1:/callback` or `http://[::1]:/callback`. + */ +import { useState, type FormEvent, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { handoffSignIn, readHandoff, returnToProgram, type HandoffState } from '../../core/handoff.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { PasswordInput } from '../shared/PasswordInput.js'; +import { Spinner } from '../shared/Spinner.js'; +import { WorkspaceChooser } from './WorkspaceChooser.js'; + +export interface HandoffSignInProps extends HTMLAttributes { + /** The program's name, for the copy. @default the config's `handoff.program` */ + readonly program?: string; + /** Replaces the page's heading. */ + readonly heading?: ReactNode; + /** Called with the address the browser is about to go to. */ + readonly onDone?: (returnUrl: string) => void; + readonly messages?: BridgeMessages; +} + +export function HandoffSignIn({ program, heading, onDone, messages, ...rest }: HandoffSignInProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const handoff = peekConfig()?.handoff ?? null; + const name = program ?? handoff?.program ?? ''; + + const [view, setView] = useState(null); + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [loading, setLoading] = useState(false); + const [failure, setFailure] = useState(null); + + useMountOnce(() => { + setView(readHandoff(router.location.search)); + }); + + function settle(next: HandoffState) { + setView(next); + if (next.status === 'done') { + onDone?.(next.returnUrl); + returnToProgram(next); + } + } + + async function submit(event: FormEvent) { + event.preventDefault(); + if (loading || view?.status !== 'ready') return; + setFailure(null); + setLoading(true); + try { + settle(await handoffSignIn(getBridge(), view.request, { email: email.trim(), password })); + } catch (error) { + setFailure(errorMessage(error, t, 'login.error.invalidCredentials')); + } finally { + setLoading(false); + } + } + + async function choose(id: string) { + if (view?.status !== 'workspace') return; + try { + settle(await view.choose(id)); + } catch (error) { + setFailure(errorMessage(error, t, 'workspace.error.select')); + } + } + + const pageHeading = heading === undefined ? t('handoff.heading', { program: name }) : heading; + + if (handoff === null) { + return ( + + {t('handoff.notOffered')} + + ); + } + if (view === null) { + return ( + +
+ +
+
+ ); + } + if (view.status === 'invalid') { + return ( + + {t('handoff.invalid', { program: name })} + + ); + } + if (view.status === 'done') { + return ( + + {t('handoff.done', { program: name })} + + ); + } + if (view.status === 'workspace') { + return ( + + {failure && {failure}} + + + ); + } + return ( + + {failure && {failure}} +
void submit(event)}> +
+ + setEmail(e.target.value)} disabled={loading} /> +
+
+ + +
+ +
+
+ ); +} + +export default HandoffSignIn; diff --git a/bridge-react/src/components/auth/HostedCallback.tsx b/bridge-react/src/components/auth/HostedCallback.tsx new file mode 100644 index 0000000..12fc96d --- /dev/null +++ b/bridge-react/src/components/auth/HostedCallback.tsx @@ -0,0 +1,65 @@ +/** + * Hosted mode (`hosted` in the config), `/callback`: where Bridge's + * hosted page sends the person back. It checks the return (its `state` and + * issuer) and trades the code with the verifier this browser kept, then goes + * on to where the person was going. + */ +import { takeReturnTo } from '@nebulr-group/bridge-auth-core'; +import { useState, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface HostedCallbackProps { + /** Replaces the heading shown when finishing fails. */ + readonly heading?: ReactNode; + readonly messages?: BridgeMessages; +} + +export function HostedCallback({ heading, messages }: HostedCallbackProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + const [failure, setFailure] = useState(null); + + useMountOnce(async () => { + const back = location.href; + // The code and state leave the address bar and the history at once. + history.replaceState(history.state, '', location.pathname); + try { + await getBridge().hosted.finish(back); + router.navigate(takeReturnTo() ?? config?.afterSignIn ?? '/', { replace: true }); + } catch (error) { + setFailure(errorMessage(error, t, 'link.error.invalid')); + } + }); + + if (failure === null) { + return ( + +
+ +
+
+ ); + } + return ( + + {failure} +
+ + {t('action.backToSignIn')} + +
+
+ ); +} + +export default HostedCallback; diff --git a/bridge-react/src/components/auth/HostedSignIn.tsx b/bridge-react/src/components/auth/HostedSignIn.tsx new file mode 100644 index 0000000..fcca6dc --- /dev/null +++ b/bridge-react/src/components/auth/HostedSignIn.tsx @@ -0,0 +1,57 @@ +/** + * Hosted mode (`hosted` in the config), the sign-in page: starts a sign-in + * request at Bridge and sends the browser to the page Bridge hosts for the + * app. `HostedCallback` finishes it when the person comes back. + */ +import { readReturnTo, stashReturnTo } from '@nebulr-group/bridge-auth-core'; +import { useState, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface HostedSignInProps { + /** Replaces the heading shown when starting fails. */ + readonly heading?: ReactNode; + readonly messages?: BridgeMessages; +} + +export function HostedSignIn({ heading, messages }: HostedSignInProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const [failure, setFailure] = useState(null); + + useMountOnce(async () => { + const config = peekConfig(); + try { + const hosted = config?.hosted ?? {}; + const redirectUri = hosted.redirectUri ?? new URL(`${config?.authBase ?? '/auth'}/callback`, location.origin).toString(); + // Where to go once signed in survives the trip to Bridge's page, in this tab. + stashReturnTo(readReturnTo(router.location.search, config?.returnToParam)); + location.assign(await getBridge().hosted.start({ redirectUri, ...(hosted.linkAddress === undefined ? {} : { linkAddress: hosted.linkAddress }) })); + } catch (error) { + setFailure(errorMessage(error, t, 'login.error.invalidCredentials')); + } + }); + + if (failure === null) { + return ( + +
+ +
+
+ ); + } + return ( + + {failure} + + ); +} + +export default HostedSignIn; diff --git a/bridge-react/src/components/auth/InviteLanding.tsx b/bridge-react/src/components/auth/InviteLanding.tsx new file mode 100644 index 0000000..58b2d81 --- /dev/null +++ b/bridge-react/src/components/auth/InviteLanding.tsx @@ -0,0 +1,274 @@ +/** + * Where an invite email lands (`#bridge=invite&token=…`). It takes the token + * from the address, clears it, and shows which workspace the invite is for: + * + * - a person with no account signs up from the invite: no email to verify, + * and they land signed in, in the workspace; + * - a person with an account signs in, and the invite is accepted at once; + * - someone signed in already accepts with one button. + * + * An invite that no longer works says why: revoked, used or expired. One + * sent to another address says so, and offers to sign out. An issuer that + * does not offer invites gets a plain "not offered here yet". + */ +import { isBridgeError, type InvitePreview } from '@nebulr-group/bridge-auth-core'; +import { useState, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { takeEmailLink } from '../../core/email-link.js'; +import { errorMessage, type BridgeMessageKey } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator, useUser } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { Spinner } from '../shared/Spinner.js'; +import { SignInForm } from './SignInForm.js'; +import { SignUpForm } from './SignUpForm.js'; + +export interface InviteLandingProps extends HTMLAttributes { + /** The invite's token. @default read from the page's address */ + readonly token?: string; + /** Replaces the page's heading. */ + readonly heading?: ReactNode; + /** Called once the person is in the workspace. Without it, the page goes to `auth.afterSignIn`. */ + readonly onAccepted?: () => void; + readonly messages?: BridgeMessages; +} + +type Closed = Exclude; +type View = + | { step: 'loading' } + | { step: 'not-offered' } + | { step: 'failed'; message: string } + | { step: 'closed'; state: Closed } + | { step: 'open'; token: string; workspace: string }; + +const CLOSED_COPY: Record = { + revoked: 'invite.state.revoked', + used: 'invite.state.used', + expired: 'invite.state.expired', +}; +const CLOSED_CODES: Record = { invite_revoked: 'revoked', invite_used: 'used', invite_expired: 'expired' }; + +function closedBy(error: unknown): Closed | null { + return isBridgeError(error, 'link-invalid') && error.code !== null ? (CLOSED_CODES[error.code] ?? null) : null; +} + +export function InviteLanding({ token, heading, onAccepted, messages, ...rest }: InviteLandingProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const user = useUser(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + + const [view, setView] = useState({ step: 'loading' }); + /** `auth`: the sign-up or sign-in form. `accept`: signed in, accepting or about to. */ + const [phase, setPhase] = useState<'auth' | 'accept'>('auth'); + const [mode, setMode] = useState<'sign-in' | 'sign-up'>('sign-up'); + const [accepting, setAccepting] = useState(false); + const [failure, setFailure] = useState<{ message: string; code: string | null } | null>(null); + const [notice, setNotice] = useState(null); + + useMountOnce(() => { + const found = token ?? takeEmailLink('invite'); + if (found === null) { + setView({ step: 'failed', message: t('verify.missingLink') }); + return; + } + const bridge = getBridge(); + bridge.invites + .preview(found) + .then((preview) => { + if (preview.state !== 'open') { + setView({ step: 'closed', state: preview.state }); + return; + } + setView({ step: 'open', token: found, workspace: preview.workspace.name ?? '' }); + setMode(preview.account ? 'sign-in' : 'sign-up'); + setPhase(bridge.session.get().status === 'signed-in' ? 'accept' : 'auth'); + }) + .catch((error: unknown) => { + setView(isBridgeError(error, 'not-offered') ? { step: 'not-offered' } : { step: 'failed', message: errorMessage(error, t, 'link.error.invalid') }); + }); + }); + + function done() { + if (onAccepted) onAccepted(); + else router.navigate(config?.afterSignIn ?? '/'); + } + + /** What to say about a refused invite call: the server's code first. */ + function refusal(error: unknown): { message: string; code: string | null } { + const code = isBridgeError(error) ? error.code : null; + if (code === 'invite_for_another_address') return { message: t('invite.wrongAddress'), code }; + if (code === 'already_member') return { message: t('invite.alreadyMember'), code }; + if (code === 'account_exists') return { message: t('invite.accountExists'), code }; + return { message: errorMessage(error, t, 'link.error.invalid'), code }; + } + + async function accept() { + if (view.step !== 'open' || accepting) return; + setPhase('accept'); + setAccepting(true); + setFailure(null); + try { + await getBridge().invites.accept(view.token); + done(); + } catch (error) { + const closed = closedBy(error); + if (closed !== null) setView({ step: 'closed', state: closed }); + else setFailure(refusal(error)); + } finally { + setAccepting(false); + } + } + + function signUpFailed(error: unknown) { + const closed = closedBy(error); + if (closed !== null) { + setView({ step: 'closed', state: closed }); + } else if (isBridgeError(error) && error.code === 'account_exists') { + // The address has an account after all: sign in, and the invite is accepted on the way. + setMode('sign-in'); + setNotice(t('invite.accountExists')); + } + } + + async function signOut() { + setFailure(null); + await getBridge() + .signOut() + .catch(() => undefined); + setPhase('auth'); + setMode('sign-in'); + } + + const named = (fallback: ReactNode) => (heading === undefined ? fallback : heading); + + if (view.step === 'loading') { + return ( + +
+ +
+
+ ); + } + if (view.step === 'not-offered') { + return ( + + {t('invite.notOffered')} + + ); + } + if (view.step === 'failed') { + return ( + + {view.message} + + ); + } + if (view.step === 'closed') { + return ( + + {t(CLOSED_COPY[view.state])} +
+ + {t('action.backToSignIn')} + +
+
+ ); + } + if (phase === 'accept') { + return ( + + {failure && {failure.message}} + {failure?.code === 'invite_for_another_address' ? ( + + ) : failure?.code === 'already_member' ? ( + + ) : ( + <> + {user?.email && ( +

+ {t('invite.signedInAs', { email: user.email })} +

+ )} + + + )} +
+ ); + } + return ( + + {notice && {notice}} + {mode === 'sign-in' ? ( + void accept()} + messages={messages} + footer={ +
+ {t('login.signupPrompt')}{' '} + +
+ } + /> + ) : ( + + {t('signup.loginPrompt')}{' '} + + + } + /> + )} +
+ ); +} + +export default InviteLanding; diff --git a/bridge-react/src/components/auth/Login.tsx b/bridge-react/src/components/auth/Login.tsx deleted file mode 100644 index 29350e1..0000000 --- a/bridge-react/src/components/auth/Login.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { useAuth } from '../../hooks'; - -interface LoginProps { - redirectUri?: string; -} - -export function Login({ redirectUri }: LoginProps) { - const { login } = useAuth(); - - const handleLogin = () => { - login({ redirectUri }); - }; - - return ( - - ); -} - diff --git a/bridge-react/src/components/auth/MagicLinkLanding.tsx b/bridge-react/src/components/auth/MagicLinkLanding.tsx new file mode 100644 index 0000000..886d578 --- /dev/null +++ b/bridge-react/src/components/auth/MagicLinkLanding.tsx @@ -0,0 +1,132 @@ +/** + * Signs in from a sign-in link (a magic link), on the device that asked for + * it. Opened on another device it says so, and the link still works on the + * right one. The link works once: opened again, it says the link is no + * longer valid. + * + * With `storage: 'memory'` the verifier waited in localStorage, which every + * tab of the origin shares, so the tab the link opens in signs in itself and + * holds the session in its own memory. + */ +import { isBridgeError, type SignInStep, type WorkspaceChoice } from '@nebulr-group/bridge-auth-core'; +import { useState, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { takeEmailLink } from '../../core/email-link.js'; +import { bounded, handOff, leave } from '../../core/finish-link.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { Spinner } from '../shared/Spinner.js'; +import { WorkspaceChooser } from './WorkspaceChooser.js'; + +export interface MagicLinkLandingProps extends Omit, 'onError'> { + /** The link's token. @default read from the page's address */ + readonly token?: string; + /** Replaces the page's heading. */ + readonly heading?: ReactNode; + /** Called once signed in. Without it, the page goes to `auth.afterSignIn`. */ + readonly onSignIn?: () => void; + readonly onError?: (error: unknown) => void; + readonly messages?: BridgeMessages; +} + +type View = + | { step: 'working' } + | { step: 'signed-in'; to: string } + | { step: 'workspace'; workspaces: readonly WorkspaceChoice[]; choose: (id: string) => Promise } + | { step: 'failed'; message: string; kind: string | null }; + +export function MagicLinkLanding({ token, heading, onSignIn, onError, messages, ...rest }: MagicLinkLandingProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + const [view, setView] = useState({ step: 'working' }); + + async function finish() { + if (onSignIn) { + onSignIn(); + return; + } + // Signing in runs the route guard again, which can replace this navigation: go again, then offer a link. + const to = config?.afterSignIn ?? '/'; + const here = location.pathname; + if (!(await leave(async () => router.navigate(to), () => location.pathname !== here))) setView({ step: 'signed-in', to }); + } + + function fail(error: unknown) { + const kind = isBridgeError(error) ? error.kind : null; + setView({ step: 'failed', message: kind === 'wrong-device' ? t('magicLink.wrongDevice') : errorMessage(error, t, 'link.error.invalid'), kind }); + onError?.(error); + } + + async function follow(step: SignInStep) { + if (handOff(step)) setView({ step: 'working' }); + else if (step.done) await finish(); + else setView({ step: 'workspace', workspaces: step.workspaces, choose: step.choose }); + } + + useMountOnce(() => { + const found = token ?? takeEmailLink('magic-link'); + if (found === null) { + setView({ step: 'failed', message: t('verify.missingLink'), kind: null }); + return; + } + bounded(getBridge().magicLink.finish(found)).then(follow).catch(fail); + }); + + async function choose(id: string) { + if (view.step !== 'workspace') return; + try { + await follow(await view.choose(id)); + } catch (error) { + fail(error); + } + } + + const pageHeading = heading === undefined ? t('login.heading') : heading; + switch (view.step) { + case 'working': + return ( + +
+ + {t('magicLink.finishing')} +
+
+ ); + case 'signed-in': + return ( + +
+ + {t('invite.continue')} + +
+
+ ); + case 'workspace': + return ( + + + + ); + case 'failed': + return ( + + {view.message} +
+ + {t('action.backToSignIn')} + +
+
+ ); + } +} + +export default MagicLinkLanding; diff --git a/bridge-react/src/components/auth/PasskeyManager.tsx b/bridge-react/src/components/auth/PasskeyManager.tsx new file mode 100644 index 0000000..0fb7b44 --- /dev/null +++ b/bridge-react/src/components/auth/PasskeyManager.tsx @@ -0,0 +1,128 @@ +/** + * The signed-in person's passkeys: each one's name, when it was added and + * last used, and whether it syncs to their other devices; adding one from + * this device and removing one. Adding or removing needs a recent sign-in; + * otherwise the person is asked to sign in again. The last way to sign in + * cannot be removed. + */ +import { isBridgeError, type PasskeyInfo } from '@nebulr-group/bridge-auth-core'; +import { useState, type FormEvent, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface PasskeyManagerProps extends Omit, 'onChange' | 'onError'> { + /** Heading above the list. @default "Passkeys"; `null` for none */ + readonly heading?: ReactNode; + /** Called after a passkey was added or removed. */ + readonly onChange?: (passkeys: readonly PasskeyInfo[]) => void; + readonly onError?: (error: unknown) => void; + readonly messages?: BridgeMessages; +} + +const date = (value: string | null) => (value === null ? '' : new Date(value).toLocaleDateString()); + +export function PasskeyManager({ heading, onChange, onError, messages, className, ...rest }: PasskeyManagerProps) { + const t = useTranslator(messages); + const [passkeys, setPasskeys] = useState(null); + const [supported, setSupported] = useState(false); + const [name, setName] = useState(''); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState(null); + + function fail(error: unknown) { + if (isBridgeError(error, 'cancelled')) setFailure(t('passkey.cancelled')); + else if (isBridgeError(error, 'reauthenticate')) setFailure(t('passkey.reauthenticate')); + else if (isBridgeError(error, 'conflict') && error.code === 'last_sign_in_method') setFailure(t('passkey.lastMethod')); + else if (isBridgeError(error, 'conflict') && error.code === 'passkey_exists') setFailure(t('passkey.exists')); + else setFailure(errorMessage(error, t)); + onError?.(error); + } + + async function load(): Promise { + const list = await getBridge().passkeys.list(); + setPasskeys(list); + return list; + } + + useMountOnce(async () => { + setSupported(await getBridge().passkeys.supported()); + await load().catch(fail); + }); + + async function add(event: FormEvent) { + event.preventDefault(); + if (busy) return; + setBusy(true); + setFailure(null); + try { + await getBridge().passkeys.add(name.trim() || undefined); + setName(''); + onChange?.(await load()); + } catch (error) { + fail(error); + } finally { + setBusy(false); + } + } + + async function remove(id: string) { + if (busy) return; + setBusy(true); + setFailure(null); + try { + await getBridge().passkeys.remove(id); + onChange?.(await load()); + } catch (error) { + fail(error); + } finally { + setBusy(false); + } + } + + return ( +
+ {heading !== null && (typeof heading === 'string' || heading === undefined ?

{heading ?? t('passkey.manageHeading')}

: heading)} + {failure && {failure}} + {passkeys === null ? ( + + ) : passkeys.length === 0 ? ( +

{t('passkey.empty')}

+ ) : ( +
    + {passkeys.map((passkey) => ( +
  • +
    + {passkey.name} +
    + {t('passkey.added', { date: date(passkey.createdAt) })} + {passkey.lastUsedAt && ` · ${t('passkey.lastUsed', { date: date(passkey.lastUsedAt) })}`} + {passkey.deviceType === 'multiDevice' && ` · ${t('passkey.synced')}`} +
    +
    + +
  • + ))} +
+ )} + {supported ? ( +
void add(event)} className="bridge-passkey-add"> + setName(e.target.value)} disabled={busy} /> + +
+ ) : ( +

{t('passkey.unsupported')}

+ )} +
+ ); +} + +export default PasskeyManager; diff --git a/bridge-react/src/components/auth/PasskeySetupLanding.tsx b/bridge-react/src/components/auth/PasskeySetupLanding.tsx new file mode 100644 index 0000000..53054de --- /dev/null +++ b/bridge-react/src/components/auth/PasskeySetupLanding.tsx @@ -0,0 +1,134 @@ +/** + * Sets up a passkey from an emailed link, on the device that asked for it, + * then signs the person in. The browser's dialog opens only on a click, as + * Safari asks. Opened on another device it says so, and the link still works + * on the right one. The link works once. + */ +import { isBridgeError, type SignInStep, type WorkspaceChoice } from '@nebulr-group/bridge-auth-core'; +import { useRef, useState, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { takeEmailLink } from '../../core/email-link.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { Spinner } from '../shared/Spinner.js'; +import { WorkspaceChooser } from './WorkspaceChooser.js'; + +export interface PasskeySetupLandingProps extends Omit, 'onError'> { + /** The link's token. @default read from the page's address */ + readonly token?: string; + /** Replaces the page's heading. */ + readonly heading?: ReactNode; + /** Called once signed in. Without it, the page goes to `auth.afterSignIn`. */ + readonly onSignIn?: () => void; + readonly onError?: (error: unknown) => void; + readonly messages?: BridgeMessages; +} + +type View = + | { step: 'ready' } + | { step: 'working' } + | { step: 'unsupported' } + | { step: 'workspace'; workspaces: readonly WorkspaceChoice[]; choose: (id: string) => Promise } + | { step: 'failed'; message: string; kind: string | null; again: boolean }; + +export function PasskeySetupLanding({ token, heading, onSignIn, onError, messages, ...rest }: PasskeySetupLandingProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + const [view, setView] = useState({ step: 'ready' }); + const found = useRef(null); + + async function follow(step: SignInStep) { + if (!step.done) { + setView({ step: 'workspace', workspaces: step.workspaces, choose: step.choose }); + return; + } + if (onSignIn) onSignIn(); + else router.navigate(config?.afterSignIn ?? '/'); + } + + function fail(error: unknown) { + const kind = isBridgeError(error) ? error.kind : null; + const message = kind === 'wrong-device' ? t('magicLink.wrongDevice') : kind === 'cancelled' ? t('passkey.cancelled') : errorMessage(error, t, 'link.error.invalid'); + // A closed dialog leaves the link unused: the person may try again. + setView({ step: 'failed', message, kind, again: kind === 'cancelled' }); + onError?.(error); + } + + useMountOnce(async () => { + found.current = token ?? takeEmailLink('passkey-setup'); + if (found.current === null) setView({ step: 'failed', message: t('verify.missingLink'), kind: null, again: false }); + else if (!(await getBridge().passkeys.supported())) setView({ step: 'unsupported' }); + }); + + async function create() { + if (found.current === null) return; + setView({ step: 'working' }); + try { + await follow(await getBridge().passkeys.setupLink.finish(found.current)); + } catch (error) { + fail(error); + } + } + + async function choose(id: string) { + if (view.step !== 'workspace') return; + try { + await follow(await view.choose(id)); + } catch (error) { + fail(error); + } + } + + if (view.step === 'working') { + return ( + +
+ + {t('magicLink.finishing')} +
+
+ ); + } + if (view.step === 'workspace') { + return ( + + + + ); + } + return ( + + {view.step === 'unsupported' ? ( + {t('passkey.unsupported')} + ) : view.step === 'failed' ? ( + {view.message} + ) : ( +

{t('passkey.setupPrompt')}

+ )} + {(view.step === 'ready' || (view.step === 'failed' && view.again)) && ( + + )} +
+ + {t('action.backToSignIn')} + +
+
+ ); +} + +export default PasskeySetupLanding; diff --git a/bridge-react/src/components/auth/ProfileName.tsx b/bridge-react/src/components/auth/ProfileName.tsx new file mode 100644 index 0000000..878d634 --- /dev/null +++ b/bridge-react/src/components/auth/ProfileName.tsx @@ -0,0 +1,18 @@ +/** The signed-in person's name, or their email while it has none. */ +import type { HTMLAttributes } from 'react'; +import { useMe, useUser } from '../../react/hooks.js'; + +export function ProfileName(props: HTMLAttributes) { + const profile = useMe().value; + const user = useUser(); + const full = [profile?.firstName, profile?.lastName].filter((part) => part && part.trim() !== '').join(' '); + const name = full !== '' ? full : (profile?.email ?? user?.email ?? ''); + if (!name) return null; + return ( + + {name} + + ); +} + +export default ProfileName; diff --git a/bridge-react/src/components/auth/ProtectedRoute.tsx b/bridge-react/src/components/auth/ProtectedRoute.tsx deleted file mode 100644 index 27e6837..0000000 --- a/bridge-react/src/components/auth/ProtectedRoute.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import { ReactNode, useEffect } from 'react'; -import { useAuth } from '../../hooks/use-auth'; -import { useBridgeStore } from '../../core/bridge-instance'; -import { getRouterAdapter } from '../../utils/router-adapter'; -import { currentAttemptedPath, resolveReturnTo, returnToParam } from '../../utils/return-to'; -import { stashReturnTo, withReturnTo } from '@nebulr-group/bridge-auth-core'; - -interface ProtectedRouteProps { - children: ReactNode; -} - -/** - * A component that protects routes from unauthenticated access. - * - * When the user is not authenticated the guard redirects them to log in. The - * destination depends on how Bridge is configured — mirroring bridge-svelte's - * `BridgeBootstrap` login branch: - * - * - **Hosted mode (default, no `loginRoute`):** launches the hosted auth portal - * via `login()` (`bridge.createLoginUrl()` → `window.location`). - * - **SDK mode (`loginRoute` configured on `BridgeConfig`):** navigates to that - * in-app route using the SDK's router adapter, so the app can render its own - * in-app auth surface (`` etc.) instead of leaving the app. - * - * @example Basic usage - * ```tsx - * - * - * - * ``` - * - * @example With React Router - * ```tsx - * // In your App.tsx - * import { setRouterAdapter } from '@nebulr-group/bridge-react'; - * - * function App() { - * const navigate = useNavigate(); - * - * useEffect(() => { - * setRouterAdapter({ - * navigate: (path, opts) => navigate(path, { replace: opts?.replace }), - * replace: (path) => navigate(path, { replace: true }), - * getCurrentPath: () => window.location.pathname - * }); - * }, [navigate]); - * - * return ...; - * } - * ``` - */ -export function ProtectedRoute({ children }: ProtectedRouteProps) { - const { isAuthenticated, isLoading, login } = useAuth(); - // Resolved in-app login route (config.loginRoute), captured at init. When set - // we redirect in-app; when null we fall back to the hosted portal. - const loginRoute = useBridgeStore((s) => s.loginRoute); - - // Auto-initiate login if not authenticated. - useEffect(() => { - if (isLoading || isAuthenticated) return; - - // TBP-629 — carry the page they actually asked for through the login, so a - // deep link does not collapse to the app's default route. `null` when there - // is nothing safe or worth carrying, and every call below tolerates null by - // behaving exactly as it did before this existed. - const returnTo = resolveReturnTo(currentAttemptedPath()); - - if (loginRoute) { - // SDK mode: consumer set loginRoute → navigate to the in-app login view - // using the same router adapter the rest of the SDK uses. The target rides - // as a query parameter because the login page is ours to read, and because - // a parameter survives a cross-tab click — which is the emailed-link case - // that prompted this. - getRouterAdapter().navigate(withReturnTo(loginRoute, returnTo, returnToParam())); - } else { - // Hosted mode (default): no loginRoute → launch the hosted auth portal. - // - // Here the target CANNOT ride on the URL. `createLoginUrl()` feeds - // `redirectUri` to the OAuth authorize call and bridge-api validates it - // with an exact `allowedRedirectUris.includes()` match, so appending a - // query would break login rather than improve it. Stash it instead; - // picks it up when the round-trip lands back on our - // origin, in the same tab that wrote it. - stashReturnTo(returnTo); - login(); - } - }, [isAuthenticated, isLoading, login, loginRoute]); - - // Show loading state while checking authentication - if (isLoading) { - return ( -
-

Loading...

-
- ); - } - - // If not authenticated, render nothing (login flow will start immediately) - if (!isAuthenticated) { - return null; - } - - // Render the protected content - return <>{children}; -} diff --git a/bridge-react/src/components/auth/SetPassword.tsx b/bridge-react/src/components/auth/SetPassword.tsx new file mode 100644 index 0000000..d6fb2fb --- /dev/null +++ b/bridge-react/src/components/auth/SetPassword.tsx @@ -0,0 +1,141 @@ +/** + * Sets a new password from a reset link. It signs nobody in and ends every + * session of the account, so the page goes on to sign-in. + */ +import { useState, type FormEvent, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { takeEmailLink } from '../../core/email-link.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { PasswordInput } from '../shared/PasswordInput.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface SetPasswordProps extends HTMLAttributes { + /** The reset link's token. @default read from the page's address */ + readonly token?: string; + /** Heading: text or your own node. `null` for none. */ + readonly heading?: ReactNode; + readonly loginHref?: string; + readonly onDone?: () => void; + readonly messages?: BridgeMessages; +} + +export function SetPassword({ token, heading, loginHref, onDone, messages, ...rest }: SetPasswordProps) { + const t = useTranslator(messages); + const authBase = peekConfig()?.authBase ?? '/auth'; + const [linkToken, setLinkToken] = useState(null); + const [checked, setChecked] = useState(false); + const [password, setPassword] = useState(''); + const [confirm, setConfirm] = useState(''); + const [minLength, setMinLength] = useState(8); + const [loading, setLoading] = useState(false); + const [done, setDone] = useState(false); + const [failure, setFailure] = useState(null); + + useMountOnce(() => { + setLinkToken(token ?? takeEmailLink('reset-password')); + setChecked(true); + getBridge() + .signIn.options() + .then((found) => { + if (found.password?.minLength !== undefined) setMinLength(found.password.minLength); + }) + .catch(() => undefined); + }); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (loading || linkToken === null) return; + setFailure(null); + if (password !== confirm) { + setFailure(t('forgot.error.mismatch')); + return; + } + if (password.length < minLength) { + setFailure(t('password.tooShort', { count: minLength })); + return; + } + setLoading(true); + try { + await getBridge().password.set(linkToken, password); + setDone(true); + onDone?.(); + } catch (error) { + setFailure(errorMessage(error, t, 'forgot.error.update')); + } finally { + setLoading(false); + } + } + + if (done) { + return ( + + + {t('login.submit')} + + + ); + } + if (checked && linkToken === null) { + return ( + + {t('verify.missingLink')} +
+ + {t('login.forgotPassword')} + +
+
+ ); + } + return ( + + {failure && {failure}} +
void submit(event)}> +
+ + +
+
+ + +
+ +
+
+ + {t('action.backToSignIn')} + +
+
+ ); +} + +export default SetPassword; diff --git a/bridge-react/src/components/auth/SignInForm.tsx b/bridge-react/src/components/auth/SignInForm.tsx new file mode 100644 index 0000000..48783df --- /dev/null +++ b/bridge-react/src/components/auth/SignInForm.tsx @@ -0,0 +1,366 @@ +/** + * Sign in with email and password, or with a sign-in link sent by email (a + * magic link), then pick a workspace when the person has several. On success + * it calls `onSignIn`, or goes to the page the person was sent here from + * (else `auth.afterSignIn`). + * + * The form shows the methods the app's sign-in options list: the password + * fields when it offers passwords, "Email me a sign-in link" when it offers + * links, and "Sign in with a passkey" when it offers passkeys and the browser + * can use them. With passkeys, the email field also offers the person's + * passkeys in its autofill list, where the browser supports it; the button + * stays for a phone or a security key. + * + * Too many failed attempts: the form says how many minutes to wait, from + * Bridge's answer. + */ +import { isBridgeError, readReturnTo, type SignInOptions, type SignInStep, type WorkspaceChoice } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useRef, useState, type FormEvent, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig, takeEndedReason } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { handOff } from '../../core/finish-link.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { PasswordInput } from '../shared/PasswordInput.js'; +import { Spinner } from '../shared/Spinner.js'; +import { WorkspaceChooser } from './WorkspaceChooser.js'; + +export interface SignInFormProps extends Omit, 'onError'> { + /** Heading on the credentials step: text or your own node. @default the shared "Log in to your account" copy; `null` for none */ + readonly heading?: ReactNode; + /** Show the sign-up link. @default whether the app's sign-in options allow sign-up */ + readonly showSignupLink?: boolean; + readonly signupHref?: string; + readonly showForgotPassword?: boolean; + readonly forgotPasswordHref?: string; + /** Sign straight in to this workspace. */ + readonly workspace?: string; + /** Called once signed in. Without it, the form goes to the return address. */ + readonly onSignIn?: () => void; + readonly onError?: (error: unknown) => void; + /** Replaces the sign-up line under the form. */ + readonly footer?: ReactNode; + readonly messages?: BridgeMessages; +} + +type Choice = { workspaces: readonly WorkspaceChoice[]; choose: (id: string) => Promise }; + +export function SignInForm({ + heading, + showSignupLink, + signupHref, + showForgotPassword = true, + forgotPasswordHref, + workspace, + onSignIn, + onError, + footer, + messages, + ...rest +}: SignInFormProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [loading, setLoading] = useState(false); + const [failure, setFailure] = useState(null); + const [notice, setNotice] = useState(null); + const [linkSent, setLinkSent] = useState(false); + const [options, setOptions] = useState(null); + const [choice, setChoice] = useState(null); + const [settled, setSettled] = useState(false); + const [passkeySupported, setPasskeySupported] = useState(false); + const [setupLinkSent, setSetupLinkSent] = useState(false); + const autofillStarted = useRef(false); + + const signUpShown = showSignupLink ?? options?.signUp ?? true; + const passwordOffered = options === null || options.methods.includes('password'); + const linkOffered = options !== null && options.methods.includes('magicLink'); + const passkeysOffered = passkeySupported && options !== null && options.methods.includes('passkeys'); + const emailAutocomplete = passkeysOffered ? 'username webauthn' : 'username'; + + function finish() { + setSettled(true); + if (onSignIn) { + onSignIn(); + return; + } + const back = readReturnTo(router.location.search, config?.returnToParam); + router.navigate(back ?? config?.afterSignIn ?? '/'); + } + + function fail(error: unknown) { + setFailure(errorMessage(error, t, 'login.error.invalidCredentials')); + onError?.(error); + } + + async function follow(step: SignInStep) { + if (handOff(step)) setSettled(true); + else if (step.done) finish(); + else setChoice({ workspaces: step.workspaces, choose: step.choose }); + } + + /** Waits for the person to pick a passkey from the email field's autofill list. A closed list is not an error. */ + async function startAutofill() { + const bridge = getBridge(); + if (autofillStarted.current || !(await bridge.passkeys.autofillSupported())) return; + autofillStarted.current = true; + try { + await follow(await bridge.passkeys.signIn({ autofill: true, ...(workspace ? { workspace } : {}) })); + } catch (error) { + if (!isBridgeError(error, 'cancelled')) fail(error); + } + } + + useMountOnce(() => { + // Why the last session ended: told by the client as it happened, or read from the session on a fresh page. + const bridge = getBridge(); + const now = bridge.session.get(); + const ended = takeEndedReason() ?? (now.status === 'signed-out' ? now.reason : null); + if (ended === 'session-ended') setNotice(t('session.ended')); + if (ended === 'access-removed') setNotice(t('session.accessRemoved')); + bridge.signIn + .options() + .then(async (found) => { + setOptions(found); + if (!found.methods.includes('passkeys')) return; + const supported = await bridge.passkeys.supported(); + setPasskeySupported(supported); + if (supported) void startAutofill(); + }) + .catch(() => undefined); + }); + + // An autofill wait must not outlive the form. + useEffect( + () => () => { + if (autofillStarted.current) void getBridge().passkeys.cancel(); + }, + [], + ); + + /** Signs in with a passkey from the browser's dialog: a phone, a security key, or this device. */ + async function signInWithPasskey() { + if (loading) return; + setFailure(null); + setNotice(null); + setLoading(true); + try { + await follow(await getBridge().passkeys.signIn({ ...(email.trim() ? { email: email.trim() } : {}), ...(workspace ? { workspace } : {}) })); + } catch (error) { + if (isBridgeError(error, 'cancelled')) setNotice(t('passkey.cancelled')); + else fail(error); + } finally { + setLoading(false); + } + } + + /** Emails a link to set up a passkey on this device. The answer is the same whether or not the address has an account. */ + async function sendSetupLink() { + if (loading || !email.trim()) return; + setFailure(null); + setLoading(true); + try { + await getBridge().passkeys.setupLink.request(email.trim()); + setSetupLinkSent(true); + } catch (error) { + fail(error); + } finally { + setLoading(false); + } + } + + async function submit(event: FormEvent) { + event.preventDefault(); + if (loading) return; + setFailure(null); + setNotice(null); + setLoading(true); + try { + await follow(await getBridge().signIn.start({ email: email.trim(), password, ...(workspace ? { workspace } : {}) })); + } catch (error) { + fail(error); + } finally { + setLoading(false); + } + } + + /** Asks for a sign-in link to the address typed. The answer is the same whether or not it has an account. */ + async function sendLink(event?: { preventDefault(): void }) { + event?.preventDefault(); + if (loading || !email.trim()) return; + setFailure(null); + setNotice(null); + setLoading(true); + try { + await getBridge().magicLink.start(email.trim()); + setLinkSent(true); + } catch (error) { + fail(error); + } finally { + setLoading(false); + } + } + + async function choose(id: string) { + if (choice === null) return; + try { + await follow(await choice.choose(id)); + } catch (error) { + setChoice(null); + fail(error); + } + } + + if (settled) { + return ( + +
+ + {t('login.submitting')} +
+
+ ); + } + + if (choice) { + return ( + + + + ); + } + + const emailField = (required: boolean) => ( +
+ + setEmail(event.target.value)} + disabled={loading} + /> +
+ ); + + return ( + + {notice && {notice}} + {failure && {failure}} + {setupLinkSent ? ( + {t('passkey.setupLinkSent')} + ) : linkSent ? ( + {t('magicLink.sent')} + ) : passwordOffered ? ( +
void submit(event)}> + {emailField(true)} +
+ + +
+ + {showForgotPassword && ( +
+ + {t('login.forgotPassword')} + +
+ )} + {linkOffered && ( + <> +
+ {t('magicLink.or')} +
+ + + )} +
+ ) : linkOffered ? ( +
void sendLink(event)} data-bridge-magic-link-form=""> + {emailField(true)} + +
+ ) : passkeysOffered ? ( +
{ + event.preventDefault(); + void signInWithPasskey(); + }} + data-bridge-passkey-form="" + > + {emailField(false)} +
+ ) : null} + + {passkeysOffered && !linkSent && !setupLinkSent && ( + <> + {(passwordOffered || linkOffered) && ( +
+ {t('magicLink.or')} +
+ )} + +
+ +
+ + )} + + {footer !== undefined + ? footer + : signUpShown && ( +
+ {t('login.signupPrompt')}{' '} + + {t('login.signupLink')} + +
+ )} +
+ ); +} + +export default SignInForm; diff --git a/bridge-react/src/components/auth/SignOutButton.tsx b/bridge-react/src/components/auth/SignOutButton.tsx new file mode 100644 index 0000000..f130d90 --- /dev/null +++ b/bridge-react/src/components/auth/SignOutButton.tsx @@ -0,0 +1,41 @@ +/** + * Signs out here, in every tab, and at Bridge, then goes to `redirectTo` + * (default `auth.afterSignOut`). Pass children for your own label. + */ +import { useState, type ButtonHTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; + +export interface SignOutButtonProps extends Omit, 'onClick' | 'children'> { + readonly redirectTo?: string; + readonly onSignOut?: () => void; + readonly children?: ReactNode; + readonly messages?: BridgeMessages; +} + +export function SignOutButton({ redirectTo, onSignOut, children, messages, ...rest }: SignOutButtonProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const [busy, setBusy] = useState(false); + + async function signOut() { + if (busy) return; + setBusy(true); + try { + await getBridge().signOut(); + } finally { + setBusy(false); + } + if (onSignOut) onSignOut(); + else router.navigate(redirectTo ?? peekConfig()?.afterSignOut ?? '/'); + } + + return ( + + ); +} + +export default SignOutButton; diff --git a/bridge-react/src/components/auth/SignUpForm.tsx b/bridge-react/src/components/auth/SignUpForm.tsx new file mode 100644 index 0000000..522f7ef --- /dev/null +++ b/bridge-react/src/components/auth/SignUpForm.tsx @@ -0,0 +1,238 @@ +/** + * Sign up with email and password. Nothing is made until the person proves + * the address: Bridge emails a link to the app's verify-email page, which + * finishes the sign-up on this device. The answer is the same whether or not + * the address already has an account, so the form never says which. + * + * With `invite`, it signs the person up from an invite instead: the invite's + * link proved the address, so there is no email field and no email to wait + * for, and the person lands signed in, in the inviting workspace. + */ +import type { SignInOptions } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useRef, useState, type FormEvent, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { errorMessage } from '../../core/i18n.js'; +import { takeSignUpLinks } from '../../core/link-relay.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { PasswordInput } from '../shared/PasswordInput.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface SignUpFormProps extends Omit, 'onError'> { + /** Heading: text or your own node. @default the shared sign-up copy; `null` for none */ + readonly heading?: ReactNode; + /** Ask for first and last name. @default true */ + readonly showNameFields?: boolean; + /** + * The new person's own workspace: `true` makes one with no name yet, + * `'ask'` asks for its name, `false` makes none. @default true + */ + readonly workspace?: boolean | 'ask'; + /** + * An invite's token: sign the person up from the invite. The address is + * the invite's, so no email field is shown and no email is sent. + */ + readonly invite?: string; + /** With `invite`: called once signed in. Without it, the page goes to `auth.afterSignIn`. */ + readonly onSignIn?: () => void; + readonly showLoginLink?: boolean; + readonly loginHref?: string; + /** Called once the email is sent. */ + readonly onSent?: (email: string) => void; + readonly onError?: (error: unknown) => void; + readonly footer?: ReactNode; + readonly messages?: BridgeMessages; +} + +export function SignUpForm({ + heading, + showNameFields = true, + workspace = true, + invite, + onSignIn, + showLoginLink = true, + loginHref, + onSent, + onError, + footer, + messages, + ...rest +}: SignUpFormProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [firstName, setFirstName] = useState(''); + const [lastName, setLastName] = useState(''); + const [workspaceName, setWorkspaceName] = useState(''); + const [loading, setLoading] = useState(false); + const [failure, setFailure] = useState(null); + const [sentTo, setSentTo] = useState(null); + const [options, setOptions] = useState(null); + const stopRelay = useRef<(() => void) | null>(null); + + const minLength = options?.password?.minLength ?? 8; + /** An app that offers sign-in links only takes no password: the person signs in by link. */ + const passwordOffered = options === null || options.methods.includes('password'); + // An invite is its own way in, whether or not the app takes sign-ups. + const closed = !invite && options !== null && !options.signUp; + + useEffect( + () => () => { + stopRelay.current?.(); + stopRelay.current = null; + }, + [], + ); + + useMountOnce(() => { + getBridge() + .signIn.options() + .then(setOptions) + .catch(() => undefined); + }); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (loading) return; + setFailure(null); + if (passwordOffered && password.length < minLength) { + setFailure(t('password.tooShort', { count: minLength })); + return; + } + setLoading(true); + const secret = passwordOffered ? { password } : {}; + const address = email.trim(); + const names = { + ...(firstName.trim() ? { firstName: firstName.trim() } : {}), + ...(lastName.trim() ? { lastName: lastName.trim() } : {}), + }; + try { + if (invite) { + // Signed in at once, in the inviting workspace: the invite's link proved the address. + await getBridge().invites.signUp({ token: invite, ...secret, ...names }); + if (onSignIn) onSignIn(); + else router.navigate(config?.afterSignIn ?? '/'); + return; + } + await getBridge().signUp.start({ + email: address, + ...secret, + ...names, + ...(workspace === 'ask' ? { workspace: workspaceName.trim() || true } : workspace ? { workspace: true } : {}), + }); + setSentTo(address); + onSent?.(address); + // Memory only: this tab holds the sign-up's verifier, and the email link opens in a new tab, which hands it here. + if (config?.storage === 'memory' && stopRelay.current === null) { + stopRelay.current = takeSignUpLinks(config.issuer, () => router.navigate(`${authBase}/verify-email`)); + } + } catch (error) { + setFailure(errorMessage(error, t, 'signup.error.create')); + onError?.(error); + } finally { + setLoading(false); + } + } + + const shownHeading = heading === undefined ? t('signup.heading') : heading; + + if (sentTo !== null) { + return ( + + {t('signup.successDescription', { email: sentTo })} +

+ } + data-bridge-sign-up-step="sent" + {...rest} + /> + ); + } + + if (closed) { + return ( + + {t('signup.closed')} +
+ + {t('action.backToSignIn')} + +
+
+ ); + } + + return ( + + {failure && {failure}} +
void submit(event)}> + {showNameFields && ( +
+
+ + setFirstName(e.target.value)} disabled={loading} /> +
+
+ + setLastName(e.target.value)} disabled={loading} /> +
+
+ )} + {!invite && ( +
+ + setEmail(e.target.value)} disabled={loading} /> +
+ )} + {passwordOffered && ( +
+ + +
+ )} + {workspace === 'ask' && !invite && ( +
+ + setWorkspaceName(e.target.value)} disabled={loading} /> +
+ )} + +
+ {footer !== undefined + ? footer + : showLoginLink && ( +
+ {t('signup.loginPrompt')}{' '} + + {t('signup.loginLink')} + +
+ )} +
+ ); +} + +export default SignUpForm; diff --git a/bridge-react/src/components/auth/TokenStatus.tsx b/bridge-react/src/components/auth/TokenStatus.tsx deleted file mode 100644 index 9653079..0000000 --- a/bridge-react/src/components/auth/TokenStatus.tsx +++ /dev/null @@ -1,132 +0,0 @@ -import { jwtDecode } from 'jwt-decode'; -import { FC, useEffect, useState } from 'react'; -import { getBridgeAuth } from '../../core/bridge-instance'; -import { useBridgeToken } from '../../hooks/use-bridge-token'; -import { logger } from '../../utils/logger'; - -export interface TokenStatusProps { - /** - * Additional CSS class names - */ - className?: string; -} - -/** Returns the access-token expiry time in ms epoch, or null if undecodable. */ -function getTokenExpiryTime(accessToken: string): number | null { - try { - const decoded = jwtDecode<{ exp?: number }>(accessToken); - return decoded.exp ? decoded.exp * 1000 : null; - } catch { - return null; - } -} - -/** - * Component to display token status. Rides the auth-core singleton for token - * access + refresh (no legacy TokenService). - * - * @example - * import { TokenStatus } from '@nebulr-group/bridge-react'; - * - * function MyComponent() { - * return ; - * } - */ -export const TokenStatus: FC = ({ className }) => { - const { getAccessToken } = useBridgeToken(); - const [hasToken, setHasToken] = useState(false); - const [tokenExpiresIn, setTokenExpiresIn] = useState(null); - const [lastRenewal, setLastRenewal] = useState(null); - const [isRenewing, setIsRenewing] = useState(false); - - useEffect(() => { - const updateExpiry = () => { - const accessToken = getAccessToken(); - if (accessToken) { - setHasToken(true); - const expiryTime = getTokenExpiryTime(accessToken); - if (expiryTime) { - const timeUntilExpiry = expiryTime - Date.now(); - setTokenExpiresIn(Math.floor(timeUntilExpiry / 1000)); - } - } else { - setHasToken(false); - setTokenExpiresIn(null); - } - }; - - updateExpiry(); - const interval = setInterval(updateExpiry, 1000); - return () => clearInterval(interval); - }, [getAccessToken]); - - // Function to refresh token via the auth-core singleton. - const refreshToken = async () => { - if (isRenewing) return; - - setIsRenewing(true); - try { - const tokens = await getBridgeAuth().refreshTokens(); - if (tokens) { - setLastRenewal(Date.now()); - } - } catch (error) { - logger.error('[TokenStatus] Error refreshing token:', error); - } finally { - setIsRenewing(false); - } - }; - - // Format the time until expiry - const formatExpiryTime = (seconds: number | null): string => { - if (seconds === null) return 'No token'; - - if (seconds < 0) return 'Expired'; - - const minutes = Math.floor(seconds / 60); - const remainingSeconds = seconds % 60; - - if (minutes > 0) { - return `${minutes}m ${remainingSeconds}s`; - } - - return `${remainingSeconds}s`; - }; - - // Format the last renewal time - const formatLastRenewal = (): string => { - if (!lastRenewal) return 'No renewals yet'; - - const date = new Date(lastRenewal); - return date.toLocaleTimeString(); - }; - - return ( -
-

Token Status

-
-

- Token expires in: {formatExpiryTime(tokenExpiresIn)} -

-

- Last renewal: {formatLastRenewal()} -

-

- Status:{' '} - - {isRenewing ? 'Renewing...' : 'Idle'} - -

- {hasToken && ( - - )} -
-
- ); -}; diff --git a/bridge-react/src/components/auth/VerifyEmail.tsx b/bridge-react/src/components/auth/VerifyEmail.tsx new file mode 100644 index 0000000..7712ecc --- /dev/null +++ b/bridge-react/src/components/auth/VerifyEmail.tsx @@ -0,0 +1,157 @@ +/** + * Finishes a sign-up from its email link, on the device that started it, and + * signs the person in. Opened on another device it says so, and the link + * still works on the right one. + * + * With `storage: 'memory'` the session lives only in the tab that started the + * sign-up, so this page first hands the link to that tab; when one takes it, + * this page says to go on there. When none does, this page finishes itself. + * + * Every wait has a bound: finishing fails with an error after a while, and + * once signed in the page goes on, or offers a link when it cannot. + */ +import { isBridgeError, type SignInStep, type WorkspaceChoice } from '@nebulr-group/bridge-auth-core'; +import { useState, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge, peekConfig } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { takeEmailLink } from '../../core/email-link.js'; +import { bounded, handOff, leave } from '../../core/finish-link.js'; +import { errorMessage } from '../../core/i18n.js'; +import { offerSignUpLink, takeRelayedLink } from '../../core/link-relay.js'; +import { useBridgeRouter, useTranslator } from '../../react/hooks.js'; +import { useMountOnce } from '../../react/once.js'; +import { Alert } from '../shared/Alert.js'; +import { AuthFormWrapper } from '../shared/AuthFormWrapper.js'; +import { Link } from '../shared/Link.js'; +import { Spinner } from '../shared/Spinner.js'; +import { WorkspaceChooser } from './WorkspaceChooser.js'; + +export interface VerifyEmailProps extends Omit, 'onError'> { + /** The link's token. @default read from the page's address */ + readonly token?: string; + /** Replaces the page's heading. */ + readonly heading?: ReactNode; + /** Called once signed in. Without it, the page goes to `auth.afterSignIn`. */ + readonly onSignIn?: () => void; + readonly onError?: (error: unknown) => void; + readonly messages?: BridgeMessages; +} + +type View = + | { step: 'working' } + | { step: 'continued' } + | { step: 'signed-in'; to: string } + | { step: 'workspace'; workspaces: readonly WorkspaceChoice[]; choose: (id: string) => Promise } + | { step: 'failed'; message: string; kind: string | null }; + +export function VerifyEmail({ token, heading, onSignIn, onError, messages, ...rest }: VerifyEmailProps) { + const t = useTranslator(messages); + const router = useBridgeRouter(); + const config = peekConfig(); + const authBase = config?.authBase ?? '/auth'; + const [view, setView] = useState({ step: 'working' }); + + async function finish() { + if (onSignIn) { + onSignIn(); + return; + } + // Signing in runs the route guard again, which can replace this navigation: go again, then offer a link. + const to = config?.afterSignIn ?? '/'; + const here = location.pathname; + if (!(await leave(async () => router.navigate(to), () => location.pathname !== here))) setView({ step: 'signed-in', to }); + } + + function fail(error: unknown) { + setView({ step: 'failed', message: errorMessage(error, t, 'link.error.invalid'), kind: isBridgeError(error) ? error.kind : null }); + onError?.(error); + } + + async function follow(step: SignInStep) { + if (handOff(step)) setView({ step: 'working' }); + else if (step.done) await finish(); + else setView({ step: 'workspace', workspaces: step.workspaces, choose: step.choose }); + } + + async function start(found: string, relayed: boolean) { + try { + // The session belongs in the tab that started the sign-up (memory only): offer it the link first. + if (!relayed && config?.storage === 'memory' && (await offerSignUpLink(config.issuer, found))) { + setView({ step: 'continued' }); + return; + } + await follow(await bounded(getBridge().signUp.finish(found))); + } catch (error) { + fail(error); + } + } + + useMountOnce(() => { + // A link another tab handed here (memory only), the token given, or the page's own address. + const relayed = token === undefined ? takeRelayedLink() : null; + const found = token ?? relayed ?? takeEmailLink('verify-email'); + if (found === null) { + setView({ step: 'failed', message: t('verify.missingLink'), kind: null }); + return; + } + void start(found, relayed !== null); + }); + + async function choose(id: string) { + if (view.step !== 'workspace') return; + try { + await follow(await view.choose(id)); + } catch (error) { + fail(error); + } + } + + const pageHeading = heading === undefined ? t('signup.heading') : heading; + + switch (view.step) { + case 'working': + return ( + +
+ + {t('verify.finishing')} +
+
+ ); + case 'continued': + return ( + + {t('verify.continuedElsewhere')} + + ); + case 'signed-in': + return ( + +
+ + {t('invite.continue')} + +
+
+ ); + case 'workspace': + return ( + + + + ); + case 'failed': + return ( + + {view.message} +
+ + {t('action.backToSignIn')} + +
+
+ ); + } +} + +export default VerifyEmail; diff --git a/bridge-react/src/components/auth/WorkspaceChooser.tsx b/bridge-react/src/components/auth/WorkspaceChooser.tsx new file mode 100644 index 0000000..8a0085a --- /dev/null +++ b/bridge-react/src/components/auth/WorkspaceChooser.tsx @@ -0,0 +1,126 @@ +/** + * The workspace list, for two moments: + * + * - **At sign-in**, when the person belongs to several: pass the step's + * `workspaces` and `onChoose`. SignInForm, VerifyEmail and the hand-off page + * do this for you. + * - **To switch** while signed in: pass nothing. It lists the person's + * workspaces and moves the session (every tab follows) on a click. + * + * Each row renders as a button; `workspaceItem` replaces a row. + */ +import type { WorkspaceChoice } from '@nebulr-group/bridge-auth-core'; +import { useState, type HTMLAttributes, type ReactNode } from 'react'; +import { getBridge } from '../../core/client.js'; +import type { BridgeMessages } from '../../core/config.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useSession, useTranslator, useWorkspaces } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface WorkspaceRow { + readonly id: string; + readonly name: string | null; + readonly logo: string | null; + /** A step this SDK cannot do yet, so the row cannot be chosen. */ + readonly needs?: string; +} + +export interface WorkspaceChooserProps extends HTMLAttributes { + /** The sign-in step's workspaces. Leave out to switch between the person's own. */ + readonly workspaces?: readonly WorkspaceChoice[]; + /** Called with the chosen id at sign-in. Resolve when the step is done. */ + readonly onChoose?: (workspaceId: string) => Promise; + /** Called after a switch. */ + readonly onSwitch?: (workspaceId: string) => void; + /** Replaces a row. */ + readonly workspaceItem?: (item: { workspace: WorkspaceRow; isActive: boolean; isLoading: boolean; onSelect: () => void }) => ReactNode; + readonly messages?: BridgeMessages; +} + +const initial = (name: string | null) => (name ?? '?').trim().charAt(0).toUpperCase() || '?'; + +export function WorkspaceChooser({ workspaces, onChoose, onSwitch, workspaceItem, messages, ...rest }: WorkspaceChooserProps) { + const t = useTranslator(messages); + const session = useSession(); + const mine = useWorkspaces(); + const choosing = workspaces !== undefined; + const rows: readonly WorkspaceRow[] = choosing ? workspaces : (mine.value ?? []).map((w) => ({ id: w.id, name: w.name, logo: w.logo })); + const loadingList = !choosing && mine.value === null && mine.error === null; + const currentId = session.status === 'signed-in' && !choosing ? (session.workspace?.id ?? null) : null; + + const [busyId, setBusyId] = useState(null); + const [failure, setFailure] = useState(null); + + async function select(row: WorkspaceRow) { + if (busyId !== null || row.needs !== undefined) return; + setFailure(null); + setBusyId(row.id); + try { + if (choosing) { + await onChoose?.(row.id); + } else { + if (row.id !== currentId) await getBridge().workspaces.switch(row.id); + onSwitch?.(row.id); + } + } catch (error) { + setFailure(errorMessage(error, t, choosing ? 'workspace.error.select' : 'workspace.error.switch')); + } finally { + setBusyId(null); + } + } + + return ( +
+ {failure ? ( + {failure} + ) : !choosing && mine.error ? ( + {errorMessage(mine.error, t, 'workspace.error.load')} + ) : null} + + {loadingList ? ( +
+ +
+ ) : rows.length === 0 ? ( +

+ {t('workspace.empty')} +

+ ) : ( +
+ {rows.map((row) => { + const isActive = row.id === currentId; + const isLoading = busyId === row.id; + if (workspaceItem) return {workspaceItem({ workspace: row, isActive, isLoading, onSelect: () => void select(row) })}; + return ( + + ); + })} +
+ )} +
+ ); +} + +function WorkspaceItem({ children }: { children: ReactNode }) { + return <>{children}; +} + +export default WorkspaceChooser; diff --git a/bridge-react/src/components/billing/BillingNotice.tsx b/bridge-react/src/components/billing/BillingNotice.tsx new file mode 100644 index 0000000..d7c7c69 --- /dev/null +++ b/bridge-react/src/components/billing/BillingNotice.tsx @@ -0,0 +1,119 @@ +/** + * The one billing notice worth showing now, most urgent first: access locked, + * a payment due, no plan, a trial ending, the subscription ending, or a plan + * change waiting. Renders nothing when all is well. A person with the + * `billingManage` flag gets a link to the billing pages; anyone else is told + * to ask the workspace owner. Not dismissible: it goes when the facts change. + */ +import { billingNotice, type BillingFacts, type BillingNotice as Notice, type Plan } from '@nebulr-group/bridge-auth-core'; +import type { HTMLAttributes, MouseEvent } from 'react'; +import { useBilling, useBridgeConfig, useCanManageBilling, usePlans } from '../../react/hooks.js'; +import { Link } from '../shared/Link.js'; +import { formatDate } from './plan-format.js'; + +type Chassis = 'bar' | 'rail' | 'card'; +type Severity = 'info' | 'warn' | 'critical' | 'locked'; + +export interface BillingNoticeProps extends HTMLAttributes { + /** The notice's shape: a full-width bar, a rail with a left edge, or a card. @default 'rail' */ + readonly chassis?: Chassis; + /** Where the action link goes. @default the plan page for no plan, else the subscription page */ + readonly actionHref?: string; + /** Replaces the action link's navigation. */ + readonly onActionClick?: (notice: Notice) => void; +} + +const SEVERITY: Record = { + blocked: 'locked', + 'payment-due': 'critical', + 'needs-plan': 'critical', + 'trial-ending': 'warn', + ending: 'warn', + waiting: 'info', +}; + +const OWNER = 'Please contact your workspace owner.'; + +function daysLeft(days: number): string { + if (days <= 0) return 'The trial ends today.'; + return `${days} ${days === 1 ? 'day' : 'days'} left.`; +} + +function copyFor(n: Notice, admin: boolean, facts: BillingFacts | null, plans: readonly Plan[] | null): { title: string; body: string; cta?: string } { + const current = facts?.plan?.name ?? 'your plan'; + const planName = (key: string) => plans?.find((p) => p.key === key)?.name ?? key; + switch (n.kind) { + case 'blocked': + return admin ? { title: 'Access locked', body: 'Update the payment method to restore access.', cta: 'Update card' } : { title: 'Access locked', body: OWNER }; + case 'payment-due': + return admin + ? { title: 'Payment failed', body: `We couldn't charge your card. Update your payment method to keep using ${current}.`, cta: 'Update card' } + : { title: "Your workspace's payment failed", body: 'Please contact your workspace owner to update the payment method.' }; + case 'needs-plan': + return admin ? { title: 'No active plan', body: 'Choose a plan to continue.', cta: 'Choose plan' } : { title: 'No active plan', body: OWNER }; + case 'trial-ending': + return admin + ? { title: 'Trial ending soon', body: `${daysLeft(n.daysLeft)} Add a payment method to keep your access.`, cta: 'Add card' } + : { title: 'Trial ending soon', body: daysLeft(n.daysLeft) }; + case 'ending': { + const ends = formatDate(n.periodEnd); + return admin + ? { + title: 'Subscription ending', + body: ends ? `Your subscription ends ${ends}. You'll keep full access until then.` : "Your subscription is ending. You'll keep access until the period ends.", + cta: 'Manage billing', + } + : { title: 'Subscription ending', body: ends ? `Your workspace's subscription ends ${ends}.` : "Your workspace's subscription is ending." }; + } + case 'waiting': + return n.waitsFor === 'payment' + ? { title: 'Waiting for payment', body: `The move to ${planName(n.plan)} starts once the payment goes through.` } + : { title: 'Plan change scheduled', body: `The workspace moves to ${planName(n.plan)} at the end of this billing period.` }; + } +} + +export function BillingNotice({ chassis = 'rail', actionHref, onActionClick, className, ...rest }: BillingNoticeProps) { + const config = useBridgeConfig(); + const base = config?.billingBase ?? '/subscription'; + const canManage = useCanManageBilling(); + const billing = useBilling(); + const plans = usePlans(); + + const notice = billing.value ? billingNotice(billing.value) : null; + if (!notice) return null; + const severity = SEVERITY[notice.kind]; + const urgent = severity === 'critical' || severity === 'locked'; + const href = actionHref ?? (notice.kind === 'needs-plan' ? `${base}/plan` : base || '/'); + const copy = copyFor(notice, canManage, billing.value, plans.value); + + function handleAction(event: MouseEvent) { + if (!onActionClick || !notice) return; + event.preventDefault(); + onActionClick(notice); + } + + return ( +
+
+ {copy.title} + {copy.body} +
+ {copy.cta && canManage && ( + + {copy.cta} + + )} +
+ ); +} + +export default BillingNotice; diff --git a/bridge-react/src/components/billing/BillingPortalButton.tsx b/bridge-react/src/components/billing/BillingPortalButton.tsx new file mode 100644 index 0000000..c5743cc --- /dev/null +++ b/bridge-react/src/components/billing/BillingPortalButton.tsx @@ -0,0 +1,57 @@ +/** + * "Manage billing": opens the workspace's billing portal (payment method, + * invoices, cancelling). The portal address is fetched on click, since it is + * short-lived. Renders only for a person with the `billingManage` flag. + */ +import { useState, type ButtonHTMLAttributes, type ReactNode } from 'react'; +import { getBridge } from '../../core/client.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useCanManageBilling, useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; + +export interface BillingPortalButtonProps extends Omit, 'onClick' | 'children'> { + /** The button text. @default 'Manage billing' */ + readonly label?: string; + /** Replaces the button text. */ + readonly children?: ReactNode; +} + +export function BillingPortalButton({ label = 'Manage billing', children, className, ...rest }: BillingPortalButtonProps) { + const canManage = useCanManageBilling(); + const t = useTranslator(); + const [opening, setOpening] = useState(false); + const [failure, setFailure] = useState(null); + + async function openPortal() { + if (opening) return; + setOpening(true); + setFailure(null); + try { + const { url } = await getBridge().billing.portal(); + window.location.assign(url); + } catch (error) { + setFailure(errorMessage(error, t, 'error.generic')); + setOpening(false); + } + } + + if (!canManage) return null; + return ( + <> + {failure && {failure}} + + + ); +} + +export default BillingPortalButton; diff --git a/bridge-react/src/components/billing/BridgeBillingRoutes.tsx b/bridge-react/src/components/billing/BridgeBillingRoutes.tsx new file mode 100644 index 0000000..f9d7efb --- /dev/null +++ b/bridge-react/src/components/billing/BridgeBillingRoutes.tsx @@ -0,0 +1,141 @@ +/** + * Every billing page from one route: mount it on `/subscription/*` in your + * router. + * + * ```tsx + * } /> + * ``` + * + * Serves, under `billing.base`: + * (the base) the current plan, "Manage billing" and the plans to change to + * plan the paywall: where the route guard sends a workspace whose app + * is not active. Once a plan is active it goes on to the page the + * person was headed for. + * success a confirmation page + * error where a failed checkout lands + * A return from checkout is confirmed on any of the first three. An unknown + * page renders `notFound`. + * + * Customising, in rungs: + * 1. `--bridge-*` CSS tokens restyle the pages. + * 2. `frame(page, content)` replaces everything around the content on every + * page; `heading(page)` replaces each page's heading. + * 3. To own one page, add a more specific route for it + * (`/subscription/plan`) before this one; the other pages keep working. + * 4. Headless: PlanPicker, SubscriptionStatus, BillingPortalButton, + * CheckoutNotice and the `useBilling` and `usePlans` hooks. + */ +import { readReturnTo, STANDARD_FLAGS } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { normalizePath } from '../../core/guard.js'; +import { parseBillingPage, type BillingPage } from '../../core/routes.js'; +import { useBilling, useBridgeConfig, useBridgeRouter, useFlag } from '../../react/hooks.js'; +import { Link } from '../shared/Link.js'; +import { BillingPortalButton } from './BillingPortalButton.js'; +import { CheckoutNotice } from './CheckoutNotice.js'; +import { PlanPicker } from './PlanPicker.js'; +import { SubscriptionStatus } from './SubscriptionStatus.js'; +import { subscriptionMeta } from './plan-format.js'; + +export interface BridgeBillingRoutesProps { + /** Replaces everything around the content, on every page. */ + readonly frame?: (page: BillingPage, content: ReactNode) => ReactNode; + /** Replaces each page's heading. */ + readonly heading?: (page: BillingPage) => ReactNode; + /** Where "Continue" on the success page goes. @default the return address, else `auth.afterSignIn` */ + readonly redirectTo?: string; + /** Confirm and announce a return from checkout. `false` leaves it to your own CheckoutNotice. @default true */ + readonly checkoutNotice?: boolean; + /** Shown for a path under `billing.base` that is none of the pages. @default nothing */ + readonly notFound?: ReactNode; +} + +const DEFAULT_HEADINGS: Record = { + manage: 'Subscription', + plan: 'Choose a plan', + success: "You're all set", + error: "We couldn't confirm your payment", +}; + +export function BridgeBillingRoutes({ frame, heading, redirectTo, checkoutNotice = true, notFound = null }: BridgeBillingRoutesProps) { + const config = useBridgeConfig(); + const router = useBridgeRouter(); + const billing = useBilling(); + const base = config?.billingBase ?? '/subscription'; + const manageHref = base || '/'; + const appActive = useFlag(config?.flagKeys.appActive ?? STANDARD_FLAGS.appActive).value === true; + + const path = normalizePath(router.location.pathname); + const current = path === base || path.startsWith(`${base}/`) ? parseBillingPage(path.slice(base.length)) : null; + const returnTo = readReturnTo(router.location.search, config?.returnToParam) ?? config?.afterSignIn ?? '/'; + const meta = subscriptionMeta(billing.value); + + // On the plan page: once a plan was chosen here and the app is active, go on. + const [chosen, setChosen] = useState(false); + const leaving = useRef(false); + useEffect(() => { + if (current !== 'plan' || !chosen || !appActive || leaving.current) return; + leaving.current = true; + router.navigate(returnTo); + }, [current, chosen, appActive, returnTo]); + + if (current === null) return <>{notFound}; + const p = current; + + const content = ( + <> + {checkoutNotice && p !== 'error' && setChosen(true) : undefined} />} + {heading ? heading(p) :

{DEFAULT_HEADINGS[p]}

} + + {p === 'manage' ? ( + <> +

Your plan, what it includes, and billing.

+
+
+ Current plan + + {meta && ( + + {meta} + + )} +
+ +
+ + + ) : p === 'plan' ? ( + <> +

Pick a plan to start using the app.

+ setChosen(true)} /> + + ) : p === 'success' ? ( + <> +

Your plan is active.

+
+ Current plan + +
+ + Continue + + + ) : ( + <> +

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. + + )} +
+ {dismissible && outcome.state !== 'confirming' && ( + + )} +
+ ); +} + +export default CheckoutNotice; diff --git a/bridge-react/src/components/billing/PlanPicker.tsx b/bridge-react/src/components/billing/PlanPicker.tsx new file mode 100644 index 0000000..0efffc9 --- /dev/null +++ b/bridge-react/src/components/billing/PlanPicker.tsx @@ -0,0 +1,414 @@ +/** + * The plans on offer, as cards, with an interval switch (Monthly / Yearly) + * when the plans have more than one. Choosing a plan changes it, or sends the + * person to checkout when it needs a payment method; switching from a paid + * plan asks to confirm first. + * + * Only a person with the `billingManage` flag may choose. Anyone else sees + * the plans with the buttons off and a note to ask the workspace owner. + * + * `planCard` replaces a whole card; `planDescription` and `planFooter` + * replace parts of the default one. + */ +import type { Plan, PlanChange, Price } 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 { useBilling, useCanManageBilling, useFlagsStatus, usePlans, useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import { Spinner } from '../shared/Spinner.js'; +import { BillingPortalButton } from './BillingPortalButton.js'; +import { formatAmount, formatPrice, intervalSuffix, isFreePick, minAmount, pickKind, pickLabel, planFeatures, trialDays } from './plan-format.js'; + +export interface PlanCardContext { + readonly plan: Plan; + /** The plan's full price list. */ + readonly prices: readonly Price[]; + readonly isCurrent: boolean; + /** The selected interval. */ + readonly interval: string; + readonly canChoose: boolean; + readonly onPick: (price?: Price) => void; +} + +export interface PlanPickerProps extends Omit, 'children'> { + /** A heading above the plans, beside the interval switch. */ + readonly heading?: string; + /** The interval selected at first, when the plans offer it. @default 'year' */ + readonly defaultInterval?: string; + /** Called after the plan changed here (not when the person is sent to checkout). */ + readonly onChanged?: (detail: { plan: Plan; change: PlanChange }) => void; + /** Replaces a whole card. */ + readonly planCard?: (context: PlanCardContext) => ReactNode; + /** Replaces the default card's description. */ + readonly planDescription?: (context: { plan: Plan; isCurrent: boolean }) => ReactNode; + /** Rendered at the bottom of the default card. */ + readonly planFooter?: (context: { plan: Plan; isCurrent: boolean }) => ReactNode; + readonly emptyState?: ReactNode; + readonly loadingState?: ReactNode; +} + +const INTERVAL_ORDER = ['day', 'week', 'month', 'year']; +const INTERVAL_LABELS: Record = { day: 'Daily', week: 'Weekly', month: 'Monthly', year: 'Yearly' }; + +function intervalLabel(interval: string): string { + return INTERVAL_LABELS[interval] ?? interval.charAt(0).toUpperCase() + interval.slice(1); +} + +function changeNotice(plan: Plan, price: Price | undefined, status: PlanChange['status']): string { + switch (status) { + case 'scheduled': + return `You'll move to ${plan.name} at the end of this billing period.`; + case 'waiting_for_payment': + return `You'll move to ${plan.name} once the payment goes through.`; + default: + return `You're now on ${plan.name} (${formatPrice(price)}).`; + } +} + +export function PlanPicker({ + heading, + defaultInterval = 'year', + onChanged, + planCard, + planDescription, + planFooter, + emptyState, + loadingState, + ...rest +}: PlanPickerProps) { + const t = useTranslator(); + const canManage = useCanManageBilling(); + const billing = useBilling(); + const plans = usePlans(); + const flagsStatus = useFlagsStatus(); + + const [picking, setPicking] = useState(false); + const [pickError, setPickError] = useState(null); + const [successNotice, setSuccessNotice] = useState(null); + const successTimer = useRef | undefined>(undefined); + const [confirmTarget, setConfirmTarget] = useState<{ plan: Plan; price: Price | undefined } | null>(null); + const [confirmBusy, setConfirmBusy] = useState(false); + const [confirmError, setConfirmError] = useState(null); + const [retrying, setRetrying] = useState(false); + const [intervalOverride, setIntervalOverride] = useState(null); + + useEffect(() => () => clearTimeout(successTimer.current), []); + + const facts = billing.value; + const currentKey = facts?.plan?.key ?? null; + const loading = plans.value === null && plans.error === null; + const loadError = plans.value === null && plans.error !== null ? errorMessage(plans.error, t, 'error.generic') : null; + const list = (plans.value ?? []).filter((p) => !p.archived || p.key === currentKey); + const flagsKnown = flagsStatus === 'ready' || flagsStatus === 'error'; + + const uiState = !facts + ? 'idle' + : facts.access === 'payment_due' || facts.status === 'past_due' + ? 'payment-failed' + : facts.plan === null || facts.access === 'needs_plan' + ? 'select-plan' + : facts.status === 'trialing' + ? 'trial' + : 'active'; + + // Intervals any paid price is offered in, in a stable order. + const found = list.flatMap((plan) => plan.prices.filter((p) => p.amount > 0 && p.interval).map((p) => p.interval as string)); + const others = found.filter((i, at) => !INTERVAL_ORDER.includes(i) && found.indexOf(i) === at); + const availableIntervals = [...INTERVAL_ORDER.filter((i) => found.includes(i)), ...others]; + const showIntervalTabs = availableIntervals.length >= 2; + const selectedInterval = + intervalOverride && availableIntervals.includes(intervalOverride) + ? intervalOverride + : availableIntervals.includes(defaultInterval) + ? defaultInterval + : (availableIntervals[0] ?? defaultInterval); + + // Cheapest first, by each plan's cheapest price in any interval, so cards stay put on a tab switch. + const sortedPlans = [...list].sort((a, b) => minAmount(a) - minAmount(b)); + const currentPlan = list.find((p) => p.key === currentKey) ?? null; + const currentPlanName = currentPlan?.name ?? facts?.plan?.name ?? 'your current plan'; + + // The prices a card shows under the selected interval: one button each. A + // free or interval-less price shows under every tab. + function pricesForInterval(plan: Plan): Price[] { + const exact = plan.prices.filter((p) => p.interval === selectedInterval); + if (exact.length > 0) return exact; + const unbound = plan.prices.filter((p) => !p.interval); + if (unbound.length > 0) return unbound; + const free = plan.prices.find((p) => p.amount === 0); + return free ? [free] : []; + } + + function showSuccess(message: string): void { + setSuccessNotice(message); + clearTimeout(successTimer.current); + successTimer.current = setTimeout(() => setSuccessNotice(null), 6000); + } + + /** Chooses the plan. True when the person is on their way to checkout. */ + async function choose(plan: Plan, price: Price | undefined): Promise { + const change = await getBridge().billing.choosePlan({ + plan: plan.key, + ...(price ? { currency: price.currency } : {}), + ...(price?.interval ? { interval: price.interval } : {}), + }); + if (change.status === 'payment_required') { + window.location.assign(change.checkout.url); + return true; + } + await billing.refresh(); + showSuccess(changeNotice(plan, price, change.status)); + onChanged?.({ plan, change }); + return false; + } + + // Switching away from a paid plan happens without checkout, so it is confirmed first. + function needsConfirm(plan: Plan, price: Price | undefined): boolean { + return !isFreePick(plan, price) && currentPlan !== null && currentPlan.key !== plan.key && minAmount(currentPlan) > 0; + } + + async function handlePick(plan: Plan, price?: Price): Promise { + if (!canManage || picking) return; + setPickError(null); + if (needsConfirm(plan, price)) { + setConfirmTarget({ plan, price }); + setConfirmError(null); + return; + } + setPicking(true); + let leaving = false; + try { + leaving = await choose(plan, price); + } catch (error) { + setPickError(errorMessage(error, t, 'error.generic')); + } finally { + if (!leaving) setPicking(false); + } + } + + async function confirmPlanChange(): Promise { + if (!confirmTarget) return; + const { plan, price } = confirmTarget; + setConfirmBusy(true); + setConfirmError(null); + let leaving = false; + try { + leaving = await choose(plan, price); + setConfirmTarget(null); + } catch (error) { + setConfirmError(errorMessage(error, t, 'error.generic')); + } finally { + if (!leaving) setConfirmBusy(false); + } + } + + async function retryPlans(): Promise { + setRetrying(true); + try { + await plans.refresh(); + } finally { + setRetrying(false); + } + } + + const intervalTabs = ( +
+ {availableIntervals.map((interval) => ( + + ))} +
+ ); + + function card(plan: Plan) { + const isCurrent = plan.key === currentKey; + const onPick = (price?: Price) => void handlePick(plan, price); + const visiblePrices = pricesForInterval(plan); + const kind = pickKind(plan, currentPlan); + const days = trialDays(plan); + const features = planFeatures(plan); + const buttonClass = `${kind === 'current' || kind === 'switch' ? 'bridge-btn-secondary' : 'bridge-btn-primary'} bridge-plan-select-btn`; + + if (planCard) { + return {planCard({ plan, prices: plan.prices, isCurrent, interval: selectedInterval, canChoose: canManage, onPick })}; + } + return ( +
+ {isCurrent && ( + + Your plan + + )} +
+

{plan.name}

+ {days !== null && {days}-day trial} +
+ + {visiblePrices[0] ? ( +
+ {formatAmount(visiblePrices[0].amount, visiblePrices[0].currency)} + {intervalSuffix(visiblePrices[0])} +
+ ) : plan.free ? ( +
+ Free +
+ ) : null} + + {planDescription ? planDescription({ plan, isCurrent }) : plan.description ?

{plan.description}

: null} + + {features.length > 0 && ( +
    + {features.map((feature) => ( +
  • + + {feature.name} +
  • + ))} +
+ )} + +
+ {visiblePrices.map((price) => ( + + ))} + + {plan.prices.length === 0 ? ( + + ) : visiblePrices.length === 0 ? ( +

+ Not available {intervalLabel(selectedInterval).toLowerCase()} +

+ ) : null} +
+ + {planFooter?.({ plan, isCurrent })} +
+ ); + } + + return ( +
+ {loading ? ( + (loadingState ?? ( +
+ +
+ )) + ) : loadError ? ( + <> + {loadError} +
+ +
+ + ) : ( + <> + {pickError && {pickError}} + + {successNotice && ( +
+ {successNotice} +
+ )} + + {uiState === 'payment-failed' && ( +
+ + {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.'} + + +
+ )} + + {list.length === 0 ? ( + (emptyState ?? ( +
+

No plans are available yet.

+
+ )) + ) : ( + <> + {heading ? ( +
+

{heading}

+ {showIntervalTabs && intervalTabs} +
+ ) : ( + showIntervalTabs && intervalTabs + )} + + {flagsKnown && !canManage && ( +

+ Ask the workspace owner to change the plan. +

+ )} + +
+ {sortedPlans.map(card)} +
+ + )} + + )} + + {confirmTarget && ( +
+
+

+ Change plan? +

+

+ Switch from {currentPlanName} to {confirmTarget.plan.name} ({formatPrice(confirmTarget.price)}). +

+

Any price difference shows on your next invoice.

+ {confirmError && {confirmError}} +
+ + +
+
+
+ )} +
+ ); +} + +/** Keys a custom card in the list without adding an element. */ +function PlanCardSlot({ children }: { children: ReactNode }) { + return <>{children}; +} + +export default PlanPicker; diff --git a/bridge-react/src/components/billing/QuotaBanner.tsx b/bridge-react/src/components/billing/QuotaBanner.tsx new file mode 100644 index 0000000..45b2a49 --- /dev/null +++ b/bridge-react/src/components/billing/QuotaBanner.tsx @@ -0,0 +1,97 @@ +/** + * A banner for one metric nearing or at its plan limit: + * + * ```tsx + * + * ``` + * + * Renders nothing below 80% of the limit, or for a metric with no limit. It + * shows numbers only and blocks nothing: whether something is allowed is a + * flag. A person with the `billingManage` flag gets an Upgrade link; anyone + * else is told to contact the workspace owner. + */ +import type { HTMLAttributes, MouseEvent } from 'react'; +import { useBridgeConfig, useCanManageBilling, useUsage } from '../../react/hooks.js'; +import { Link } from '../shared/Link.js'; +import { quotaFor, type Quota } from './quota.js'; + +export interface QuotaBannerProps extends HTMLAttributes { + /** The metric to watch, such as `projects`. */ + readonly metric: string; + /** The metric's name in the copy. @default the metric key */ + readonly label?: string; + /** Where Upgrade goes. @default the subscription page */ + readonly actionHref?: string; + /** Replaces Upgrade's navigation. */ + readonly onActionClick?: (quota: Quota) => void; +} + +const OWNER = 'Contact your workspace owner.'; + +function copyFor(q: Quota, admin: boolean, what: string): { title: string; body: string } { + const used = q.used.toLocaleString(); + const limit = q.limit.toLocaleString(); + if (q.used > q.limit) { + return admin + ? { title: `${what} over cap`, body: `You've used ${used} of ${limit}. Upgrade your plan to add headroom.` } + : { title: `${what} over cap`, body: `Your workspace is over its ${what} cap. ${OWNER}` }; + } + if (q.state === 'over') { + return admin + ? { title: `${what} limit reached`, body: `You've used all ${limit} on your plan. Upgrade your plan to add more.` } + : { title: `${what} limit reached`, body: `Your workspace has reached its ${what} limit. ${OWNER}` }; + } + const left = Math.max(0, q.limit - q.used).toLocaleString(); + return admin + ? { title: `${what} approaching cap`, body: `You've used ${used} of ${limit} (${left} left).` } + : { title: `${what} approaching cap`, body: `Your workspace is approaching its ${what} cap.` }; +} + +export function QuotaBanner({ metric, label, actionHref, onActionClick, className, ...rest }: QuotaBannerProps) { + const base = useBridgeConfig()?.billingBase ?? '/subscription'; + const canManage = useCanManageBilling(); + const usage = useUsage(); + + const quota = quotaFor(usage.value, metric); + if (quota === null || quota.state === 'ok') return null; + const name = label ?? metric; + const percent = Math.min(100, Math.round(quota.ratio * 100)); + const href = actionHref ?? (base || '/'); + const copy = copyFor(quota, canManage, name); + + function handleAction(event: MouseEvent) { + if (!onActionClick || !quota) return; + event.preventDefault(); + onActionClick(quota); + } + + return ( +
+
+ {copy.title} + {copy.body} + {quota.limit > 0 && ( + + {canManage && ( + + Upgrade + + )} +
+ ); +} + +export default QuotaBanner; diff --git a/bridge-react/src/components/billing/SubscriptionStatus.tsx b/bridge-react/src/components/billing/SubscriptionStatus.tsx new file mode 100644 index 0000000..4fdbcf3 --- /dev/null +++ b/bridge-react/src/components/billing/SubscriptionStatus.tsx @@ -0,0 +1,50 @@ +/** + * The workspace's plan name and a status badge (trial, active, past due, + * ending, canceled), from the billing facts. It follows plan changes on its + * own: the facts are fetched again on every billing change. + */ +import type { HTMLAttributes } from 'react'; +import { errorMessage } from '../../core/i18n.js'; +import { useBilling, useTranslator } from '../../react/hooks.js'; +import { statusBadge } from './plan-format.js'; + +export type SubscriptionStatusProps = HTMLAttributes; + +export function SubscriptionStatus({ className, ...rest }: SubscriptionStatusProps) { + const billing = useBilling(); + const t = useTranslator(); + const facts = billing.value; + const view = facts ? (facts.plan ? 'plan' : 'empty') : billing.error ? 'error' : 'loading'; + const badge = facts ? statusBadge(facts) : null; + + return ( + + {view === 'loading' ? ( + Loading… + ) : view === 'error' ? ( + + Subscription unavailable + + ) : facts?.plan ? ( + <> + {facts.plan.name} + {badge && ( + + {badge.label} + + )} + + ) : ( + No subscription + )} + + ); +} + +export default SubscriptionStatus; diff --git a/bridge-react/src/components/billing/UpgradeDialog.tsx b/bridge-react/src/components/billing/UpgradeDialog.tsx new file mode 100644 index 0000000..2535621 --- /dev/null +++ b/bridge-react/src/components/billing/UpgradeDialog.tsx @@ -0,0 +1,91 @@ +/** + * The dialog a plan limit or a missing plan feature opens. `` + * renders it whenever a request is open (a 402 through `bridgeFetch`, or an + * upgrade prompt). A person who may manage billing (the `billingManage` flag) + * gets a link to the plan page; anyone else is told to ask the owner. + */ +import { sanitizeReturnTo } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useRef, type DialogHTMLAttributes } from 'react'; +import type { UpgradeDialogProps as BaseProps } from '../../core/upgrade.js'; +import { Link } from '../shared/Link.js'; + +export interface UpgradeDialogProps extends BaseProps, Omit, 'onClose' | 'open'> {} + +export function UpgradeDialog({ request, upgradeHref, canUpgrade, onClose, className, ...rest }: UpgradeDialogProps) { + const dialog = useRef(null); + useEffect(() => { + const element = dialog.current; + if (element && !element.open && typeof element.showModal === 'function') element.showModal(); + }, []); + + const hasNumbers = typeof request.used === 'number' && typeof request.limit === 'number'; + // A link from the request is used only when it is a path on this site. + const href = sanitizeReturnTo(request.upgradeHref) ?? upgradeHref; + const variant = canUpgrade ? 'admin' : 'member'; + + return ( + onClose()} + {...rest} + > +
+ {request.kind === 'feature' ? ( + <> +

+ This feature isn't on your plan +

+

+ {canUpgrade ? 'Upgrade the plan to use it.' : 'Ask the workspace owner to upgrade the plan to use it.'} +

+ + ) : ( + <> +

+ You've reached your plan's limit +

+

+ {hasNumbers && request.metric ? ( + <> + This workspace has used {request.used?.toLocaleString()} of {request.limit?.toLocaleString()}{' '} + {request.metric} on its current plan. + + ) : request.metric ? ( + <> + This workspace has reached its {request.metric} limit. + + ) : ( + <>This workspace has reached a limit of its plan. + )}{' '} + {canUpgrade ? 'Upgrade the plan to keep going.' : 'Ask the workspace owner to upgrade the plan.'} +

+ + )} +
+ {canUpgrade ? ( + <> + + onClose()}> + Upgrade plan + + + ) : ( + + )} +
+
+
+ ); +} + +export default UpgradeDialog; diff --git a/bridge-react/src/components/billing/plan-format.ts b/bridge-react/src/components/billing/plan-format.ts new file mode 100644 index 0000000..0e66b14 --- /dev/null +++ b/bridge-react/src/components/billing/plan-format.ts @@ -0,0 +1,133 @@ +/** + * How the billing components word plans, prices and billing facts, as pure + * functions. Amounts are in the currency's minor units (2000 EUR is 20.00 EUR). + */ +import type { BillingFacts, Plan, Price } from '@nebulr-group/bridge-auth-core'; + +/** How many decimals a currency has: 2 for EUR, 0 for JPY. */ +function currencyDigits(code: string): number { + try { + return new Intl.NumberFormat('en', { style: 'currency', currency: code }).resolvedOptions().maximumFractionDigits ?? 2; + } catch { + return 2; + } +} + +/** `2900` + `usd` → `$29`; `950` → `$9.50`. An unknown currency code reads `29 XYZ`. */ +export function formatAmount(amount: number, currency: string, locale?: string): string { + const code = currency.toUpperCase(); + const value = amount / 10 ** currencyDigits(code); + try { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: code, + ...(Number.isInteger(value) ? { minimumFractionDigits: 0 } : {}), + }).format(value); + } catch { + return `${value} ${code}`; + } +} + +/** `/ month`, after a price; nothing for a price without an interval. */ +export function intervalSuffix(price: Price): string { + return price.interval ? `/ ${price.interval}` : ''; +} + +/** `$29 / month`, or `Free`. */ +export function formatPrice(price: Price | undefined): string { + if (!price || price.amount === 0) return 'Free'; + const suffix = intervalSuffix(price); + return suffix ? `${formatAmount(price.amount, price.currency)} ${suffix}` : formatAmount(price.amount, price.currency); +} + +/** The cheapest price a plan has in any interval; a plan with no price and not free sorts last. */ +export function minAmount(plan: Plan): number { + if (plan.free) return 0; + const amounts = plan.prices.map((p) => p.amount); + return amounts.length > 0 ? Math.min(...amounts) : Number.POSITIVE_INFINITY; +} + +/** A pick that costs nothing: a free plan, a plan without prices, or a zero price. */ +export function isFreePick(plan: Plan, price: Price | undefined): boolean { + return plan.free || price === undefined || price.amount === 0; +} + +/** What picking a plan does, relative to the current one. */ +export type PickKind = 'current' | 'choose' | 'upgrade' | 'switch'; + +export function pickKind(plan: Plan, current: Plan | null | undefined): PickKind { + if (current && current.key === plan.key) return 'current'; + if (!current) return 'choose'; + return minAmount(plan) > minAmount(current) ? 'upgrade' : 'switch'; +} + +/** The button text for a pick. */ +export function pickLabel(kind: PickKind, plan: Plan): string { + switch (kind) { + case 'current': + return 'Current plan'; + case 'upgrade': + return `Upgrade to ${plan.name}`; + case 'switch': + return `Switch to ${plan.name}`; + default: + return `Choose ${plan.name}`; + } +} + +/** A plan's trial length in days, or null for none. */ +export function trialDays(plan: Plan): number | null { + const trial = plan.trial; + const days = typeof trial === 'number' ? trial : trial !== null && typeof trial === 'object' ? (trial as { days?: unknown }).days : null; + return typeof days === 'number' && days > 0 ? days : null; +} + +/** The features a plan includes, for its card. */ +export function planFeatures(plan: Plan): { key: string; name: string }[] { + const features: unknown = plan.features; + if (Array.isArray(features)) { + return features.filter((f): f is string => typeof f === 'string').map((key) => ({ key, name: key })); + } + if (features === null || typeof features !== 'object') return []; + return Object.entries(features as Record) + .filter(([, value]) => value !== false && value !== null && value !== undefined) + .map(([key, value]) => ({ key, name: typeof value === 'string' ? value : key })); +} + +/** `Mar 4, 2027`, or null for no date. */ +export function formatDate(iso: string | null | undefined, locale?: string): string | null { + if (!iso) return null; + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return null; + return date.toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }); +} + +/** The line under the current plan's name: when the trial or period ends, or when it renews. */ +export function subscriptionMeta(facts: BillingFacts | null | undefined, locale?: string): string { + if (!facts) return ''; + if (facts.status === 'trialing') { + const ends = formatDate(facts.trialEnd, locale); + return ends ? `Trial ends ${ends}` : ''; + } + const end = formatDate(facts.periodEnd, locale); + if (!end) return ''; + if (facts.cancelAtPeriodEnd || facts.status === 'canceled') return `Ends ${end}`; + return facts.status === 'active' ? `Renews ${end}` : ''; +} + +/** The status badge beside the plan's name, or null when there is nothing to say. */ +export function statusBadge(facts: BillingFacts): { status: string; label: string } | null { + if (facts.cancelAtPeriodEnd && facts.status !== 'canceled') return { status: 'ending', label: 'ending' }; + switch (facts.status) { + case 'trialing': + return { status: 'trialing', label: 'trial' }; + case 'active': + return { status: 'active', label: 'active' }; + case 'past_due': + return { status: 'past_due', label: 'past due' }; + case 'canceled': + return { status: 'canceled', label: 'canceled' }; + default: + return null; + } +} diff --git a/bridge-react/src/components/billing/quota.ts b/bridge-react/src/components/billing/quota.ts new file mode 100644 index 0000000..8f7732d --- /dev/null +++ b/bridge-react/src/components/billing/quota.ts @@ -0,0 +1,43 @@ +/** + * One metric's usage against its plan limit, for your own UI: + * + * ```tsx + * const projects = useQuota('projects'); + * return projects ? {projects.used} of {projects.limit} projects : null; + * ``` + * + * Numbers only, never a gate: whether something is allowed is a flag. + */ +import type { UsageNumbers } from '@nebulr-group/bridge-auth-core'; +import { useMemo } from 'react'; +import { useUsage } from '../../react/hooks.js'; + +export type QuotaState = 'ok' | 'near' | 'over'; + +export interface Quota { + readonly used: number; + readonly limit: number; + /** `used / limit`; 1 for a limit of 0. */ + readonly ratio: number; + /** `near` from 80% of the limit, `over` once the limit is reached. */ + readonly state: QuotaState; +} + +/** From this share of the limit, a metric is `near` it. */ +export const NEAR_LIMIT = 0.8; + +/** A metric's quota from the usage numbers, or null when it has no limit or is not loaded. */ +export function quotaFor(numbers: UsageNumbers | null | undefined, metric: string): Quota | null { + const row = numbers?.metrics.find((m) => m.metric === metric); + if (!row || row.limit === null) return null; + const { used, limit } = row; + const ratio = limit > 0 ? used / limit : 1; + const state: QuotaState = used >= limit ? 'over' : ratio >= NEAR_LIMIT ? 'near' : 'ok'; + return { used, limit, ratio, state }; +} + +/** A metric's quota: null while loading and for a metric without a limit. */ +export function useQuota(metric: string): Quota | null { + const numbers = useUsage().value; + return useMemo(() => quotaFor(numbers, metric), [numbers, metric]); +} diff --git a/bridge-react/src/components/developer/ApiTokenManagement.tsx b/bridge-react/src/components/developer/ApiTokenManagement.tsx deleted file mode 100644 index 7bb9cd7..0000000 --- a/bridge-react/src/components/developer/ApiTokenManagement.tsx +++ /dev/null @@ -1,422 +0,0 @@ -import type { ApiToken, CreateApiTokenInput } from '@nebulr-group/bridge-auth-core'; -import type { FormEvent, HTMLAttributes } from 'react'; -import { useEffect, useState } from 'react'; -import { getBridgeAuth } from '../../core/bridge-instance'; - -type AvailablePrivilege = { - key: string; - description?: string; -}; - -interface Props extends HTMLAttributes {} - -export function ApiTokenManagement({ className, style, ...rest }: Props) { - const [tokens, setTokens] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - const [success, setSuccess] = useState(null); - - const [showCreateForm, setShowCreateForm] = useState(false); - const [creating, setCreating] = useState(false); - const [createName, setCreateName] = useState(''); - const [createExpiry, setCreateExpiry] = useState(''); - - const [availablePrivileges, setAvailablePrivileges] = useState([]); - const [selectedPrivileges, setSelectedPrivileges] = useState([]); - const [privSearch, setPrivSearch] = useState(''); - const [privDropdownOpen, setPrivDropdownOpen] = useState(false); - - const [newToken, setNewToken] = useState(null); - const [showToken, setShowToken] = useState(false); - - const [revokeTarget, setRevokeTarget] = useState(null); - const [revokeDialogOpen, setRevokeDialogOpen] = useState(false); - const [revoking, setRevoking] = useState(false); - - useEffect(() => { - let mounted = true; - (async () => { - try { - const list = await getBridgeAuth().apiTokens.listTokens(); - if (mounted) setTokens(list); - } catch (err) { - if (mounted) setError(err instanceof Error ? err.message : 'Failed to load API tokens'); - } finally { - if (mounted) setLoading(false); - } - })(); - return () => { - mounted = false; - }; - }, []); - - useEffect(() => { - if (!showCreateForm) return; - (async () => { - try { - const list = await (getBridgeAuth().apiTokens as any).listAvailablePrivileges?.(); - if (Array.isArray(list)) setAvailablePrivileges(list); - } catch { - /* non-fatal — picker shows empty */ - } - })(); - }, [showCreateForm]); - - useEffect(() => { - if (!privDropdownOpen) return; - function handleOutsideClick(e: MouseEvent) { - const picker = document.querySelector('.bridge-privilege-picker'); - if (picker && !picker.contains(e.target as Node)) setPrivDropdownOpen(false); - } - document.addEventListener('click', handleOutsideClick); - return () => document.removeEventListener('click', handleOutsideClick); - }, [privDropdownOpen]); - - function resetCreateForm() { - setCreateName(''); - setSelectedPrivileges([]); - setPrivSearch(''); - setPrivDropdownOpen(false); - setCreateExpiry(''); - } - - async function handleCreate(e: FormEvent) { - e.preventDefault(); - setCreating(true); - setError(null); - try { - const input: CreateApiTokenInput = { - name: createName.trim(), - privileges: selectedPrivileges, - expireAt: createExpiry || undefined, - }; - const result = await getBridgeAuth().apiTokens.createToken(input); - setNewToken(result.token); - setTokens((prev) => [result.record, ...prev]); - setShowCreateForm(false); - resetCreateForm(); - setSuccess('Token created. Copy it now — it will not be shown again.'); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to create token'); - } finally { - setCreating(false); - } - } - - async function confirmRevoke() { - if (!revokeTarget) return; - setRevoking(true); - setError(null); - try { - await getBridgeAuth().apiTokens.revokeToken(revokeTarget.id); - setTokens((prev) => prev.filter((t) => t.id !== revokeTarget.id)); - setSuccess(`Token "${revokeTarget.name}" revoked.`); - setRevokeDialogOpen(false); - setRevokeTarget(null); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to revoke token'); - } finally { - setRevoking(false); - } - } - - async function copyToClipboard(text: string) { - try { - await navigator.clipboard.writeText(text); - setSuccess('Copied to clipboard!'); - setTimeout(() => setSuccess(null), 3000); - } catch { - setError('Failed to copy to clipboard'); - } - } - - function formatDate(iso: string | null | undefined): string { - if (!iso) return '—'; - return new Date(iso).toLocaleDateString(); - } - - const filteredPrivileges = availablePrivileges.filter( - (p) => - !selectedPrivileges.includes(p.key) && - p.key.toLowerCase().includes(privSearch.toLowerCase()) - ); - - return ( - <> -
-
-
-

API Tokens

-

- Long-lived JWT tokens for programmatic API access. -

-
- -
- - {error &&
{error}
} - {success &&
{success}
} - - {newToken && ( -
-

- ⚠ Store this token securely — you won't be able to see it again. -

-
- - - -
- -
- )} - - {showCreateForm && ( -
-

New API Token

-
-
-
- - setCreateName(e.target.value)} - /> -
-
- -
-
setPrivDropdownOpen((v) => !v)} - > - {selectedPrivileges.map((priv) => ( - - {priv} - - - ))} - {selectedPrivileges.length === 0 && ( - Select privileges… - )} -
- {privDropdownOpen && ( -
- setPrivSearch(e.target.value)} - onClick={(e) => e.stopPropagation()} - /> - {filteredPrivileges.length === 0 ? ( -
No privileges found
- ) : ( - filteredPrivileges.map((priv) => ( - - )) - )} -
- )} -
-
-
- - setCreateExpiry(e.target.value)} - /> -
-
-
- -
-
-
- )} - -
- {loading ? ( -
Loading…
- ) : tokens.length === 0 ? ( -
- No API tokens yet. Create one to get started. -
- ) : ( - - - - - - - - - - - - {tokens.map((token) => ( - - - - - - - - ))} - -
NamePrivilegesCreatedExpires
{token.name} -
- {token.privileges.map((priv) => ( - - {priv} - - ))} -
-
{formatDate(token.createdAt)}{formatDate(token.expireAt)} - -
- )} -
-
- - {revokeDialogOpen && ( - <> -
{ - setRevokeDialogOpen(false); - setRevokeTarget(null); - }} - /> -
-

Revoke token?

-

- Token {revokeTarget?.name} will be permanently revoked and can no longer be used. -

-
- - -
-
- - )} - - ); -} - -export default ApiTokenManagement; diff --git a/bridge-react/src/components/developer/RealtimeDevBadge.tsx b/bridge-react/src/components/developer/RealtimeDevBadge.tsx deleted file mode 100644 index 6a4e9ee..0000000 --- a/bridge-react/src/components/developer/RealtimeDevBadge.tsx +++ /dev/null @@ -1,201 +0,0 @@ -/** - * TBP-644 — development-only "Live updates off — why?" corner badge. - * - * `` mounts this automatically. It renders only in development - * builds (`process.env.NODE_ENV !== 'production'`) and only while live updates - * are actually off: refused (`unauthorized`), connected but deaf (`degraded`), - * or retrying for longer than 30 s. Opt out with `config.devBadge: false`. - * - * Styled inline so it neither needs `@nebulr-group/bridge-react/styles` nor - * picks anything up from the host app's CSS. - */ -import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from 'react'; -import { useRealtimeStatusDetail } from '../../core/realtime-status'; -import { - REALTIME_BADGE_RETRYING_AFTER_MS, - createRetryClock, - isDevBuild, - realtimeBadgeView, -} from '../../core/realtime-dev-badge'; - -export interface RealtimeDevBadgeProps { - /** Set false to never render (the provider passes `config.devBadge`). Default true. */ - enabled?: boolean; -} - -const PANEL_ID = 'bridge-realtime-dev-badge-panel'; - -const FONT = "ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"; -const MONO = 'ui-monospace, SFMono-Regular, Menlo, monospace'; - -const s = { - root: { - position: 'fixed', - right: 16, - bottom: 16, - zIndex: 2147483000, - margin: 0, - padding: 0, - fontFamily: FONT, - fontSize: 12, - lineHeight: 1.4, - fontWeight: 400, - letterSpacing: 'normal', - textTransform: 'none', - textAlign: 'left', - color: '#f5f5f5', - }, - srOnly: { - position: 'absolute', - width: 1, - height: 1, - overflow: 'hidden', - clip: 'rect(0 0 0 0)', - whiteSpace: 'nowrap', - }, - badge: { - display: 'block', - maxWidth: 'min(360px, calc(100vw - 32px))', - margin: 0, - padding: 0, - background: '#1f2328', - border: '1px solid #3d444d', - borderRadius: 8, - boxShadow: '0 4px 16px rgba(0, 0, 0, 0.25)', - }, - bar: { display: 'flex', alignItems: 'center' }, - button: { - appearance: 'none', - margin: 0, - padding: '6px 10px', - border: 'none', - borderRadius: 8, - background: 'transparent', - color: 'inherit', - font: 'inherit', - cursor: 'pointer', - textAlign: 'left', - }, - dot: { color: '#f85149' }, - panel: { display: 'block', padding: '4px 10px 10px', borderTop: '1px solid #3d444d' }, - row: { display: 'flex', gap: 8, paddingTop: 6 }, - label: { flex: '0 0 72px', color: '#9198a1' }, - code: { fontFamily: MONO, overflowWrap: 'anywhere' }, - link: { display: 'inline-block', marginTop: 8, color: '#58a6ff', textDecoration: 'underline' }, - note: { display: 'block', marginTop: 8, color: '#9198a1', fontSize: 11 }, -} satisfies Record; - -/** - * The badge. Renders nothing in production builds or when `enabled` is false — - * checked before any hook runs, so a production tree never subscribes. - */ -export function RealtimeDevBadge({ enabled = true }: RealtimeDevBadgeProps) { - if (!enabled || !isDevBuild()) return null; - return ; -} - -function RealtimeDevBadgeView() { - const status = useRealtimeStatusDetail(); - const clockRef = useRef(createRetryClock()); - // Start of the current retry run — stable across the closed/connecting flips - // inside one episode (see createRetryClock). Idempotent for a given status, - // so StrictMode's double-invoke is harmless. - const retryingSince = useMemo(() => clockRef.current(status, Date.now()), [status]); - const [now, setNow] = useState(() => Date.now()); - const [expanded, setExpanded] = useState(false); - const [dismissedKey, setDismissedKey] = useState(undefined); - const toggleRef = useRef(null); - - // Tick `now` once the retrying threshold passes — nothing else re-renders. - useEffect(() => { - if (retryingSince === undefined) return; - const remaining = retryingSince + REALTIME_BADGE_RETRYING_AFTER_MS - Date.now(); - const timer = setTimeout(() => setNow(Date.now()), Math.max(0, remaining) + 50); - return () => clearTimeout(timer); - }, [retryingSince]); - - const view = realtimeBadgeView(status, retryingSince, now); - const visible = !!view && view.key !== dismissedKey; - - const onKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape' && expanded) { - setExpanded(false); - toggleRef.current?.focus(); - } - }; - - return ( -
- - {visible && view ? `Bridge live updates are off: ${view.reason}` : ''} - - {visible && view && ( - - )} -
- ); -} - -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 ( -
- {(() => { - const own = pages[page]; - return typeof own === 'function' ? own(route) : own; - })()} -
- ); - } - - // 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 ? ( - <> -

{t('forgot.successHeading')}

- - - ) : ( -
-
- -
- setPassword(e.target.value)} - disabled={loading} - /> - -
-
-
- - setConfirmPassword(e.target.value)} - disabled={loading} - /> -
- -
- ) - ) : emailSent ? ( - <> - {t('forgot.emailSent')} - - - ) : ( - <> -
-
- - setEmail(e.target.value)} - disabled={loading} - /> -
- -
- - - )} -
- ); -} - -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')} -
- -
- - ) : ( - <> -
-
- - setEmail(e.target.value)} - disabled={fpLoading} - /> -
- -
-
- -
- - )} -
- ); - } - - return ( - - {error && {error}} - -
-
- - setEmail(e.target.value)} - disabled={loading} - /> -
- -
- -
- setPassword(e.target.value)} - disabled={loading} - /> - -
-
- - - - {effectiveShowForgotPassword && ( -
- -
- )} -
- - {(effectiveShowPasskeys || effectiveShowMagicLink || effectiveSso.length > 0) && ( -
{t('divider.or')}
- )} - - {effectiveShowPasskeys && ( -
- { - setStep('passkey-request'); - setError(null); - } - } - messages={messages} - className="bridge-btn bridge-btn-secondary bridge-sso-btn" - /> -
- )} - - {effectiveShowMagicLink && ( - - )} - - {effectiveSso.map((conn) => ( -
- {onSsoClick ? ( - - ) : ( - } - /> - )} -
- ))} - - {footer ?? ( - effectiveShowSignupLink && ( -
- {t('login.signupPrompt')}{' '} - {t('login.signupLink')} -
- ) - )} -
- ); -} - -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 && ( - - )} - - ) : ( - <> -
-
- - setEmail(e.target.value)} - disabled={loading} - /> -
- -
- {loginHref && ( - - )} - - )} -
- ); -} - -export default MagicLink; diff --git a/bridge-react/src/components/sdk-auth/MfaChallenge.tsx b/bridge-react/src/components/sdk-auth/MfaChallenge.tsx deleted file mode 100644 index f5bd5cb..0000000 --- a/bridge-react/src/components/sdk-auth/MfaChallenge.tsx +++ /dev/null @@ -1,202 +0,0 @@ -import type { HTMLAttributes } from 'react'; -import { useEffect, 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'; - -interface Props extends Omit, 'onError'> { - onVerified?: () => void; - onError?: (error: Error) => void; - showRecoveryOption?: boolean; - /** Heading text. Pass `null`/`''` to render no heading and use your own page title. */ - heading?: string | null; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function MfaChallenge({ - onVerified, - onError, - showRecoveryOption = true, - heading, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [code, setCode] = useState(''); - const [backupCode, setBackupCode] = useState(''); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - const [useRecovery, setUseRecovery] = useState(false); - const [resendCountdown, setResendCountdown] = useState(0); - - const wrapperHeading = heading !== undefined ? heading : t('mfa.challengeHeading'); - - useEffect(() => { - if (resendCountdown <= 0) return; - const id = setInterval(() => setResendCountdown((v) => v - 1), 1000); - return () => clearInterval(id); - }, [resendCountdown]); - - async function handleResend() { - if (loading || resendCountdown > 0) return; - setError(null); - setLoading(true); - try { - await (getBridgeAuth() as any).resendMfaCode(); - setCode(''); - setResendCountdown(60); - } catch (err: any) { - setError(authErrorMessage(err, t, 'mfa.error.resend')); - onError?.(err); - } finally { - setLoading(false); - } - } - - async function handleVerify(e: React.FormEvent) { - e.preventDefault(); - if (loading) return; - setError(null); - setLoading(true); - try { - await (getBridgeAuth() as any).verifyMfa(code); - onVerified?.(); - } catch (err: any) { - setError(authErrorMessage(err, t, 'mfa.error.invalidCode')); - onError?.(err); - } finally { - setLoading(false); - } - } - - async function handleRecovery(e: React.FormEvent) { - e.preventDefault(); - if (loading) return; - setError(null); - setLoading(true); - try { - await (getBridgeAuth() as any).resetMfa(backupCode); - onVerified?.(); - } catch (err: any) { - setError(authErrorMessage(err, t, 'mfa.error.invalidRecoveryCode')); - onError?.(err); - } finally { - setLoading(false); - } - } - - return ( - - {error && {error}} - - {!useRecovery ? ( - <> -
-
- - setCode(e.target.value)} - disabled={loading} - /> -
- -
-

- {resendCountdown > 0 ? ( - t('mfa.resendCountdown', { seconds: resendCountdown }) - ) : ( - <> - {t('mfa.resendPrompt')}{' '} - - . - - )} -

- {showRecoveryOption && ( -
- -
- )} - - ) : ( - <> -
-
- - setBackupCode(e.target.value)} - disabled={loading} - /> -
- -
-
- -
- - )} -
- ); -} - -export default MfaChallenge; diff --git a/bridge-react/src/components/sdk-auth/MfaSetup.tsx b/bridge-react/src/components/sdk-auth/MfaSetup.tsx deleted file mode 100644 index 2fe7184..0000000 --- a/bridge-react/src/components/sdk-auth/MfaSetup.tsx +++ /dev/null @@ -1,250 +0,0 @@ -import type { HTMLAttributes } from 'react'; -import { useEffect, useState } from 'react'; -import type { MessageKey, 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'; - -interface Props extends Omit, 'onError'> { - onComplete?: () => void; - onError?: (error: Error) => void; - /** Heading text. Pass `null`/`''` to render no heading and use your own page title. */ - heading?: string | null; - /** - * Step description. Pass `null`/`''` to render nothing and use your own - * subtitle (TBP-631). - * - * This component has THREE steps, each with its own description, but one - * wrapper — so an override replaces whichever description is showing. - */ - description?: string | null; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -// TBP-631 — the three step descriptions used to sit inline in the markup, -// outside AuthFormWrapper's heading guard, so `heading={null}` could not reach -// them. They live in one wrapper rather than three, so the wrapper cannot know -// the step — the component computes it and hands over the resolved value. -const STEP_DESCRIPTION_KEYS: Record<'phone' | 'verify' | 'backup', MessageKey> = { - phone: 'mfaSetup.phoneDescription', - verify: 'mfaSetup.verifyDescription', - backup: 'mfaSetup.backupDescription', -}; - -export function MfaSetup({ - onComplete, - onError, - heading, - description, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [step, setStep] = useState<'phone' | 'verify' | 'backup'>('phone'); - const [phoneNumber, setPhoneNumber] = useState(''); - const [code, setCode] = useState(''); - const [backupCode, setBackupCode] = useState(null); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - const [copied, setCopied] = useState(false); - const [resendCountdown, setResendCountdown] = useState(0); - - const wrapperHeading = heading !== undefined ? heading : t('mfaSetup.heading'); - // `undefined` = not overridden (use the built-in); `null` = host suppressed it. - const wrapperDescription = - description !== undefined ? description : t(STEP_DESCRIPTION_KEYS[step]); - - useEffect(() => { - if (resendCountdown <= 0) return; - const id = setInterval(() => setResendCountdown((v) => v - 1), 1000); - return () => clearInterval(id); - }, [resendCountdown]); - - async function handleSendCode(e: React.FormEvent) { - e.preventDefault(); - if (loading) return; - setError(null); - setLoading(true); - try { - await (getBridgeAuth() as any).setupMfa(phoneNumber); - setStep('verify'); - setResendCountdown(60); - } catch (err: any) { - setError(authErrorMessage(err, t, 'mfaSetup.error.sendCode')); - onError?.(err); - } finally { - setLoading(false); - } - } - - async function handleResendCode() { - if (loading || resendCountdown > 0) return; - setError(null); - setLoading(true); - try { - await (getBridgeAuth() as any).setupMfa(phoneNumber); - setCode(''); - setResendCountdown(60); - } catch (err: any) { - setError(authErrorMessage(err, t, 'mfaSetup.error.resend')); - onError?.(err); - } finally { - setLoading(false); - } - } - - async function handleVerifyCode(e: React.FormEvent) { - e.preventDefault(); - if (loading) return; - setError(null); - setLoading(true); - try { - const result = await (getBridgeAuth() as any).confirmMfaSetup(code); - setBackupCode(result.backupCode ?? null); - setStep('backup'); - } catch (err: any) { - setError(authErrorMessage(err, t, 'mfa.error.invalidCode')); - onError?.(err); - } finally { - setLoading(false); - } - } - - async function copyBackupCode() { - if (!backupCode) return; - await navigator.clipboard.writeText(backupCode); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } - - async function handleDone() { - await (getBridgeAuth() as any).completeMfaSetup(); - onComplete?.(); - } - - return ( - - {error && {error}} - - {step === 'phone' && ( -
-
- - setPhoneNumber(e.target.value)} - disabled={loading} - /> -
- -
- )} - - {step === 'verify' && ( - <> -
-
- - setCode(e.target.value)} - disabled={loading} - /> -
- -
-

- {resendCountdown > 0 ? ( - t('mfa.resendCountdown', { seconds: resendCountdown }) - ) : ( - <> - {t('mfa.resendPrompt')}{' '} - - . - - )} -

- - - )} - - {step === 'backup' && ( - <> - {t('mfaSetup.successHeading')} - {backupCode && ( -
- {backupCode} - -
- )} - - - )} -
- ); -} - -export default MfaSetup; diff --git a/bridge-react/src/components/sdk-auth/PasskeyLogin.tsx b/bridge-react/src/components/sdk-auth/PasskeyLogin.tsx deleted file mode 100644 index 7f3509d..0000000 --- a/bridge-react/src/components/sdk-auth/PasskeyLogin.tsx +++ /dev/null @@ -1,96 +0,0 @@ -import type { ButtonHTMLAttributes } from 'react'; -import { useEffect, useState } from 'react'; -import type { MessageOverrides } from '@nebulr-group/bridge-auth-core'; -import { getBridgeAuth } from '../../core/bridge-instance'; -import { getTranslator } from '../../i18n'; -import { authErrorMessage, isOriginNotAllowed } from './shared/auth-error'; -import { Spinner } from './shared/Spinner'; -import { passkeysSupported, startPasskeyAuthentication } from '../../core/webauthn'; -import { PasskeyIcon } from './shared/icons'; - -interface Props extends Omit, 'onError'> { - onLogin?: () => void; - onError?: (error: Error) => void; - onSetupPasskey?: () => void; - setupHref?: string; - /** Offer passkeys in the browser's autofill (conditional mediation). */ - autofill?: boolean; - /** Button label. Defaults to the catalogue's `passkey.loginButton`. */ - label?: string; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function PasskeyLogin({ - onLogin, - onError, - onSetupPasskey, - setupHref, - autofill = false, - label, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [loading, setLoading] = useState(false); - // Hidden where the browser cannot run a passkey ceremony (as bridge-svelte). - // Read after mount, so a server render and the first client render agree. - const [supported, setSupported] = useState(false); - useEffect(() => setSupported(passkeysSupported()), []); - - // TBP-743 / TBP-515 — the real ceremony: options from Bridge, the - // authenticator in the browser, the signed answer back to Bridge. This used - // to call `authenticateWithPasskey()` with no answer at all, so no - // authenticator was ever asked and the sign-in could not succeed. - async function handleClick() { - if (loading) return; - setLoading(true); - try { - const auth = getBridgeAuth(); - const options = await auth.getPasskeyAuthOptions(); - const response = await startPasskeyAuthentication(options, autofill); - await auth.authenticateWithPasskey(response); - onLogin?.(); - } catch (err: any) { - // The authenticator refused or found no passkey: offer to create one. - if (err?.name === 'NotAllowedError' && (onSetupPasskey || setupHref)) { - if (onSetupPasskey) onSetupPasskey(); - else if (setupHref && typeof window !== 'undefined') window.location.href = setupHref; - return; - } - if (err?.name === 'NotAllowedError') { - onError?.(new Error(t('passkey.error.authCancelled'))); - return; - } - // TBP-669 — the origin refusal travels as-is (code / status intact), so - // LoginForm can recognise it and show the fix instead of "Signing in…". - onError?.(isOriginNotAllowed(err) ? err : new Error(authErrorMessage(err, t, 'passkey.error.auth'))); - } finally { - setLoading(false); - } - } - - if (!supported) return null; - - return ( - - ); -} - -export default PasskeyLogin; diff --git a/bridge-react/src/components/sdk-auth/PasskeyRequestSetupLink.tsx b/bridge-react/src/components/sdk-auth/PasskeyRequestSetupLink.tsx deleted file mode 100644 index 6433d98..0000000 --- a/bridge-react/src/components/sdk-auth/PasskeyRequestSetupLink.tsx +++ /dev/null @@ -1,141 +0,0 @@ -import type { HTMLAttributes } 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'; - -interface Props extends Omit, 'onError'> { - initialEmail?: string; - onSent?: () => void; - onError?: (error: Error) => void; - onBack?: () => void; - loginHref?: string; - /** Heading text. Pass `null`/`''` to render no heading and use your own page title. */ - heading?: string | null; - /** - * Step description. Pass `null`/`''` to render nothing and use your own - * subtitle (TBP-631). Applies to whichever view is showing; the two views - * have different built-in copy, and the 'sent' one carries markup, so a - * string override replaces both with the same sentence. - */ - description?: string | null; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function PasskeyRequestSetupLink({ - initialEmail = '', - onSent, - onError, - onBack, - loginHref = '/auth/login', - heading, - description, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [email, setEmail] = useState(initialEmail); - const [loading, setLoading] = useState(false); - const [sent, setSent] = useState(false); - const [error, setError] = useState(null); - - const builtInHeading = sent ? t('passkey.sentHeading') : t('passkey.createHeading'); - const wrapperHeading = heading !== undefined ? heading : builtInHeading; - - // The catalogue holds the whole sentence with a `{email}` placeholder so a - // locale can put the address wherever it belongs; the split below runs on the - // already-translated string purely to wrap it in ``. - const sentDescriptionParts = t('passkey.sentDescription').split('{email}'); - const sentDescriptionSlot = ( -

- {sentDescriptionParts[0]} - {email} - {sentDescriptionParts[1] ?? ''} -

- ); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - if (loading) return; - setError(null); - setLoading(true); - try { - // auth-core's name for it; `sendPasskeySetupLink` never existed (TBP-743). - await getBridgeAuth().requestPasskeySetupLink(email); - setSent(true); - onSent?.(); - } catch (err: any) { - setError(authErrorMessage(err, t, 'passkey.error.sendLink')); - onError?.(err); - } finally { - setLoading(false); - } - } - - const backLink = onBack ? ( - - ) : ( - {t('action.backToLogin')} - ); - - if (sent) { - return ( - -
{backLink}
-
- ); - } - - return ( - - {error && {error}} - -
-
- - setEmail(e.target.value)} - disabled={loading} - /> -
- -
-
{backLink}
-
- ); -} - -export default PasskeyRequestSetupLink; diff --git a/bridge-react/src/components/sdk-auth/PasskeySetup.tsx b/bridge-react/src/components/sdk-auth/PasskeySetup.tsx deleted file mode 100644 index 66a8ce3..0000000 --- a/bridge-react/src/components/sdk-auth/PasskeySetup.tsx +++ /dev/null @@ -1,160 +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 { passkeysSupported, startPasskeyRegistration } from '../../core/webauthn'; - -interface Props extends Omit, 'onError'> { - 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). - * - * The built-in is `passkey.setupClickPrompt`, not `passkey.setupDescription`: - * this screen waits for a click before it raises the browser ceremony, so the - * "follow the prompt from your browser" copy would be describing something - * that has not started (TBP-633). - */ - description?: string | null; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; - /** The link has expired: offer "Request new setup link" (as bridge-svelte). */ - onExpired?: () => void; -} - -type SetupError = 'expired' | 'cancelled' | 'unsupported' | 'general'; - -function classifyError(err: any): SetupError { - if (err?.name === 'NotAllowedError') return 'cancelled'; - const msg = String(err?.message ?? '').toLowerCase(); - if (msg.includes('expired') || msg.includes('invalid token') || msg.includes('not found')) return 'expired'; - return 'general'; -} - -export function PasskeySetup({ - token, - onComplete, - onError, - loginHref = '/auth/login', - heading, - headingSlot, - description, - messages, - onExpired, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - const [errorType, setErrorType] = useState(null); - const [done, setDone] = useState(false); - - const builtInHeading = done ? t('passkey.setupSuccessHeading') : t('passkey.setupHeading'); - const wrapperHeading = heading !== undefined ? heading : builtInHeading; - // Only the pre-click view has a description; the success view's copy is the - // Alert below it. - const wrapperDescription = done - ? null - : description !== undefined - ? description - : t('passkey.setupClickPrompt'); - - // TBP-743 / TBP-515 — the real ceremony: registration options for this - // link's token from Bridge, the authenticator in the browser, the new - // credential back to Bridge to verify. This used to call a - // `registerPasskeyWithToken()` that auth-core does not have, so every - // emailed setup link ended in "Passkey setup failed." - async function handleRegister() { - if (loading) return; - setError(null); - setErrorType(null); - if (!passkeysSupported()) { - setErrorType('unsupported'); - setError(t('passkey.error.unsupported')); - return; - } - setLoading(true); - try { - const auth = getBridgeAuth(); - const options = await auth.getPasskeyRegistrationOptions(token); - const credential = await startPasskeyRegistration(options); - const result = await auth.verifyPasskeyRegistration(credential, token); - if (!result?.verified) { - setErrorType('general'); - setError(t('passkey.error.verify')); - return; - } - setDone(true); - onComplete?.(); - } catch (err: any) { - const type = classifyError(err); - setErrorType(type); - setError( - type === 'cancelled' - ? t('passkey.error.cancelled') - : type === 'expired' - ? t('passkey.error.expired') - : authErrorMessage(err, t, 'passkey.error.setupFailed'), - ); - onError?.(err); - } finally { - setLoading(false); - } - } - - return ( - - {error && {error}} - {errorType === 'expired' && onExpired ? ( - - ) : null} - - {done ? ( - <> - {t('passkey.setupSuccessDescription')} - - - ) : ( - - )} - - ); -} - -export default PasskeySetup; diff --git a/bridge-react/src/components/sdk-auth/SignupForm.tsx b/bridge-react/src/components/sdk-auth/SignupForm.tsx deleted file mode 100644 index 62a75ee..0000000 --- a/bridge-react/src/components/sdk-auth/SignupForm.tsx +++ /dev/null @@ -1,171 +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'; - -interface Props extends Omit, 'onError'> { - onSignup?: () => void; - onError?: (error: Error) => void; - showLoginLink?: boolean; - 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; - /** - * Success-state description. Pass `null`/`''` to render nothing (TBP-631). - * - * NOT lifted into AuthFormWrapper, unlike most of the other components: it - * belongs under the "Check your email" heading, which is rendered inside the - * wrapper's children rather than as the wrapper heading. Hoisting it would - * print the description above the heading it belongs to. - */ - description?: string | null; - footer?: ReactNode; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function SignupForm({ - onSignup, - onError, - showLoginLink = true, - loginHref = '/auth/login', - heading, - headingSlot, - description, - footer, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [email, setEmail] = useState(''); - const [firstName, setFirstName] = useState(''); - const [lastName, setLastName] = useState(''); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - const [success, setSuccess] = useState(false); - - const wrapperHeading = heading !== undefined ? heading : t('signup.heading'); - - // The catalogue holds the whole sentence with an `{email}` placeholder so a - // locale can put the address wherever it belongs; the split below runs on the - // already-translated string purely to wrap it in ``. - const successDescriptionParts = t('signup.successDescription').split('{email}'); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - if (loading) return; - setError(null); - setLoading(true); - try { - await getBridgeAuth().signup(email, firstName, lastName); - setSuccess(true); - onSignup?.(); - } catch (err: any) { - setError(authErrorMessage(err, t, 'signup.error.create')); - onError?.(err); - } finally { - setLoading(false); - } - } - - const loginFooter = footer ?? ( - showLoginLink && ( -
- {t('signup.loginPrompt')} {t('signup.loginLink')} -
- ) - ); - - 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 ? ( - <> -

{t('signup.successHeading')}

- {description === undefined ? ( -

- {successDescriptionParts[0]} - {email} - {successDescriptionParts[1] ?? ''} -

- ) : description ? ( -

{description}

- ) : null} - {loginFooter} - - ) : ( - <> - {error && {error}} - -
-
- - setEmail(e.target.value)} - disabled={loading} - /> -
-
- - setFirstName(e.target.value)} - disabled={loading} - /> -
-
- - setLastName(e.target.value)} - disabled={loading} - /> -
- -
- - {loginFooter} - - )} -
- ); -} - -export default SignupForm; diff --git a/bridge-react/src/components/sdk-auth/SsoButton.tsx b/bridge-react/src/components/sdk-auth/SsoButton.tsx deleted file mode 100644 index 92af82a..0000000 --- a/bridge-react/src/components/sdk-auth/SsoButton.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import type { FederationConnection, MessageOverrides } from '@nebulr-group/bridge-auth-core'; -import type { ButtonHTMLAttributes, ReactNode } from 'react'; -import { useState } from 'react'; -import { getBridgeAuth } from '../../core/bridge-instance'; -import { Spinner } from './shared/Spinner'; -import { getTranslator } from '../../i18n'; -import { authErrorMessage, isOriginNotAllowed } from './shared/auth-error'; - -interface Props extends Omit, 'onError'> { - connection: FederationConnection; - label?: string; - mode?: 'redirect' | 'popup'; - onSuccess?: () => void; - onError?: (error: Error) => void; - icon?: ReactNode; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function SsoButton({ - connection, - label, - mode = 'redirect', - onSuccess, - onError, - icon, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const [loading, setLoading] = useState(false); - // `label` still wins: an app naming its own provider button is voice, not - // mechanics, and the catalogue only supplies the default (TBP-634). - const buttonLabel = label ?? t('sso.continueWith', { provider: connection.name }); - - async function handleClick() { - if (loading) return; - setLoading(true); - try { - const result = await (getBridgeAuth() as any).startSsoLogin(connection.type, { mode }); - if (result.type === 'auth_success') { - onSuccess?.(); - } else if (result.type === 'auth_error') { - throw new Error(result.error || t('sso.error.login')); - } - } catch (err: any) { - // TBP-669 — the origin refusal travels as-is (code / status intact), so - // LoginForm can recognise it and show the fix. - if (isOriginNotAllowed(err)) { - authErrorMessage(err, t, 'sso.error.login'); // logs the one console line - onError?.(err); - return; - } - const message = err.message?.includes('popup') - ? t('sso.error.popupBlocked') - : authErrorMessage(err, t, 'sso.error.login'); - onError?.(new Error(message)); - } finally { - setLoading(false); - } - } - - return ( - - ); -} - -export default SsoButton; diff --git a/bridge-react/src/components/sdk-auth/SsoProviderIcon.tsx b/bridge-react/src/components/sdk-auth/SsoProviderIcon.tsx deleted file mode 100644 index 78186f4..0000000 --- a/bridge-react/src/components/sdk-auth/SsoProviderIcon.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import type { HTMLAttributes } from 'react'; - -interface Props extends HTMLAttributes { - type: string; -} - -export function SsoProviderIcon({ type, className, style, ...rest }: Props) { - return ( - - {type === 'google' && ( - - )} - {type === 'ms-azure-ad' && ( - - )} - {type === 'linkedin' && ( - - )} - {type === 'facebook' && ( - - )} - {type === 'github' && ( - - )} - {type === 'apple' && ( - - )} - - ); -} - -export default SsoProviderIcon; diff --git a/bridge-react/src/components/sdk-auth/TenantSelector.tsx b/bridge-react/src/components/sdk-auth/TenantSelector.tsx deleted file mode 100644 index 9703456..0000000 --- a/bridge-react/src/components/sdk-auth/TenantSelector.tsx +++ /dev/null @@ -1,92 +0,0 @@ -import type { MessageOverrides, TenantUser } from '@nebulr-group/bridge-auth-core'; -import type { HTMLAttributes, ReactNode } from 'react'; -import { useState } from 'react'; -import { getBridgeAuth, useBridgeStore } from '../../core/bridge-instance'; -import { AuthFormWrapper } from './shared/AuthFormWrapper'; -import { Alert } from './shared/Alert'; -import { Spinner } from './shared/Spinner'; -import { getTranslator } from '../../i18n'; -import { authErrorMessage } from './shared/auth-error'; - -interface Props extends Omit, 'onError' | 'onSelect'> { - onSelect?: () => void; - onError?: (error: Error) => void; - tenantItem?: (tu: TenantUser) => ReactNode; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function TenantSelector({ - onSelect, - onError, - tenantItem, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const tenantUsers = useBridgeStore((s) => s.tenantUsers); - - const [loading, setLoading] = useState(false); - const [selectedId, setSelectedId] = useState(null); - const [error, setError] = useState(null); - - async function handleSelect(tenantUser: TenantUser) { - if (loading) return; - setError(null); - setSelectedId(tenantUser.id); - setLoading(true); - try { - await (getBridgeAuth() as any).selectTenant(tenantUser.id); - onSelect?.(); - } catch (err: any) { - setError(authErrorMessage(err, t, 'tenant.error.select')); - onError?.(err); - } finally { - setLoading(false); - setSelectedId(null); - } - } - - return ( - - {error && {error}} - -
- {tenantUsers.map((tu) => ( - - ))} -
-
- ); -} - -export default TenantSelector; diff --git a/bridge-react/src/components/sdk-auth/WorkspaceSelector.tsx b/bridge-react/src/components/sdk-auth/WorkspaceSelector.tsx deleted file mode 100644 index 4bdf531..0000000 --- a/bridge-react/src/components/sdk-auth/WorkspaceSelector.tsx +++ /dev/null @@ -1,137 +0,0 @@ -import type { MessageOverrides, Workspace } from '@nebulr-group/bridge-auth-core'; -import type { HTMLAttributes, ReactNode } from 'react'; -import { useEffect, useState } from 'react'; -import { getBridgeAuth, useBridgeStore } from '../../core/bridge-instance'; -import { Alert } from './shared/Alert'; -import { Spinner } from './shared/Spinner'; -import { getTranslator } from '../../i18n'; -import { authErrorMessage } from './shared/auth-error'; - -interface Props extends Omit, 'onError'> { - onSwitch?: () => void; - onError?: (error: Error) => void; - workspaceItem?: (ctx: { - workspace: Workspace; - isActive: boolean; - isLoading: boolean; - onSelect: () => void; - }) => ReactNode; - /** Per-key copy overrides for this component only (TBP-630). */ - messages?: MessageOverrides; -} - -export function WorkspaceSelector({ - onSwitch, - onError, - workspaceItem, - messages, - className, - style, - ...rest -}: Props) { - const t = getTranslator(messages); - const profile = useBridgeStore((s) => s.profile); - const currentWorkspaceId = profile?.id ?? null; - - const [workspaces, setWorkspaces] = useState([]); - const [loadError, setLoadError] = useState(null); - const [loadingList, setLoadingList] = useState(true); - const [switchingId, setSwitchingId] = useState(null); - const [switchError, setSwitchError] = useState(null); - - useEffect(() => { - let mounted = true; - (async () => { - try { - const ws = await (getBridgeAuth() as any).getWorkspaces(); - if (mounted) setWorkspaces(ws); - } catch (err: any) { - if (mounted) setLoadError(authErrorMessage(err, t, 'workspace.error.load')); - } finally { - if (mounted) setLoadingList(false); - } - })(); - return () => { - mounted = false; - }; - }, []); - - async function handleSelect(workspace: Workspace) { - if (switchingId) return; - setSwitchError(null); - setSwitchingId(workspace.id); - try { - await (getBridgeAuth() as any).switchWorkspace(workspace.id); - onSwitch?.(); - } catch (err: any) { - setSwitchError(authErrorMessage(err, t, 'workspace.error.switch')); - onError?.(err); - } finally { - setSwitchingId(null); - } - } - - return ( -
- {(loadError || switchError) && ( - {loadError ?? switchError} - )} - - {loadingList ? ( -
- -
- ) : ( -
- {workspaces.map((ws) => { - const isActive = ws.id === currentWorkspaceId; - const isLoading = switchingId === ws.id; - const onSelect = () => handleSelect(ws); - - if (workspaceItem) { - return ( -
- {workspaceItem({ workspace: ws, isActive, isLoading, onSelect })} -
- ); - } - - return ( - - ); - })} -
- )} -
- ); -} - -export default WorkspaceSelector; diff --git a/bridge-react/src/components/sdk-auth/shared/Alert.tsx b/bridge-react/src/components/sdk-auth/shared/Alert.tsx deleted file mode 100644 index 679f941..0000000 --- a/bridge-react/src/components/sdk-auth/shared/Alert.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import type { HTMLAttributes, ReactNode } from 'react'; - -interface AlertProps extends HTMLAttributes { - variant?: 'error' | 'info' | 'success'; - children?: ReactNode; -} - -export function Alert({ - variant = 'error', - children, - className, - style, - ...rest -}: AlertProps) { - if (!children) return null; - return ( -
- {children} -
- ); -} - -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 ( +
+ {typeof heading === 'string' ? heading !== '' &&

{heading}

: heading} + {typeof description === 'string' ? description !== '' &&

{description}

: description} + {children} +
+ ); +} + +export default AuthFormWrapper; diff --git a/bridge-react/src/components/shared/Link.tsx b/bridge-react/src/components/shared/Link.tsx new file mode 100644 index 0000000..0f58263 --- /dev/null +++ b/bridge-react/src/components/shared/Link.tsx @@ -0,0 +1,27 @@ +/** + * A link to a page of this app that goes through the app's router, so a + * click does not reload the page (with `storage: 'memory'`, a reload signs + * the person out of this tab). Modified clicks and other targets behave as + * plain links. + */ +import type { AnchorHTMLAttributes, MouseEvent } from 'react'; +import { useBridgeRouter } from '../../react/hooks.js'; + +export interface LinkProps extends AnchorHTMLAttributes { + readonly href: string; +} + +export function Link({ href, onClick, target, ...rest }: LinkProps) { + const router = useBridgeRouter(); + function click(event: MouseEvent) { + onClick?.(event); + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + if (target !== undefined && target !== '_self') return; + if (!href.startsWith('/') || href.startsWith('//')) return; + event.preventDefault(); + router.navigate(href); + } + return ; +} + +export default Link; diff --git a/bridge-react/src/components/shared/PasswordInput.tsx b/bridge-react/src/components/shared/PasswordInput.tsx new file mode 100644 index 0000000..2af5f68 --- /dev/null +++ b/bridge-react/src/components/shared/PasswordInput.tsx @@ -0,0 +1,34 @@ +/** A password field with a show/hide toggle. */ +import { useState, type InputHTMLAttributes } from 'react'; + +export interface PasswordInputProps extends Omit, 'type' | 'value' | 'onChange'> { + readonly value: string; + readonly onValue: (value: string) => void; + readonly showLabel: string; + readonly hideLabel: string; +} + +export function PasswordInput({ value, onValue, showLabel, hideLabel, ...rest }: PasswordInputProps) { + const [shown, setShown] = useState(false); + return ( +
+ onValue(event.target.value)} {...rest} /> + +
+ ); +} + +export default PasswordInput; diff --git a/bridge-react/src/components/shared/Spinner.tsx b/bridge-react/src/components/shared/Spinner.tsx new file mode 100644 index 0000000..f1954e0 --- /dev/null +++ b/bridge-react/src/components/shared/Spinner.tsx @@ -0,0 +1,11 @@ +import type { HTMLAttributes } from 'react'; + +export interface SpinnerProps extends HTMLAttributes { + readonly size?: number; +} + +export function Spinner({ size = 24, style, ...rest }: SpinnerProps) { + return ; +} + +export default Spinner; diff --git a/bridge-react/src/components/subscription/BillingPortalButton.tsx b/bridge-react/src/components/subscription/BillingPortalButton.tsx deleted file mode 100644 index d5b4ba5..0000000 --- a/bridge-react/src/components/subscription/BillingPortalButton.tsx +++ /dev/null @@ -1,64 +0,0 @@ -/** - * TBP-743 (port of bridge-svelte TBP-702) — the "Manage billing" button: opens - * the workspace's Stripe billing portal (payment method, invoices, cancel). - * - * Fetches a one-time portal URL at click time (the session is short-lived, so - * it is never cached) and follows it. Renders only for someone who can act on - * it: the workspace owner (`canManageBilling()`), on an app with payments on, - * whose workspace already has a plan. - */ -import { useState, type ButtonHTMLAttributes } from 'react'; -import { getBridgeAuth, useBridgeStore } from '../../core/bridge-instance'; -import { Alert } from './shared/Alert'; - -export interface BillingPortalButtonProps extends Omit, 'onClick'> { - /** The button text. @default 'Manage billing' */ - label?: string; -} - -export function BillingPortalButton({ label = 'Manage billing', className = '', ...rest }: BillingPortalButtonProps) { - const status = useBridgeStore((s) => s.subscription.status); - const signedIn = useBridgeStore((s) => !!s.tokens?.accessToken); - const [opening, setOpening] = useState(false); - const [failure, setFailure] = useState(null); - - let canManage = false; - if (signedIn && status) { - try { - canManage = getBridgeAuth().canManageBilling(); - } catch { - canManage = false; - } - } - const visible = canManage && !!status?.paymentsEnabled && !status?.shouldSelectPlan; - if (!visible) return null; - - async function openPortal() { - setOpening(true); - setFailure(null); - try { - window.location.href = await getBridgeAuth().getBillingPortalUrl(); - } catch (err) { - setFailure(err instanceof Error ? err.message : 'Could not open the billing portal'); - setOpening(false); - } - } - - return ( - <> - {failure ? {failure} : null} - - - ); -} - -export default BillingPortalButton; diff --git a/bridge-react/src/components/subscription/BridgeBillingNotice.tsx b/bridge-react/src/components/subscription/BridgeBillingNotice.tsx deleted file mode 100644 index 14746bb..0000000 --- a/bridge-react/src/components/subscription/BridgeBillingNotice.tsx +++ /dev/null @@ -1,264 +0,0 @@ -/** - * Billing 2.0 / Phase B / US-5 → US-9 — ported from bridge-svelte's - * `BridgeBillingNotice.svelte` (via bridge-nextjs). - * - * Unified billing-notice component. Renders the workspace's current billing - * notice based on auth-core's `useBridge().subscription`. Multi-state from the - * start: past_due, cancellation, trial, dunning, locked. New states slot in via - * the notice-state → content map without restructuring. - * - * Audience: reads the existing auth context to render admin (CTA) vs member - * (no CTA) variants. Per the locked decision, role lives where it lives today — - * NOT on `useBridge().subscription`. - * - * Not dismissible — stays until status flips back to active. - * - * Reactive translation (§5.1): svelte `$state(snapshot())` + `onMount(subscribe)` - * → `useBridgeSnapshot`; `$derived(...)` → `useMemo`; `{#if}/{:else}` → JSX; - * `onclick` → `onClick`. - */ -import { useEffect, useMemo, useState } from 'react'; -import { - deriveNoticeState, - deriveSeverity, - useBridge, - type BillingNoticeState, - type BillingSubscriptionState, -} from '@nebulr-group/bridge-auth-core'; -import { getBridgeAuth } from '../../core/bridge-instance'; -import { billingRoutes } from '../../core/billing-routes'; -import { ensureBillingState } from '../../core/billing-state'; -import { useBridgeSnapshot } from '../../hooks/use-bridge-readable'; - -type Chassis = 'bar' | 'rail' | 'card'; - -export interface BridgeBillingNoticeProps { - /** Visual chassis variant. */ - chassis?: Chassis; - /** - * Gate behavior. `soft` (default) always renders the inline banner. `hard` - * renders a full-screen blocking lockscreen when the workspace is locked - * (gate engaged); non-locked states still render as the inline banner. - */ - mode?: 'soft' | 'hard'; - /** Optional class applied to the root element. */ - className?: string; - /** Override the default CTA click handler (links to billing surface). */ - onActionClick?: (state: BillingNoticeState) => void; - /** - * CTA destination for this instance. Overrides `billing.manageRoute` - * config; `onActionClick` takes precedence over both. - */ - actionHref?: string; -} - -export function BridgeBillingNotice({ - chassis = 'rail', - mode = 'soft', - className = '', - onActionClick, - actionHref, -}: BridgeBillingNoticeProps) { - const subscription = useBridge().subscription; - - const snapshot = useBridgeSnapshot( - (onChange) => subscription.subscribe(() => onChange()), - () => subscription.snapshot(), - ); - - // Admin/member variant. v1 policy: workspace owner only, via - // canManageBilling() (immutable OWNER role key). Defaults to non-admin if - // unavailable. - const [isBillingAdmin, setIsBillingAdmin] = useState(false); - - useEffect(() => { - const ctx = getBridgeAuth().getApiContext(); - if (ctx.accessToken) { - setIsBillingAdmin(getBridgeAuth().canManageBilling()); - } - if (!ctx.accessToken) { - subscription.setError('Not authenticated'); - return; - } - // TBP-762 — through the billing store: renews an out-of-date sign-in, - // retries once, and re-reads on the store's refresh rule. - void ensureBillingState(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - const noticeState = useMemo( - () => deriveNoticeState(snapshot.state), - [snapshot.state], - ); - const severity = useMemo(() => deriveSeverity(noticeState), [noticeState]); - const visible = snapshot.state !== null && noticeState !== 'active'; - const asLockscreen = mode === 'hard' && severity === 'locked'; - - const copy = useMemo( - () => getCopy(noticeState, isBillingAdmin, snapshot.state), - [noticeState, isBillingAdmin, snapshot.state], - ); - - function handleAction(): void { - if (onActionClick) { - onActionClick(noticeState); - return; - } - // Default: open the app's billing surface. 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) return null; - - if (asLockscreen) { - return ( -
-
- {copy.title} - {copy.body} - {copy.cta && isBillingAdmin && ( - - )} -
-
- ); - } - - const isAssertive = severity === 'critical' || severity === 'locked'; - return ( -
-
- {copy.title} - {copy.body} -
- {copy.cta && isBillingAdmin && ( - - )} -
- ); -} - -/** - * Copy map. US-5 ships past_due copy; later stories fill in trial/cancel/dunning - * variants. Member variant suppresses the CTA and softens the call-to-action. - * Pure function — ported verbatim from the svelte source. - */ -function getCopy( - state: BillingNoticeState, - admin: boolean, - snap: BillingSubscriptionState | null, -): { title: string; body: string; cta?: string } { - const cardLast4 = snap?.cardLast4; - const endsAt = snap?.endsAt; - const daysLeft = snap?.daysLeft; - const nextRetryAt = snap?.nextRetryAt; - - switch (state) { - case 'past_due': - return admin - ? { - title: 'Payment failed', - body: cardLast4 - ? `We couldn't charge your card ending in ${cardLast4}. Update your payment method to keep using ${snap?.plan.name ?? 'your plan'}.` - : `We couldn't charge your card. Update your payment method to keep using ${snap?.plan.name ?? 'your plan'}.`, - cta: 'Update card', - } - : { - title: "Your workspace's payment failed", - body: 'Please contact your workspace owner to update the payment method.', - }; - case 'past_due_trial': - return admin - ? { - title: 'Trial ended', - body: 'Add a payment method to keep using your workspace.', - cta: 'Add card', - } - : { - title: "Your workspace's trial has ended", - body: 'Please contact your workspace owner to add a payment method.', - }; - case 'trial_active': - return admin - ? { - title: 'Trial active', - body: daysLeft !== undefined ? `${daysLeft} days left in your trial.` : 'Trial in progress.', - } - : { - title: 'Trial active', - body: daysLeft !== undefined ? `${daysLeft} days left.` : 'Trial in progress.', - }; - case 'trial_ending_soon': - return admin - ? { - title: 'Trial ending soon', - body: daysLeft !== undefined ? `${daysLeft} days left. Add a payment method to keep your access.` : 'Add a payment method to keep your access.', - cta: 'Add card', - } - : { - title: 'Trial ending soon', - body: daysLeft !== undefined ? `${daysLeft} days left.` : 'Contact your workspace owner.', - }; - case 'cancel_at_period_end': - return admin - ? { - title: 'Subscription ending', - body: endsAt - ? `Your subscription ends ${new Date(endsAt).toLocaleDateString()}. You'll keep full access until then.` - : "Your subscription is ending. You'll keep access until the period ends.", - cta: 'Reactivate', - } - : { - title: 'Subscription ending', - body: endsAt ? `Your workspace's subscription ends ${new Date(endsAt).toLocaleDateString()}.` : "Your workspace's subscription is ending.", - }; - case 'canceled': - return admin - ? { title: 'Subscription canceled', body: 'Your subscription has ended. Choose a plan to continue.', cta: 'Choose plan' } - : { title: 'Subscription canceled', body: 'Please contact your workspace owner.' }; - case 'dunning_active': - return admin - ? { - title: 'Payment retry scheduled', - body: nextRetryAt - ? `We'll retry your payment on ${new Date(nextRetryAt).toLocaleDateString()}. Update your card to avoid interruption.` - : "We'll retry your payment soon. Update your card to avoid interruption.", - cta: 'Update card', - } - : { title: 'Payment retry scheduled', body: 'Please contact your workspace owner to update the payment method.' }; - case 'dunning_final_retry': - return admin - ? { - title: 'Final payment retry', - body: 'This is the last automatic retry. Update your card now to avoid losing access.', - cta: 'Update card', - } - : { title: 'Final payment retry', body: 'Please contact your workspace owner immediately.' }; - case 'dunning_exhausted': - return admin - ? { title: 'Access locked', body: 'Payment retries have exhausted. Update your card to restore access.', cta: 'Update card' } - : { title: 'Access locked', body: 'Please contact your workspace owner.' }; - default: - return { title: '', body: '' }; - } -} - -export default BridgeBillingNotice; diff --git a/bridge-react/src/components/subscription/BridgeBillingRoutes.tsx b/bridge-react/src/components/subscription/BridgeBillingRoutes.tsx deleted file mode 100644 index 5b86623..0000000 --- a/bridge-react/src/components/subscription/BridgeBillingRoutes.tsx +++ /dev/null @@ -1,191 +0,0 @@ -/** - * TBP-743 (port of bridge-svelte TBP-702) — the subscription page, the paywall - * and the checkout return pages, from one route. - * - * // React Router - * import { BridgeBillingRoutes } from '@nebulr-group/bridge-react/react-router'; - * } /> - * - * // TanStack Router - * import { BridgeBillingRoutes } from '@nebulr-group/bridge-react/tanstack-router'; - * createRoute({ getParentRoute: () => rootRoute, path: 'subscription/$', component: BridgeBillingRoutes }) - * - * Serves, relative to wherever it is mounted: - * /subscription the current plan, the plan picker and "Manage billing"; - * a completed checkout lands here, with a banner - * /subscription/plan the paywall: where a plan-less workspace is sent - * /subscription/success the old confirmation page, for `billing.successRoute` - * /subscription/error where a failed checkout confirmation lands - * - * Those are the defaults of `billing.manageRoute`, `billing.paywallRoute` and - * `billing.paymentErrorRoute`, so nothing Bridge redirects to is a 404. - * - * Customising, in rungs: - * 1. `--bridge-*` CSS tokens restyle it. - * 2. `frame(page, children)` replaces everything around the content on every - * page; `heading(page)` replaces each page's heading. - * 3. Take over one page by passing an element: - * }} /> - * 4. Headless: `PlanSelector`, `BridgeSubscriptionStatus`, - * `BillingPortalButton` and `useSubscription()` are the pieces. - * - * TBP-945 (port of bridge-svelte TBP-813) — a paid checkout and a Free pick - * land on `billing.successRoute`, by default this route's own subscription - * page, which shows ``. Set `billing.successRoute` to - * land anywhere else. - */ -import { useEffect, type ReactNode } from 'react'; -import { ensureSubscription, loadSubscription } from '../../core/bridge-instance'; -import { clearCheckoutResult } from '../../core/checkout-result'; -import { parseBridgeBillingRoute, type BridgeBillingPage } from '../../core/billing-routes'; -import { bridgeAuthBase } from '../../core/auth-routes'; -import { useWindowRouteLocation, type BridgeRouteLocation } from '../../routing/location'; -import { billingRoutes } from '../../core/billing-routes'; -import { PlanSelector } from './PlanSelector'; -import { BridgeSubscriptionStatus } from './BridgeSubscriptionStatus'; -import { BillingPortalButton } from './BillingPortalButton'; -import { BridgeCheckoutNotice } from './BridgeCheckoutNotice'; -import { subscriptionMeta } from './plan-format'; -import { useBillingSnapshot } from './use-billing-snapshot'; - -export type { BridgeBillingPage }; - -export interface BridgeBillingRoutesProps { - /** Everything around the content, on every page. Replaces the default centred column. */ - frame?: (page: BridgeBillingPage, children: ReactNode) => ReactNode; - /** Each page's heading. Replaces the default one. */ - heading?: (page: BridgeBillingPage) => ReactNode; - /** Take over a page by passing an element; every other page keeps working. */ - pages?: Partial>; - /** Rendered for an address under the mount point that names no page. */ - notFound?: ReactNode; - /** Where "Continue" on the success page goes. @default '/' */ - redirectTo?: string; - /** The "you're on Pro now" banner on the subscription page after a - * checkout. `false` hides it. @default true */ - checkoutNotice?: boolean; - /** The mount point when no router adapter supplies the location. @default billing.manageRoute */ - base?: string; - /** The current location, from a router adapter. */ - location?: BridgeRouteLocation; -} - -const DEFAULT_HEADINGS: Record = { - manage: 'Subscription', - plan: 'Choose a plan', - success: "You're all set", - error: "We couldn't confirm your payment", -}; - -export function BridgeBillingRoutes(props: BridgeBillingRoutesProps) { - const windowLocation = useWindowRouteLocation(props.base ?? billingRoutes().manageRoute); - return ; -} - -function BillingRoutesBody({ - frame, - heading, - pages, - notFound, - redirectTo = '/', - checkoutNotice = true, - location, -}: BridgeBillingRoutesProps & { location: BridgeRouteLocation }) { - const rest = location.rest; - const route = parseBridgeBillingRoute(rest); - // Links are relative to where the route is mounted, not hard-coded to /subscription. - const base = bridgeAuthBase(location.pathname, rest) || '/'; - const at = (sub: string) => (base === '/' ? `/${sub}` : `${base}/${sub}`); - const page = route?.page; - // TBP-945 — a checkout lands on `billing.successRoute`; by default on this - // route's own subscription page, wherever it is mounted. - const routes = billingRoutes(); - const successTarget = routes.successIsDefault ? base : routes.successRoute; - // The current plan's renewal date and card, for the line under its name. - const meta = subscriptionMeta(useBillingSnapshot()?.state); - - // Every page reads the subscription, reusing a read younger than 30 s. The - // success page always re-reads: the checkout just changed it. - useEffect(() => { - if (!page) return; - void (page === 'success' ? loadSubscription() : ensureSubscription()); - // The old confirmation page says it all; no banner on the next page too. - if (page === 'success') clearCheckoutResult(); - }, [page]); - - if (!route || !page) { - if (rest === null) return null; - return ( -
- {notFound ??

Page not found.

} -
- ); - } - - if (pages && pages[page] !== undefined) { - return ( -
- {pages[page]} -
- ); - } - - const content = ( - <> - {page === 'manage' && checkoutNotice ? : null} - {heading ? heading(page) :

{DEFAULT_HEADINGS[page]}

} - {page === 'manage' ? ( - <> -

Your plan, what it includes, and billing.

-
-
- Current plan - - {meta ? ( - - {meta} - - ) : null} -
- -
- - - ) : page === 'plan' ? ( - <> -

Pick a plan to start using the app.

- - - ) : page === 'success' ? ( - <> -

Your plan is active.

-
- Current plan - -
-
- Continue - - - ) : ( - <> -

- 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(page, content) :
{content}
} -
- ); -} - -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 ? ( -
- - onClose()} - > - Upgrade plan - -
- ) : ( -
- -
- ); - - const included = - includedIn.length > 0 ? ( -

- Included in: {includedIn.join(', ')} -

- ) : null; - - return ( - { - if (isOpen) onClose(); - }} - > - {featureVariant ? ( -
-

- This feature isn't on your plan -

-

- {canUpgrade ? 'Upgrade the plan to use it.' : 'Ask the workspace owner to upgrade the plan to use it.'} -

- {included} - {actions} -
- ) : refusal ? ( -
-

- You've reached your plan's limit -

-

- {!canUpgrade ? ( - quotaMemberBody(refusal.metric, 'over') - ) : hasNumbers ? ( - <> - This workspace has used {refusal.used?.toLocaleString()} of{' '} - {refusal.limit?.toLocaleString()}{' '} - {refusal.metric} on its current plan. - - ) : ( - <> - This workspace has reached its {refusal.metric}{' '} - limit. - - )} - {canUpgrade ? ' Upgrade the plan to keep going.' : null} -

- {included} - {actions} -
- ) : null} -
- ); -} - -export default BridgeUpgradeDialog; diff --git a/bridge-react/src/components/subscription/BridgeUpgradeMount.tsx b/bridge-react/src/components/subscription/BridgeUpgradeMount.tsx deleted file mode 100644 index 6b43280..0000000 --- a/bridge-react/src/components/subscription/BridgeUpgradeMount.tsx +++ /dev/null @@ -1,56 +0,0 @@ -/** - * TBP-743 — what `` renders for the upgrade dialog: it reads - * the pending plan-limit refusal and feature upgrade, and mounts the built-in - * ``, the app's own (`billing.upgradeDialog: MyDialog`), - * or nothing (`billing.upgradeDialog: false`). A plan-limit refusal wins when - * both are pending. - */ -import { useEffect, useSyncExternalStore } from 'react'; -import { getBridgeConfig, loadSubscription, useBridgeStore } from '../../core/bridge-instance'; -import { dismissQuotaRefusal, getQuotaRefusal, subscribeQuotaRefusal } from '../../core/quota-refusal'; -import { dismissFeatureUpgrade, getFeatureUpgrade, subscribeFeatureUpgrade } from '../../core/feature-upgrade'; -import { resolveUpgradeDialog, upgradeHrefFor } from '../../core/upgrade-dialog'; -import { isBillingAdmin } from '../../core/billing-role'; -import { BridgeUpgradeDialog } from './BridgeUpgradeDialog'; - -function close(): void { - dismissQuotaRefusal(); - dismissFeatureUpgrade(); -} - -export function BridgeUpgradeMount() { - const refusal = useSyncExternalStore(subscribeQuotaRefusal, getQuotaRefusal, getQuotaRefusal); - const upgrade = useSyncExternalStore(subscribeFeatureUpgrade, getFeatureUpgrade, getFeatureUpgrade); - const subscription = useBridgeStore((s) => s.subscription); - const signedIn = useBridgeStore((s) => !!s.tokens?.accessToken); - - // The feature variant names the plans that include the feature, from the - // plan list. Load it once when that variant opens. - useEffect(() => { - if (!upgrade || !signedIn) return; - const { plans, loading, error } = subscription; - if (!plans && !loading && !error) void loadSubscription(); - }, [upgrade, signedIn, subscription]); - - const billing = getBridgeConfig()?.billing; - const Dialog = resolveUpgradeDialog(billing); - if (!Dialog) return null; - const Component = Dialog === 'default' ? BridgeUpgradeDialog : Dialog; - - const open = !!refusal || !!upgrade; - const feature = refusal ? null : upgrade ? (upgrade.feature ?? upgrade.flag ?? '') : null; - - return ( - . - canUpgrade={open ? isBillingAdmin() : false} - onClose={close} - feature={feature} - plans={subscription.plans} - /> - ); -} - -export default BridgeUpgradeMount; diff --git a/bridge-react/src/components/subscription/Entitled.tsx b/bridge-react/src/components/subscription/Entitled.tsx deleted file mode 100644 index 9aeff82..0000000 --- a/bridge-react/src/components/subscription/Entitled.tsx +++ /dev/null @@ -1,43 +0,0 @@ -/** - * TBP-743 (port of bridge-svelte TBP-703) — ``: the - * children render when the workspace's plan grants the entitlement, `fallback` - * when it does not. - * - * Upgrade for analytics}> - * - * - * - * Until Bridge has answered it renders neither — only the optional `loading` - * node — so a cold start never flashes the upgrade prompt at a paying - * workspace, nor the paid feature at a free one. - * - * The markup form of `useEntitlements().can('analytics')`. It reads the plan - * directly, which is the exception: the standard gate is `` with a - * flag ruled `bridge:billing.entitlement. eq true`. In development it logs - * a one-time note saying so. - */ -import type { ReactNode } from 'react'; -import { useEntitlements } from '../../hooks/use-entitlements'; -import { noteDirectPlanCheck } from '../../core/direct-plan-check-note'; - -export interface EntitledProps { - /** The entitlement key, e.g. `'analytics'`. */ - to: string; - /** Rendered when the plan grants `to`. */ - children?: ReactNode; - /** Rendered when Bridge has answered and the plan does not grant `to`. */ - fallback?: ReactNode; - /** Rendered until Bridge has answered. Nothing by default. */ - loading?: ReactNode; -} - -export function Entitled({ to, children, fallback = null, loading = null }: EntitledProps) { - // Before the hook's `can()`, so this note — naming — is the one - // a page using the component sees. Once per page load. - noteDirectPlanCheck('entitled', to); - const entitlements = useEntitlements(); - if (!entitlements.ready) return <>{loading}; - return <>{entitlements.can(to) ? children : fallback}; -} - -export default Entitled; diff --git a/bridge-react/src/components/subscription/PlanSelector.tsx b/bridge-react/src/components/subscription/PlanSelector.tsx deleted file mode 100644 index aa6b4c2..0000000 --- a/bridge-react/src/components/subscription/PlanSelector.tsx +++ /dev/null @@ -1,506 +0,0 @@ -/** - * The plan picker. React port of bridge-svelte's `PlanSelector.svelte` - * (TBP-743 brings it to parity): billing-interval tabs, cheapest plan first, - * each plan's features, a confirm step before an instant plan switch, a retry - * when the plan list is empty, and the Stripe checkout / free pick flow of - * `plan-pick.ts`. - * - * Customising a card (TBP-515 S2), cheapest first: - * - `planDescription({ plan, isCurrent })` replaces the description paragraph; - * - `planFooter({ plan, isCurrent })` renders at the bottom of the card; - * - `planCard({ plan, prices, isCurrent, interval, onPick })` replaces the - * whole card. - * - * TBP-945 (port of bridge-svelte TBP-813): the default card sits on a surface - * (`--bridge-card-bg`, `--bridge-card-shadow`) with a large formatted price, - * buttons that say "Choose / Upgrade to / Switch to", and the current plan - * marked in the primary colour. `heading` puts a title beside the - * Monthly/Yearly switch. A pick that changes the plan here records it, so the - * landing page shows ``. - */ -import type { Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core'; -import type { HTMLAttributes, ReactNode } from 'react'; -import { useEffect, useMemo, useRef, useState } from 'react'; -import { - ensureSubscription, - getBridgeAuth, - getBridgeConfig, - loadSubscription, - useBridgeStore, -} from '../../core/bridge-instance'; -import { refreshBilling } from '../../core/billing-refresh'; -import { getRouterAdapter } from '../../utils/router-adapter'; -import { pickPlan } from './plan-pick'; -import { formatAmount, intervalSuffix, minAmount, pickKind, pickLabel } from './plan-format'; -import { markCheckoutComplete } from '../../core/checkout-result'; -import { Alert } from './shared/Alert'; -import { Spinner } from './shared/Spinner'; - -type BillingInterval = PriceOfferSdk['recurrenceInterval']; - -type UiState = 'idle' | 'payment-failed' | 'setup-payments' | 'select-plan' | 'active' | 'trial'; - -export interface PlanCardContext { - plan: Plan; - /** The plan's full price list. */ - prices: PriceOfferSdk[]; - isCurrent: boolean; - /** The active interval tab. */ - interval: BillingInterval; - onPick: (price: PriceOfferSdk) => void; -} - -export interface PlanSelectorProps extends Omit, 'onSelect'> { - /** A heading above the plans, beside the Monthly/Yearly switch (TBP-945). */ - heading?: string; - /** Where to send the user after a successful pick or checkout. @default '/subscription' */ - successRedirect?: string; - /** Where to send the user after a cancelled Stripe checkout. @default '/subscription' */ - cancelRedirect?: string; - /** - * Which billing interval tab is selected by default. Falls back to the first - * available interval when no plan offers the requested one. - * @default 'year' - */ - defaultInterval?: BillingInterval; - /** - * Called after a free-plan or direct plan change (not the Stripe redirect - * path). When given, the picker stays put instead of going to - * `successRedirect` — the page took over. - */ - onSelect?: (detail: { plan: Plan; price: PriceOfferSdk }) => void; - /** Replaces the whole default card. */ - planCard?: (ctx: PlanCardContext) => ReactNode; - /** Replaces the default card's description paragraph. */ - planDescription?: (ctx: { plan: Plan; isCurrent: boolean }) => ReactNode; - /** Rendered at the bottom of the default card, after the price buttons. */ - planFooter?: (ctx: { plan: Plan; isCurrent: boolean }) => ReactNode; - emptyState?: ReactNode; - loadingState?: ReactNode; -} - -const INTERVAL_LABELS: Record = { - day: 'Daily', - week: 'Weekly', - month: 'Monthly', - year: 'Yearly', -}; - -const INTERVAL_ORDER: BillingInterval[] = ['day', 'week', 'month', 'year']; - -// The features the plan includes — the same list the upgrade dialog reads. -// Structural: an older auth-core `Plan` type has no `features`. -function planFeatures(plan: Plan): ReadonlyArray<{ key: string; name: string }> { - return (plan as Plan & { features?: ReadonlyArray<{ key: string; name: string }> }).features ?? []; -} - -function formatPrice(price: PriceOfferSdk): string { - return price.amount === 0 - ? 'Free' - : `${formatAmount(price.amount, price.currency)} ${intervalSuffix(price)}`; -} - -const FREE_PLACEHOLDER_PRICE = { id: '', amount: 0, currency: 'usd', recurrenceInterval: 'month' } as PriceOfferSdk; - -function CheckIcon() { - return ( - - ); -} - -export function PlanSelector({ - heading, - successRedirect = '/subscription', - cancelRedirect = '/subscription', - defaultInterval = 'year', - onSelect, - planCard, - planDescription, - planFooter, - emptyState, - loadingState, - className, - style, - ...rest -}: PlanSelectorProps) { - const subscription = useBridgeStore((s) => s.subscription); - const { status, plans, loading, error: storeError } = subscription; - - const [picking, setPicking] = useState(false); - const [pickError, setPickError] = useState(null); - const [intervalOverride, setIntervalOverride] = useState(null); - const [retrying, setRetrying] = useState(false); - const [confirmTarget, setConfirmTarget] = useState<{ plan: Plan; price: PriceOfferSdk } | null>(null); - const [confirmBusy, setConfirmBusy] = useState(false); - const [confirmError, setConfirmError] = useState(null); - const [successNotice, setSuccessNotice] = useState(null); - const successTimer = useRef | undefined>(undefined); - - useEffect(() => { - // Read unless the store holds a read younger than 30 s. - void ensureSubscription(); - return () => clearTimeout(successTimer.current); - }, []); - - const uiState: UiState = useMemo(() => { - if (!status) return 'idle'; - if (status.paymentFailed) return 'payment-failed'; - if (status.shouldSetupPayments) return 'setup-payments'; - if (status.shouldSelectPlan) return 'select-plan'; - if (status.trial) return 'trial'; - if (status.paymentsEnabled || status.plan) return 'active'; - return 'select-plan'; - }, [status]); - - // `status.plan` is a Plan object from the REST endpoint; a string from JWT-derived paths. - const planField = status?.plan as unknown as { key: string } | string | undefined; - const currentPlanKey = typeof planField === 'string' ? planField : (planField?.key ?? null); - - // Distinct billing intervals offered by any *paid* price, in display order. - const availableIntervals = useMemo( - () => - INTERVAL_ORDER.filter((i) => - (plans ?? []).some((plan) => plan.prices.some((p) => p.amount > 0 && p.recurrenceInterval === i)), - ), - [plans], - ); - const showIntervalTabs = availableIntervals.length >= 2; - const selectedInterval: BillingInterval = - intervalOverride && availableIntervals.includes(intervalOverride) - ? intervalOverride - : availableIntervals.includes(defaultInterval) - ? defaultInterval - : (availableIntervals[0] ?? defaultInterval); - - // Prices to show under the active tab — at most one per interval: the active - // interval's price, else a free price from any interval so a free plan stays - // selectable under every tab. - function pricesForInterval(plan: Plan): PriceOfferSdk[] { - const exact = plan.prices.filter((p) => p.recurrenceInterval === selectedInterval); - if (exact.length > 0) return exact; - const free = plan.prices.find((p) => p.amount === 0); - return free ? [free] : []; - } - - // Cheapest first, by each plan's cheapest price across ALL intervals, so the - // order stays put when the user toggles Monthly/Yearly. - const sortedPlans = useMemo(() => [...(plans ?? [])].sort((a, b) => minAmount(a) - minAmount(b)), [plans]); - - const currentPlan = (plans ?? []).find((p) => p.key === currentPlanKey) ?? null; - const currentPlanName = currentPlan?.name ?? currentPlanKey ?? 'your current plan'; - - function showSuccess(message: string): void { - setSuccessNotice(message); - clearTimeout(successTimer.current); - successTimer.current = setTimeout(() => setSuccessNotice(null), 6000); - } - - async function retryPlans(): Promise { - setRetrying(true); - try { - await loadSubscription(); - } finally { - setRetrying(false); - } - } - - async function confirmPlanChange(): Promise { - if (!confirmTarget) return; - const { plan, price } = confirmTarget; - setConfirmBusy(true); - setConfirmError(null); - try { - await getBridgeAuth().changePlan(plan.key, price); - await refreshBilling(); - setConfirmTarget(null); - showSuccess(`You're now on ${plan.name} (${formatPrice(price)}).`); - onSelect?.({ plan, price }); - } catch (err) { - setConfirmError(err instanceof Error ? err.message : 'Plan change failed'); - } finally { - setConfirmBusy(false); - } - } - - async function handlePick(plan: Plan, price: PriceOfferSdk): Promise { - setPicking(true); - setPickError(null); - try { - const callbackBase = - getBridgeConfig()?.callbackUrl ?? `${window.location.origin}/auth/oauth-callback`; - const outcome = await pickPlan( - plan, - price, - { paymentsEnabled: !!status?.paymentsEnabled, successRedirect, cancelRedirect, callbackBase, onSelect }, - { - auth: getBridgeAuth() as unknown as Parameters[3]['auth'], - refresh: refreshBilling, - navigate: (url) => getRouterAdapter().navigate(url), - leave: (url) => { - window.location.href = url; - }, - complete: (picked) => markCheckoutComplete({ kind: 'plan', planName: picked.name }), - }, - ); - if (outcome === 'confirm') { - // Already has a payment method — an instant switch, so ask first. - setConfirmTarget({ plan, price }); - setConfirmError(null); - } - } catch (err) { - setPickError(err instanceof Error ? err.message : 'Something went wrong'); - } finally { - setPicking(false); - } - } - - async function goToPortal(): Promise { - try { - await getBridgeAuth().redirectToPlanSelection(); - } catch (err) { - setPickError(err instanceof Error ? err.message : 'Failed to open billing portal'); - } - } - - function defaultCard(plan: Plan, isCurrent: boolean, onPick: (price: PriceOfferSdk) => void): ReactNode { - const visiblePrices = pricesForInterval(plan); - const features = planFeatures(plan); - const kind = pickKind(plan, currentPlan); - const label = pickLabel(kind, plan); - const buttonClass = `${kind === 'current' || kind === 'switch' ? 'bridge-btn-secondary' : 'bridge-btn-primary'} bridge-plan-select-btn`; - const shownPrice = visiblePrices[0]; - return ( -
- {isCurrent ? ( - - Your plan - - ) : null} -
-

{plan.name}

- {plan.trial && (plan.trialDays ?? 0) > 0 ? ( - {plan.trialDays}-day trial - ) : null} -
- - {shownPrice ? ( -
- {formatAmount(shownPrice.amount, shownPrice.currency)} - {intervalSuffix(shownPrice)} -
- ) : null} - - {planDescription ? ( - planDescription({ plan, isCurrent }) - ) : plan.description ? ( -

{plan.description}

- ) : null} - - {features.length > 0 ? ( -
    - {features.map((feature) => ( -
  • - - {feature.name} -
  • - ))} -
- ) : null} - -
- {visiblePrices.map((price) => ( - - ))} - - {plan.prices.length === 0 ? ( - - ) : visiblePrices.length === 0 ? ( -

- Not available {INTERVAL_LABELS[selectedInterval].toLowerCase()} -

- ) : null} -
- - {planFooter ? planFooter({ plan, isCurrent }) : null} -
- ); - } - - const intervalTabs = ( -
- {availableIntervals.map((interval) => ( - - ))} -
- ); - - return ( -
- {loading ? ( - (loadingState ?? ( -
- -
- )) - ) : storeError ? ( - {storeError} - ) : ( - <> - {pickError ? {pickError} : null} - - {successNotice ? ( -
- {successNotice} -
- ) : null} - - {uiState === 'payment-failed' ? ( -
- Your last payment failed. Please update your payment method to continue. - -
- ) : null} - - {plans && plans.length === 0 ? ( - (emptyState ?? ( -
-

The plans could not be loaded.

- -
- )) - ) : plans ? ( - <> - {heading ? ( -
-

{heading}

- {showIntervalTabs ? intervalTabs : null} -
- ) : showIntervalTabs ? ( - intervalTabs - ) : null} - -
- {sortedPlans.map((plan) => { - const isCurrent = plan.key === currentPlanKey; - const onPick = (price: PriceOfferSdk) => void handlePick(plan, price); - if (planCard) { - return ( -
- {planCard({ plan, prices: plan.prices, isCurrent, interval: selectedInterval, onPick })} -
- ); - } - return defaultCard(plan, isCurrent, onPick); - })} -
- - ) : null} - - )} - - {confirmTarget ? ( -
-
-

- Change plan? -

-

- Switch from {currentPlanName} to {confirmTarget.plan.name} ( - {formatPrice(confirmTarget.price)}). -

-

- The change takes effect immediately. Any price difference is prorated on your next invoice. -

- {confirmError ? {confirmError} : null} -
- - -
-
-
- ) : null} -
- ); -} - -export default PlanSelector; diff --git a/bridge-react/src/components/subscription/QuotaGate.tsx b/bridge-react/src/components/subscription/QuotaGate.tsx deleted file mode 100644 index 2f6000b..0000000 --- a/bridge-react/src/components/subscription/QuotaGate.tsx +++ /dev/null @@ -1,86 +0,0 @@ -/** - * TBP-743 (port of bridge-svelte TBP-703) — `` - * (level 1): the action inside is disabled once the workspace is at its plan's - * hard cap, and an upgrade prompt shows beside it. - * - * - * - * - * - * <>{q.used} of {q.limit} used. Upgrade}> - * … - * - * - * Disabling is done by a `
` around the children, so every - * button, input, select and textarea inside is disabled natively and announced - * as such — no prop threading into your markup. (Links are not form controls; - * put a link's action behind a button.) - * - * Never disables on "don't know yet": while the quota is loading, the plan has - * no quota on the metric, or the quota is metered (it bills overage instead of - * blocking), the children are enabled. Only a known hard cap with nothing left - * disables them. - * - * Decoration only. The backend's @RequireQuota is what refuses the write. - */ -import type { ReactNode } from 'react'; -import { useQuota, type QuotaState } from '../../hooks/use-quota'; -import { billingRoutes } from '../../core/billing-routes'; - -export interface QuotaGateProps { - /** The quota metric key, e.g. `'tickets'`. */ - metric: string; - /** The action(s) to disable at the cap. */ - children: ReactNode; - /** What to show at the cap, instead of the default "limit reached — Upgrade" line. */ - atLimit?: (quota: QuotaState) => ReactNode; - /** Class on the wrapper. */ - className?: string; -} - -/** 'loading' | 'unlimited' | 'metered' | 'available' | 'at-limit' */ -export type QuotaGateState = 'loading' | 'unlimited' | 'metered' | 'available' | 'at-limit'; - -/** The gate's decision for a quota state. Exported for tests and custom gates. */ -export function quotaGateState(quota: QuotaState): QuotaGateState { - if (quota.loading) return 'loading'; - if (quota.unlimited) return 'unlimited'; - if (quota.snapshot?.policy === 'metered') return 'metered'; - const atCap = - (quota.remaining !== null && quota.remaining <= 0) || - (quota.used !== null && quota.limit !== null && quota.used >= quota.limit); - return atCap ? 'at-limit' : 'available'; -} - -export function QuotaGate({ metric, children, atLimit, className = '' }: QuotaGateProps) { - const quota = useQuota(metric); - const state = quotaGateState(quota); - const blocked = state === 'at-limit'; - - return ( -
-
- {children} -
- {blocked ? ( -
- {atLimit ? ( - atLimit(quota) - ) : ( - <> - You've used all {quota.limit?.toLocaleString()} {metric} on your plan.{' '} - Upgrade - - )} -
- ) : null} -
- ); -} - -export default QuotaGate; diff --git a/bridge-react/src/components/subscription/plan-format.ts b/bridge-react/src/components/subscription/plan-format.ts deleted file mode 100644 index 58d2802..0000000 --- a/bridge-react/src/components/subscription/plan-format.ts +++ /dev/null @@ -1,82 +0,0 @@ -// TBP-945 (port of bridge-svelte TBP-813) — how the plan cards and the -// current-plan panel word things, as pure functions. Prices are whole currency -// units (29 = 29 USD), as Bridge stores them. - -import type { BillingSubscriptionState, Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core'; - -/** `29` + `usd` → `$29`; `9.5` → `$9.50`. An unknown currency code falls back to `29 XYZ`. */ -export function formatAmount(amount: number, currency: string, locale?: string): string { - const code = currency.toUpperCase(); - try { - return new Intl.NumberFormat(locale, { - style: 'currency', - currency: code, - minimumFractionDigits: Number.isInteger(amount) ? 0 : 2, - maximumFractionDigits: 2, - }).format(amount); - } catch { - return `${amount} ${code}`; - } -} - -/** The cheapest price a plan has in any interval; plans with none sort last. */ -export function minAmount(plan: Plan): number { - const amounts = (plan.prices ?? []).map((p) => p.amount); - return amounts.length > 0 ? Math.min(...amounts) : Number.POSITIVE_INFINITY; -} - -/** What picking a plan does, relative to the current one. */ -export type PickKind = 'current' | 'choose' | 'upgrade' | 'switch'; - -export function pickKind(plan: Plan, current: Plan | null | undefined): PickKind { - if (current && current.key === plan.key) return 'current'; - if (!current) return 'choose'; - return minAmount(plan) > minAmount(current) ? 'upgrade' : 'switch'; -} - -/** The button text for a pick. */ -export function pickLabel(kind: PickKind, plan: Plan): string { - switch (kind) { - case 'current': - return 'Current plan'; - case 'upgrade': - return `Upgrade to ${plan.name}`; - case 'switch': - return `Switch to ${plan.name}`; - default: - return `Choose ${plan.name}`; - } -} - -/** `/ month`, after a price. */ -export function intervalSuffix(price: PriceOfferSdk): string { - return `/ ${price.recurrenceInterval}`; -} - -function formatDate(iso: string | undefined, locale?: string): string | null { - if (!iso) return null; - const d = new Date(iso); - if (Number.isNaN(d.getTime())) return null; - return d.toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }); -} - -/** - * The line under the current plan's name: renewal or end date, and the card on - * file. Only what the billing state actually carries; empty when it has none. - */ -export function subscriptionMeta(state: BillingSubscriptionState | null | undefined, locale?: string): string { - if (!state) return ''; - const parts: string[] = []; - const renews = formatDate(state.renewsAt, locale); - const ends = formatDate(state.endsAt, locale); - if (state.status === 'trial') { - if (ends) parts.push(`Trial ends ${ends}`); - else if (typeof state.daysLeft === 'number') parts.push(`${state.daysLeft} days left in trial`); - } else if (state.status === 'cancel_at_period_end' || state.status === 'canceled') { - if (ends) parts.push(`Ends ${ends}`); - } else if (renews) { - parts.push(`Renews ${renews}`); - } - if (state.cardLast4) parts.push(`Card ending ${state.cardLast4}`); - return parts.join(' · '); -} diff --git a/bridge-react/src/components/subscription/plan-pick.ts b/bridge-react/src/components/subscription/plan-pick.ts deleted file mode 100644 index 1b9f24e..0000000 --- a/bridge-react/src/components/subscription/plan-pick.ts +++ /dev/null @@ -1,99 +0,0 @@ -// What happens when someone picks a plan on . Ported verbatim -// from bridge-svelte (TBP-743); only `navigate` differs (the router adapter). -// -// TBP-762 — a Free pick (or a paid pick on an app without Stripe, which Bridge -// sets directly) used to re-read the subscription and then do nothing unless -// the page passed `onSelect`: the person was left on the plan picker, looking -// as if nothing had happened. It now goes on exactly like a paid pick does — -// to `successRedirect`, where a Stripe checkout returns — unless the page took -// over with `onSelect`. TBP-945 (bridge-svelte TBP-813): it also records the -// pick, so the landing page shows the same confirmation banner a checkout -// gets. Every pick that changed the plan re-reads the billing -// store (plan list, current plan, billing state) first, so the next page shows -// the new plan. - -import type { Plan, PriceOfferSdk } from '@nebulr-group/bridge-auth-core'; - -export interface PlanPickAuth { - selectFreePlan(planKey: string): Promise; - startCheckout( - planKey: string, - price: PriceOfferSdk, - urls: { successUrl: string; cancelUrl: string }, - ): Promise<{ sessionId: string | null; checkoutUrl?: string | null }>; -} - -export interface PlanPickOptions { - /** The workspace already pays: a switch is instant and needs a confirm step. */ - paymentsEnabled: boolean; - successRedirect: string; - cancelRedirect: string; - /** The OAuth callback URL Stripe returns to. */ - callbackBase: string; - onSelect?: (detail: { plan: Plan; price: PriceOfferSdk }) => void; -} - -export interface PlanPickDeps { - auth: PlanPickAuth; - /** Re-read the billing store. */ - refresh: () => Promise; - /** In-app navigation (the router adapter). */ - navigate: (url: string) => unknown; - /** Leave the app (Stripe checkout). */ - leave: (url: string) => void; - /** TBP-945 — record that the plan changed, for the landing page's banner. */ - complete?: (plan: Plan) => void; -} - -/** `selected`: the plan changed here. `confirm`: ask first. `checkout`: off to Stripe. */ -export type PlanPickOutcome = 'selected' | 'confirm' | 'checkout'; - -/** A $0 price on a plan with no metered cost is picked without checkout. */ -export function isFreePick(plan: Plan, price: PriceOfferSdk): boolean { - return price.amount === 0 && !(plan as Plan & { hasCost?: boolean }).hasCost; -} - -export async function pickPlan( - plan: Plan, - price: PriceOfferSdk, - opts: PlanPickOptions, - deps: PlanPickDeps, -): Promise { - if (isFreePick(plan, price)) { - // TBP-275: a $0-base plan with METERED pricing is not free — it goes - // through checkout below so a payment method is captured. - await deps.auth.selectFreePlan(plan.key); - await deps.refresh(); - await settle(plan, price, opts, deps); - return 'selected'; - } - if (opts.paymentsEnabled) return 'confirm'; - - // {CHECKOUT_SESSION_ID} is substituted by Stripe in place (no double `?`). - const successUrl = `${opts.callbackBase}?stripe_success=1&session_id={CHECKOUT_SESSION_ID}&redirect=${encodeURIComponent(opts.successRedirect)}`; - const cancelUrl = `${opts.callbackBase}?stripe_cancel=1&redirect=${encodeURIComponent(opts.cancelRedirect)}`; - const session = await deps.auth.startCheckout(plan.key, price, { successUrl, cancelUrl }); - if (session.sessionId === null) { - // Stripe not configured — Bridge set the plan directly. - await deps.refresh(); - await settle(plan, price, opts, deps); - return 'selected'; - } - if (!session.checkoutUrl) throw new Error('Checkout session URL missing'); - deps.leave(session.checkoutUrl); - return 'checkout'; -} - -async function settle( - plan: Plan, - price: PriceOfferSdk, - opts: PlanPickOptions, - deps: PlanPickDeps, -): Promise { - if (opts.onSelect) { - opts.onSelect({ plan, price }); - return; - } - deps.complete?.(plan); - await deps.navigate(opts.successRedirect); -} diff --git a/bridge-react/src/components/subscription/shared/Alert.tsx b/bridge-react/src/components/subscription/shared/Alert.tsx deleted file mode 100644 index 679f941..0000000 --- a/bridge-react/src/components/subscription/shared/Alert.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import type { HTMLAttributes, ReactNode } from 'react'; - -interface AlertProps extends HTMLAttributes { - variant?: 'error' | 'info' | 'success'; - children?: ReactNode; -} - -export function Alert({ - variant = 'error', - children, - className, - style, - ...rest -}: AlertProps) { - if (!children) return null; - return ( -
- {children} -
- ); -} - -export default Alert; diff --git a/bridge-react/src/components/subscription/shared/Spinner.tsx b/bridge-react/src/components/subscription/shared/Spinner.tsx deleted file mode 100644 index 7ce37fa..0000000 --- a/bridge-react/src/components/subscription/shared/Spinner.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import type { HTMLAttributes } from 'react'; - -export 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/subscription/use-billing-snapshot.ts b/bridge-react/src/components/subscription/use-billing-snapshot.ts deleted file mode 100644 index a8368ca..0000000 --- a/bridge-react/src/components/subscription/use-billing-snapshot.ts +++ /dev/null @@ -1,22 +0,0 @@ -// TBP-945 — the billing surface's snapshot (plan name, renewal date, card) for -// the subscription page's summary line and the checkout banner. Unlike -// , it never mounts the surface or throws: before -// Bridge is set up it is simply `null`, and the caller shows less. - -import { useEffect, useState } from 'react'; -import { useBridge, type BillingSubscriptionSnapshot } from '@nebulr-group/bridge-auth-core'; - -export function useBillingSnapshot(): BillingSubscriptionSnapshot | null { - const [snapshot, setSnapshot] = useState(null); - useEffect(() => { - try { - const sub = useBridge().subscription; - setSnapshot(sub.snapshot()); - return sub.subscribe((s) => setSnapshot(s)); - } catch { - /* Bridge not initialised */ - return undefined; - } - }, []); - return snapshot; -} diff --git a/bridge-react/src/components/team/ConfirmDialog.tsx b/bridge-react/src/components/team/ConfirmDialog.tsx new file mode 100644 index 0000000..d297029 --- /dev/null +++ b/bridge-react/src/components/team/ConfirmDialog.tsx @@ -0,0 +1,101 @@ +/** + * A yes-or-no dialog for a team action, such as removing a member. `detail` + * adds a line under the message (what else goes with it); `error` shows a + * refusal without closing the dialog. + */ +import { useEffect, useRef, type DialogHTMLAttributes, type ReactNode } from 'react'; +import { Alert } from '../shared/Alert.js'; + +/** What a custom `actions` render function gets. */ +export interface DialogActions { + readonly loading: boolean; + readonly onConfirm?: () => void; + readonly onCancel?: () => void; +} + +export interface ConfirmDialogProps extends Omit, 'open' | 'title' | 'onClose'> { + readonly open?: boolean; + /** The title: text for the dialog's heading (with `message` under it), or your own node, which replaces both. */ + readonly title?: ReactNode; + readonly message?: string; + readonly detail?: string | null; + readonly error?: string | null; + readonly confirmLabel?: string; + readonly variant?: 'danger' | 'default'; + readonly loading?: boolean; + readonly onConfirm?: () => void; + readonly onCancel?: () => void; + /** Replaces the Cancel and Confirm buttons. */ + readonly actions?: (actions: DialogActions) => ReactNode; +} + +export function ConfirmDialog({ + open = false, + title = 'Confirm', + message = 'Are you sure?', + detail = null, + error = null, + confirmLabel = 'Confirm', + variant = 'danger', + loading = false, + onConfirm, + onCancel, + actions, + ...rest +}: ConfirmDialogProps) { + const dialog = useRef(null); + + useEffect(() => { + const element = dialog.current; + if (!element || typeof element.showModal !== 'function') return; + if (open && !element.open) element.showModal(); + else if (!open && element.open) element.close(); + }, [open]); + + return ( + onCancel?.()} {...rest}> +
+ {typeof title !== 'string' ? ( + title + ) : ( + <> +

{title}

+

{message}

+ + )} + + {detail && ( +

+ {detail} +

+ )} + + {error && ( +
+ {error} +
+ )} + + {actions ? ( + actions({ loading, onConfirm, onCancel }) + ) : ( +
+ + +
+ )} +
+
+ ); +} + +export default ConfirmDialog; diff --git a/bridge-react/src/components/team/EditMemberDialog.tsx b/bridge-react/src/components/team/EditMemberDialog.tsx new file mode 100644 index 0000000..61e5c21 --- /dev/null +++ b/bridge-react/src/components/team/EditMemberDialog.tsx @@ -0,0 +1,147 @@ +/** + * Changes a member's role, or turns their access off and on. The roles listed + * are the ones the editor may give. Bridge decides; a refusal shows here. + */ +import type { Member, MemberUpdate, Role } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useMemo, useRef, useState, type DialogHTMLAttributes, type ReactNode } from 'react'; +import { getBridge } from '../../core/client.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import type { DialogActions } from './ConfirmDialog.js'; + +export interface EditMemberDialogProps extends Omit, 'open' | 'title' | 'onClose'> { + readonly open?: boolean; + readonly member?: Member | null; + readonly onClose?: () => void; + readonly onUpdated?: (member: Member) => void; + /** Replaces the title and subtitle. */ + readonly title?: ReactNode; + /** Replaces the Cancel and Save buttons. */ + readonly actions?: (actions: DialogActions) => ReactNode; +} + +// A member whose access is off reads as disabled or suspended. +const isOff = (m: Member) => m.status === 'disabled' || m.status === 'suspended'; + +export function EditMemberDialog({ open = false, member = null, onClose, onUpdated, title, actions, ...rest }: EditMemberDialogProps) { + const t = useTranslator(); + const dialog = useRef(null); + const [role, setRole] = useState(''); + const [enabled, setEnabled] = useState(true); + const [roles, setRoles] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + // Keep the member's current role selectable even when the editor may not give it. + const options = useMemo(() => { + const list = roles.map((r) => ({ key: r.key, name: r.name })); + const current = member?.role; + if (current && !list.some((r) => r.key === current)) list.unshift({ key: current, name: current }); + return list; + }, [roles, member]); + + useEffect(() => { + const element = dialog.current; + if (!element || typeof element.showModal !== 'function') return; + if (open && !element.open) { + reset(); + element.showModal(); + } else if (!open && element.open) { + element.close(); + } + }, [open]); + + function reset() { + setRole(member?.role ?? ''); + setEnabled(member ? !isOff(member) : true); + setRoles([]); + setError(null); + void loadRoles(); + } + + async function loadRoles() { + try { + setRoles(await getBridge().team.roles.list({ assignable: true })); + } catch (err) { + setError(errorMessage(err, t)); + } + } + + async function submit() { + if (!member) return; + const fields: MemberUpdate = { + ...(role && role !== member.role ? { role } : {}), + ...(enabled === isOff(member) ? { enabled } : {}), + }; + if (Object.keys(fields).length === 0) { + onClose?.(); + return; + } + setLoading(true); + setError(null); + try { + const updated = await getBridge().team.members.update(member.id, fields); + onUpdated?.(updated); + onClose?.(); + } catch (err) { + setError(errorMessage(err, t)); + } finally { + setLoading(false); + } + } + + return ( + onClose?.()} {...rest}> +
+ {title !== undefined ? ( + title + ) : ( + <> +

Edit Member

+ {member &&

{member.user.email}

} + + )} + + {error && ( +
+ {error} +
+ )} + +
+ + +
+ +
+ +
+ + {actions ? ( + actions({ loading, onConfirm: () => void submit(), onCancel: onClose }) + ) : ( +
+ + +
+ )} +
+
+ ); +} + +export default EditMemberDialog; diff --git a/bridge-react/src/components/team/InviteDialog.tsx b/bridge-react/src/components/team/InviteDialog.tsx new file mode 100644 index 0000000..f23b898 --- /dev/null +++ b/bridge-react/src/components/team/InviteDialog.tsx @@ -0,0 +1,152 @@ +/** + * Invites one person by email, with a role the inviter may give. Inviting an + * address that already has an invite sends a new one; the old link stops + * working. Bridge enforces any limit; a refusal shows its message here. + */ +import type { Invite, Role } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useRef, useState, type DialogHTMLAttributes, type ReactNode } from 'react'; +import { getBridge } from '../../core/client.js'; +import { errorMessage } from '../../core/i18n.js'; +import { useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import type { DialogActions } from './ConfirmDialog.js'; + +export interface InviteDialogProps extends Omit, 'open' | 'title' | 'onClose'> { + readonly open?: boolean; + readonly onClose?: () => void; + readonly onInvited?: (invite: Invite) => void; + /** Replaces the title and subtitle. */ + readonly title?: ReactNode; + /** Replaces the Cancel and Send buttons. */ + readonly actions?: (actions: DialogActions) => ReactNode; +} + +export function InviteDialog({ open = false, onClose, onInvited, title, actions, ...rest }: InviteDialogProps) { + const t = useTranslator(); + const dialog = useRef(null); + const [email, setEmail] = useState(''); + const [role, setRole] = useState(''); + const [roles, setRoles] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + const hasDefault = roles.some((r) => r.isDefault); + + useEffect(() => { + const element = dialog.current; + if (!element || typeof element.showModal !== 'function') return; + if (open && !element.open) { + reset(); + element.showModal(); + } else if (!open && element.open) { + element.close(); + } + }, [open]); + + function reset() { + setEmail(''); + setRole(''); + setRoles([]); + setError(null); + void loadRoles(); + } + + async function loadRoles() { + try { + const found = await getBridge().team.roles.list({ assignable: true }); + setRoles(found); + setRole(found.find((r) => r.isDefault)?.key ?? ''); + } catch (err) { + setError(errorMessage(err, t)); + } + } + + async function submit() { + const address = email.trim(); + if (address === '') { + setError('Please enter an email address.'); + return; + } + setLoading(true); + setError(null); + try { + const invite = await getBridge().team.invites.create(role ? { email: address, role } : { email: address }); + onInvited?.(invite); + onClose?.(); + } catch (err) { + setError(errorMessage(err, t)); + } finally { + setLoading(false); + } + } + + return ( + onClose?.()} {...rest}> +
+ {title !== undefined ? ( + title + ) : ( + <> +

Add Team Member

+

They get an email with a link to join.

+ + )} + + {error && ( +
+ {error} +
+ )} + +
{ + e.preventDefault(); + void submit(); + }} + > +
+ + setEmail(e.target.value)} + disabled={loading} + /> +
+ + {roles.length > 0 && ( +
+ + +
+ )} +
+ + {actions ? ( + actions({ loading, onConfirm: () => void submit(), onCancel: onClose }) + ) : ( +
+ + +
+ )} +
+
+ ); +} + +export default InviteDialog; diff --git a/bridge-react/src/components/team/InviteList.tsx b/bridge-react/src/components/team/InviteList.tsx new file mode 100644 index 0000000..f084aff --- /dev/null +++ b/bridge-react/src/components/team/InviteList.tsx @@ -0,0 +1,138 @@ +/** + * The workspace's pending invites. Someone who may manage the team (the + * `teamManage` flag) can send one again (the old link stops working) or + * revoke it. The list fetches again on Live notices about accounts. + */ +import type { Invite } from '@nebulr-group/bridge-auth-core'; +import { useMemo, useState, type HTMLAttributes } from 'react'; +import { getBridge } from '../../core/client.js'; +import { errorMessage } from '../../core/i18n.js'; +import { resource } from '../../core/resources.js'; +import { useCanManageTeam, useResource, useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import { Spinner } from '../shared/Spinner.js'; + +export interface InviteListProps extends HTMLAttributes { + readonly onError?: (error: unknown) => void; +} + +// Accepted, revoked and expired invites are history, not pending. +const DONE = new Set(['accepted', 'revoked', 'expired']); + +function day(iso: string): string { + const date = new Date(iso); + return Number.isNaN(date.getTime()) ? '—' : date.toLocaleDateString(); +} + +export function InviteList({ onError, ...rest }: InviteListProps) { + const t = useTranslator(); + const canManage = useCanManageTeam(); + const store = useMemo(() => resource((client) => client.team.invites.list(), ['accounts.']), []); + const invites = useResource(store); + + const pending = (invites.value ?? []).filter((invite) => !DONE.has(invite.state)); + const loadingList = invites.value === null && invites.error === null; + + const [busyId, setBusyId] = useState(null); + const [failure, setFailure] = useState(null); + const [notice, setNotice] = useState(null); + + async function act(invite: Invite, run: () => Promise, done: string) { + setBusyId(invite.id); + setFailure(null); + setNotice(null); + try { + await run(); + setNotice(done); + await store.refresh(); + } catch (error) { + setFailure(errorMessage(error, t)); + onError?.(error); + } finally { + setBusyId(null); + } + } + + function resend(invite: Invite) { + const fields = invite.role ? { email: invite.email, role: invite.role } : { email: invite.email }; + void act(invite, () => getBridge().team.invites.create(fields), `Invite sent again to ${invite.email}.`); + } + + function revoke(invite: Invite) { + void act(invite, () => getBridge().team.invites.revoke(invite.id), `Invite to ${invite.email} revoked.`); + } + + return ( +
+
+

Pending Invites

+
+ + {failure ? ( +
+ {failure} +
+ ) : invites.error ? ( +
+ {errorMessage(invites.error, t)} +
+ ) : null} + {notice && ( +
+ {notice} +
+ )} + + {loadingList ? ( +
+ + Loading invites... +
+ ) : invites.value !== null && pending.length === 0 ? ( +
+

No pending invites.

+
+ ) : pending.length > 0 ? ( +
+ + + + + + + {canManage && } + + + + {pending.map((invite) => ( + + + + + {canManage && ( + + )} + + ))} + +
EmailRoleExpires
+ {invite.email} + + {invite.role || '—'} + {day(invite.expiresAt)} +
+ + +
+
+
+ ) : null} +
+ ); +} + +export default InviteList; diff --git a/bridge-react/src/components/team/MemberList.tsx b/bridge-react/src/components/team/MemberList.tsx new file mode 100644 index 0000000..c29d29f --- /dev/null +++ b/bridge-react/src/components/team/MemberList.tsx @@ -0,0 +1,337 @@ +/** + * The workspace's members, with search. Someone who may manage the team (the + * `teamManage` flag) also gets Add Member and each row's actions: edit, enable + * or disable, and remove. Bridge decides every change; a refusal shows its + * message. The list fetches again on Live notices about accounts. + */ +import type { Member } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useMemo, useRef, useState, type HTMLAttributes, type MouseEvent } from 'react'; +import { getBridge } from '../../core/client.js'; +import { errorMessage } from '../../core/i18n.js'; +import { resource } from '../../core/resources.js'; +import { useCanManageTeam, useResource, useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import { Spinner } from '../shared/Spinner.js'; +import { ConfirmDialog } from './ConfirmDialog.js'; +import { EditMemberDialog } from './EditMemberDialog.js'; +import { InviteDialog } from './InviteDialog.js'; + +export interface MemberListProps extends HTMLAttributes { + readonly onError?: (error: unknown) => void; +} + +const PAGE = 100; +const MAX = 500; + +const nameOf = (m: Member) => [m.user.firstName, m.user.lastName].filter((part) => part && part.trim() !== '').join(' ') || m.user.email; + +// A member whose access is off reads as disabled or suspended. +const isOff = (m: Member) => m.status === 'disabled' || m.status === 'suspended'; + +function statusLabel(m: Member): string { + if (isOff(m)) return 'Disabled'; + const words = m.status.replace(/_/g, ' '); + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** The counts in a deletion preview as one line, or null when it has none. */ +function previewLine(preview: unknown): string | null { + if (preview === null || typeof preview !== 'object') return null; + const p = preview as Record; + const isObject = (v: unknown): v is Record => v !== null && typeof v === 'object'; + const source = [p['affects'], p['counts']].find(isObject) ?? p; + const parts = Object.entries(source) + .filter((entry): entry is [string, number] => typeof entry[1] === 'number' && entry[1] > 0) + .map(([key, n]) => `${n.toLocaleString()} ${key.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase()}`); + return parts.length > 0 ? `This also removes ${parts.join(', ')}.` : null; +} + +export function MemberList({ onError, ...rest }: MemberListProps) { + const t = useTranslator(); + const canManage = useCanManageTeam(); + + const [search, setSearch] = useState(''); + const [query, setQuery] = useState(''); + const [limit, setLimit] = useState(PAGE); + // The list reads the latest search and page size each time it fetches. + const wanted = useRef({ limit: PAGE, query: '' }); + wanted.current = { limit, query }; + const store = useMemo( + () => + resource( + (client) => client.team.members.list({ limit: wanted.current.limit, search: wanted.current.query || undefined }), + ['accounts.'], + ), + [], + ); + const list = useResource(store); + + const members = list.value ?? []; + const loadingList = list.value === null && list.error === null; + const hasMore = members.length >= limit && limit < MAX; + + const timer = useRef | undefined>(undefined); + useEffect(() => () => clearTimeout(timer.current), []); + + function onSearch(value: string) { + setSearch(value); + clearTimeout(timer.current); + timer.current = setTimeout(() => { + const next = value.trim(); + wanted.current = { ...wanted.current, query: next }; + setQuery(next); + void store.refresh(); + }, 250); + } + + function showMore() { + const next = Math.min(MAX, limit + PAGE); + wanted.current = { ...wanted.current, limit: next }; + setLimit(next); + void store.refresh(); + } + + const [openMenu, setOpenMenu] = useState(null); + const [busyId, setBusyId] = useState(null); + const [failure, setFailure] = useState(null); + const [inviting, setInviting] = useState(false); + const [editing, setEditing] = useState(null); + const [removing, setRemoving] = useState(null); + const [removeDetail, setRemoveDetail] = useState(null); + const [removeError, setRemoveError] = useState(null); + const [removeBusy, setRemoveBusy] = useState(false); + const removingId = useRef(null); + + // A click anywhere else closes the open row menu. + useEffect(() => { + const close = () => setOpenMenu(null); + document.addEventListener('click', close); + return () => document.removeEventListener('click', close); + }, []); + + function fail(error: unknown): string { + onError?.(error); + return errorMessage(error, t); + } + + function toggleMenu(event: MouseEvent, id: string) { + event.stopPropagation(); + event.nativeEvent.stopImmediatePropagation(); + setOpenMenu(openMenu === id ? null : id); + } + + function openEdit(member: Member) { + setOpenMenu(null); + setEditing(member); + } + + async function setEnabled(member: Member, enabled: boolean) { + setOpenMenu(null); + setFailure(null); + setBusyId(member.id); + try { + await getBridge().team.members.update(member.id, { enabled }); + await store.refresh(); + } catch (error) { + setFailure(fail(error)); + } finally { + setBusyId(null); + } + } + + async function openRemove(member: Member) { + setOpenMenu(null); + setRemoving(member); + removingId.current = member.id; + setRemoveDetail(null); + setRemoveError(null); + try { + const preview = await getBridge().team.members.deletionPreview(member.id); + if (removingId.current === member.id) setRemoveDetail(previewLine(preview)); + } catch { + // The preview is a courtesy: the removal itself reports a refusal. + } + } + + function cancelRemove() { + removingId.current = null; + setRemoving(null); + } + + async function confirmRemove() { + if (removing === null) return; + const id = removing.id; + setRemoveBusy(true); + setRemoveError(null); + try { + await getBridge().team.members.remove(id); + cancelRemove(); + await store.refresh(); + } catch (error) { + setRemoveError(fail(error)); + } finally { + setRemoveBusy(false); + } + } + + const addButton = (label: string) => ( + + ); + + return ( + <> +
+
+

Team Members

+ {canManage && addButton('Add Member')} +
+ +
+ onSearch(e.target.value)} + /> +
+ + {failure ? ( +
+ {failure} +
+ ) : list.error ? ( +
+ {errorMessage(list.error, t)} +
+ ) : null} + + {loadingList ? ( +
+ + Loading team members... +
+ ) : list.value !== null && members.length === 0 ? ( +
+ {query ? ( +

No members match your search.

+ ) : ( + <> +

No team members yet.

+ {canManage && addButton('Add your first team member')} + + )} +
+ ) : members.length > 0 ? ( + <> +
+ + + + + + + {canManage && } + + + + {members.map((member) => { + const off = isOff(member); + return ( + + + + + {canManage && ( + + )} + + ); + })} + +
UserRoleStatus
+
+
{nameOf(member)}
+
{member.user.email}
+
+
+ {member.role || '—'} + + + {statusLabel(member)} + + +
+ + {openMenu === member.id && ( +
+ + + +
+ )} +
+
+
+ {hasMore && ( + + )} + + ) : null} +
+ + {canManage && ( + <> + setInviting(false)} onInvited={() => void store.refresh()} /> + + setEditing(null)} onUpdated={() => void store.refresh()} /> + + void confirmRemove()} + onCancel={cancelRemove} + /> + + )} + + ); +} + +export default MemberList; diff --git a/bridge-react/src/components/team/ProfileForm.tsx b/bridge-react/src/components/team/ProfileForm.tsx new file mode 100644 index 0000000..9ae6a90 --- /dev/null +++ b/bridge-react/src/components/team/ProfileForm.tsx @@ -0,0 +1,135 @@ +/** The signed-in person's own profile: name and phone number. */ +import type { Me } from '@nebulr-group/bridge-auth-core'; +import { useEffect, useState, type HTMLAttributes } from 'react'; +import { getBridge } from '../../core/client.js'; +import { errorMessage } from '../../core/i18n.js'; +import { me as meStore } from '../../core/resources.js'; +import { useMe, useTranslator } from '../../react/hooks.js'; +import { Alert } from '../shared/Alert.js'; +import { Spinner } from '../shared/Spinner.js'; + +type Profile = Pick; + +export interface ProfileFormProps extends HTMLAttributes { + readonly onError?: (error: unknown) => void; +} + +export function ProfileForm({ onError, ...rest }: ProfileFormProps) { + const t = useTranslator(); + const me = useMe(); + + const [base, setBase] = useState(null); + const [firstName, setFirstName] = useState(''); + const [lastName, setLastName] = useState(''); + const [phoneNumber, setPhoneNumber] = useState(''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [success, setSuccess] = useState(null); + + const changed: { firstName?: string; lastName?: string; phoneNumber?: string } = {}; + if (base !== null) { + if (firstName.trim() !== (base.firstName ?? '')) changed.firstName = firstName.trim(); + if (lastName.trim() !== (base.lastName ?? '')) changed.lastName = lastName.trim(); + if (phoneNumber.trim() !== (base.phoneNumber ?? '')) changed.phoneNumber = phoneNumber.trim(); + } + const dirty = Object.keys(changed).length > 0; + + function adopt(value: Profile) { + setBase(value); + setFirstName(value.firstName ?? ''); + setLastName(value.lastName ?? ''); + setPhoneNumber(value.phoneNumber ?? ''); + } + + // Fresh values from Bridge fill the form, unless the person is mid-edit. + useEffect(() => { + if (me.value !== null && !dirty) adopt(me.value); + }, [me.value]); + + async function save() { + if (!dirty) return; + setSaving(true); + setError(null); + setSuccess(null); + try { + adopt(await getBridge().me.update(changed)); + setSuccess('Profile updated successfully.'); + await meStore.refresh(); + } catch (err) { + setError(errorMessage(err, t)); + onError?.(err); + } finally { + setSaving(false); + } + } + + return ( +
+

My Profile

+ + {base === null ? ( + me.error ? ( +
+ {errorMessage(me.error, t)} +
+ ) : ( +
+ + Loading profile... +
+ ) + ) : ( + <> + {error && ( +
+ {error} +
+ )} + {success && ( +
+ {success} +
+ )} + +
{ + e.preventDefault(); + void save(); + }} + > +
+ + +
+ +
+
+ + setFirstName(e.target.value)} disabled={saving} /> +
+ +
+ + setLastName(e.target.value)} disabled={saving} /> +
+
+ +
+ + setPhoneNumber(e.target.value)} disabled={saving} /> +
+ +
+ +
+
+ + )} +
+ ); +} + +export default ProfileForm; diff --git a/bridge-react/src/components/team/TeamAddUserDialog.tsx b/bridge-react/src/components/team/TeamAddUserDialog.tsx deleted file mode 100644 index 04efd78..0000000 --- a/bridge-react/src/components/team/TeamAddUserDialog.tsx +++ /dev/null @@ -1,142 +0,0 @@ -import type { TeamUser } from '@nebulr-group/bridge-auth-core'; -import type { HTMLAttributes, ReactNode } from 'react'; -import { useEffect, useRef, useState } from 'react'; -import { getBridgeAuth } from '../../core/bridge-instance'; -import { Alert } from '../sdk-auth/shared/Alert'; -import { inviteSeatError } from './seats'; - -interface Props extends HTMLAttributes { - open?: boolean; - onClose?: () => void; - onAdded?: (users: TeamUser[]) => void; - /** - * TBP-763 — seats left on the plan, when the page counts seats. An invite of - * more addresses than this is refused before anything is sent. Null or - * undefined: no limit is checked. - */ - seatsLeft?: number | null; - titleSlot?: ReactNode; - actionsSlot?: (ctx: { loading: boolean; onConfirm?: () => void; onCancel?: () => void }) => ReactNode; -} - -export function TeamAddUserDialog({ - open = false, - onClose, - onAdded, - seatsLeft = null, - titleSlot, - actionsSlot, - className, - style, - ...rest -}: Props) { - const dialogRef = useRef(null); - const [emailsText, setEmailsText] = useState(''); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - - useEffect(() => { - const dialog = dialogRef.current; - if (!dialog) return; - if (open && !dialog.open) { - setEmailsText(''); - setError(null); - dialog.showModal(); - } else if (!open && dialog.open) { - dialog.close(); - } - }, [open]); - - async function handleSubmit() { - const emails = emailsText - .split(/[,\n]/) - .map((e) => e.trim()) - .filter(Boolean); - if (emails.length === 0) { - setError('Please enter at least one email address.'); - return; - } - const seatError = inviteSeatError(emails.length, seatsLeft); - if (seatError) { - setError(seatError); - return; - } - setLoading(true); - setError(null); - try { - const bridge = getBridgeAuth(); - const created = await bridge.team.createUsers(emails); - onAdded?.(created); - onClose?.(); - } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to add users'); - } finally { - setLoading(false); - } - } - - return ( - onClose?.()} - {...rest} - > -
- {titleSlot ?? ( - <> -

Add Team Members

-

- Enter email addresses separated by commas or new lines. -

- - )} - - {error && ( -
- {error} -
- )} - -
- -