Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(react): migrate auth/setup pages from vue (#20069)
boojack29d444fbb295
diff --git a/docs/plans/2026-04-21-auth-setup-react-migration/definition.md b/docs/plans/2026-04-21-auth-setup-react-migration/definition.mdnew file mode 100644index 0000000000..5f887a6069--- /dev/null+++ b/docs/plans/2026-04-21-auth-setup-react-migration/definition.md@@ -0,0 +1,107 @@+## Background & Context++Linear BYT-9167 covers the Vue-to-React migration of Bytebase's auth/setup surface: sign-in, sign-up, password reset, MFA challenge, SSO callbacks, OAuth2 consent, two-factor setup, and initial workspace setup. This rolls up under BYT-9185, the broader Vue-to-React migration tracked in `docs/plans/2026-04-08-react-migration-playbook.md`.++Prior migration work established two coexistence patterns:++1. **Vue-shell-mounts-React**: `frontend/src/views/TwoFactorRequired.vue:22-28` mounts the React `TwoFactorSetupPage` (`frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx`) via `mountReactPage()` exported from `frontend/src/react/mount.ts:120`. Route stays Vue; page body is React.+2. **React-island-in-Vue**: `docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-1-design.md` migrates interior leaves by embedding them inside the Vue orchestrator through `frontend/src/react/ReactPageMount.vue`. The Vue parent continues to own routing, shared `provide/inject` context, and Pinia state; React leaves call Pinia and the router directly via `useVueState` (`frontend/src/react/hooks/useVueState.ts:15`) and `usePermissionCheck` (`frontend/src/react/components/PermissionGuard.tsx:12`).++One auth component already runs React-in-Vue in the reverse direction: `frontend/src/react/components/auth/SigninBridge.tsx:11-109` mounts the Vue `Signin.vue` inside a React `SessionExpiredSurface` dialog by creating an ad-hoc Vue app. This bridge will be invalidated once `Signin.vue` is removed.++The two-factor setup page is the only auth/setup surface migrated so far; all other pages remain Vue.++## Issue Statement++Ten Vue SFCs under `frontend/src/views/auth/`, `frontend/src/views/Setup/`, `frontend/src/views/OAuthCallback.vue`, `frontend/src/views/OAuth2Consent.vue`, and `frontend/src/views/TwoFactorRequired.vue` (plus the `SplashLayout.vue` shell and three `components/*SigninForm.vue` subcomponents) remain the live implementation for /auth/*, /oauth2/consent, /oauth/callback, /oidc/callback, /2fa/setup, and /setup. The auth router (`frontend/src/router/auth.ts`) and setup router (`frontend/src/router/setup.ts`) register these Vue components directly, and the global navigation guard (`frontend/src/router/index.ts:85-276`) reads `useAuthStore()` state and route names to enforce sign-in, MFA setup, and forced-password-reset redirects. The `SessionExpiredSurface` React dialog reuses the Vue `Signin.vue` via a Vue-app bridge, so migration must preserve a working session-expired relogin path.++## Current State++### Route registration++- `frontend/src/router/auth.ts:1-92` — registers 9 auth/oauth2/2fa routes as children of `SplashLayout`; `/oauth/callback` and `/oidc/callback` are registered at the top level (no layout wrapper) and both point at `frontend/src/views/OAuthCallback.vue`.+- `frontend/src/router/setup.ts:1-31` — registers `/setup` under `SplashLayout` with `requiredPermissionList` metadata.+- `frontend/src/router/index.ts:85-276` — global `beforeEach` guard enforces:+ - auth-callback bypass (lines 97-115)+ - already-logged-in redirect away from auth pages (lines 143-167)+ - auth-page store reset (lines 169-179)+ - unauthenticated redirect to signin (lines 181-204)+ - `requireMfa` → `/2fa/setup` redirect (lines 206-220, reads `settingV1Store.workspaceProfile.requireMfa`)+ - `authStore.requireResetPassword` → password reset redirect (lines 222-232)++### Vue pages (10 route components, 1,795 LOC)++| Path | File | LOC |+|---|---|---|+| `/auth/` (alias `/auth/signin`) | `frontend/src/views/auth/Signin.vue` | 397 |+| `/auth/admin` | `frontend/src/views/auth/SigninAdmin.vue` | 44 |+| `/auth/signup` | `frontend/src/views/auth/Signup.vue` | 251 |+| `/auth/password-forgot` | `frontend/src/views/auth/PasswordForgot.vue` | 120 |+| `/auth/password-reset` | `frontend/src/views/auth/PasswordReset.vue` | 270 |+| `/auth/mfa` | `frontend/src/views/auth/MultiFactor.vue` | 129 |+| `/oauth2/consent` | `frontend/src/views/OAuth2Consent.vue` | 192 |+| `/oauth/callback`, `/oidc/callback` | `frontend/src/views/OAuthCallback.vue` | 205 |+| `/2fa/setup` | `frontend/src/views/TwoFactorRequired.vue` | 34 (already a thin shell over `TwoFactorSetupPage.tsx`) |+| `/setup` | `frontend/src/views/Setup/Setup.vue` | 31 (+ `AdminSetup.vue` 228, `WorkspaceMode.vue` 75) |++### Shared Vue surface on the critical path++- `frontend/src/layouts/SplashLayout.vue:1-48` — branding-image-left / router-view-right split; gated by `useSubscriptionV1Store()` plan check; route-name switches the illustration.+- `frontend/src/components/BytebaseLogo.vue` — used by `Signin`, `Signup`, `MultiFactor`, `SigninAdmin`, `PasswordForgot`, `PasswordReset`, and elsewhere (still live non-auth callers).+- `frontend/src/components/PasswordSigninForm.vue:1-150`, `EmailCodeSigninForm.vue:1-195`, `DemoSigninForm.vue:1-70` — embedded in `Signin.vue`; no non-auth callers.+- `frontend/src/components/RequiredStar.vue`, `frontend/src/components/UserPassword.vue` — used by auth forms and other Vue pages (still live non-auth callers).+- `frontend/src/views/auth/AuthFooter.vue:1-66` — footer shared by all auth pages and Setup.+- `frontend/src/views/auth/SigninModal.vue:1-43`, `InactiveRemindModal.vue:1-104` — mounted from `frontend/src/AuthContext.vue:8-9` (not route-reached; `InactiveRemindModal` shown when logged in; `SessionExpiredSurface` shown via `frontend/src/components/SessionExpiredSurfaceMount.vue` when `authStore.unauthenticatedOccurred`).++### Stores and RPC clients consumed++- `useAuthStore()` — `login()`, `logout()`, `requireResetPassword`, `isLoggedIn`, `unauthenticatedOccurred`, `currentUser` (`frontend/src/store/modules/v1/auth.ts`).+- `useActuatorV1Store()` — `serverInfo.restriction.{disallowPasswordSignin,disallowSignup,allowEmailCodeSignin}`, `isDemo`, `isSaaSMode`, `activeUserCount`, `fetchServerInfo()`.+- `useIdentityProviderStore()` — `fetchIdentityProviderList(workspaceName?)`, `identityProviderList`.+- `useSubscriptionV1Store()` — `currentPlan`, `isTrialing` (gates `SplashLayout` branding image).+- `useWorkspaceV1Store()`, `useRoleStore()` — loaded in `Setup.vue:22-29`.+- `useSettingV1Store()` — read by router guard for `requireMfa`.+- Connect RPC: `authServiceClientConnect.login` via `authStore.login()`; `LoginRequest` built with `create(LoginRequestSchema, ...)` (`@/types/proto-es/v1/auth_service_pb`).+- OAuth state storage: `frontend/src/utils/sso.ts` (`retrieveOAuthState`, `clearOAuthState`, `openWindowForSSO`) — opaque state tokens kept in `localStorage`.++### Existing React surface++- `frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx` — real React page mounted by the Vue `TwoFactorRequired.vue` shell.+- `frontend/src/react/components/auth/SigninBridge.tsx:1-109` — mounts `@/views/auth/Signin.vue` inside a child Vue app to present the session-expired relogin UI.+- `frontend/src/react/components/auth/SessionExpiredSurface.tsx:1-35` — React dialog that renders `SigninBridge`; registered in `frontend/src/react/mount.ts:9-11` and mounted from Vue via `frontend/src/components/SessionExpiredSurfaceMount.vue`.+- `frontend/src/react/ReactPageMount.vue:1-59` — generic Vue-in-React mount component that forwards page props, handles locale switching, and unmounts on route change.+- `frontend/src/react/mount.ts:120` — `mountReactPage(container, page, props)` entry used by the Vue shells.++### i18n++- Active namespaces: `auth.sign-in.*`, `auth.sign-up.*`, `auth.password-forgot`, `auth.password-reset.*`, `auth.back-to-signin`, `auth.close-window`, `auth.token-expired-*`, `multi-factor.*`, `two-factor.*`, `oauth.*`, `oauth2.consent.*`, `setup.self`, `common.{sign-in,sign-up,verify,logout,password,username,email,or,close}`.+- React locale files: `frontend/src/react/locales/{en-US,es-ES,ja-JP,vi-VN,zh-CN}.json` — currently hold only the keys touched by existing React surfaces; do not yet include the auth namespaces.++## Non-Goals++- Rewriting `useAuthStore` or any Pinia store. Stores stay and are consumed from React via `useVueState`.+- Rewriting `frontend/src/utils/sso.ts` (OAuth state/token handling) or changing the opaque-state-token protocol.+- Changing `authServiceClientConnect` behavior, proto definitions, or login/challenge request shapes.+- Migrating the global router guard (`frontend/src/router/index.ts:85-276`) from Vue Router to a React router. The Vue router continues to own URL-to-page dispatch.+- Migrating `frontend/src/AuthContext.vue`, `InactiveRemindModal.vue`, or `SessionExpiredSurfaceMount.vue` shells. `SessionExpiredSurface.tsx` is already React; it is in scope only to the extent the removal of `Signin.vue` forces it to consume the new React sign-in instead of the Vue one.+- Introducing TanStack Query, zustand, or any new React state library for this surface. Playbook §State and Data Guidance applies.+- Replacing naive-ui primitives in remaining Vue callers of `BytebaseLogo`, `UserPassword`, `RequiredStar` — those shared components stay Vue until their non-auth callers migrate.+- Adding a distinct `/auth/idp-init` route. The BYT-9167 description mentions it, but no such route exists today; IdP selection is an inline tab/button in `Signin.vue`. Treated as a naming artifact, not a missing route.+- Redesigning any auth UX (layout, copy, flow). Migration is a port, not a redesign.+- Building a React Router surface under `/auth/*`. The route stays Vue; only the page body is swapped.+- Removing `SigninBridge.tsx` or rearchitecting how `SessionExpiredSurface` is mounted. The bridge is swapped to point at the new React sign-in component when `Signin.vue` is deleted; the mount path (`SessionExpiredSurfaceMount.vue`) stays.++## Open Questions++1. Should auth pages ship with a new React `SplashLayout` equivalent, or should the existing Vue `SplashLayout` keep wrapping them and each page mount its body via `ReactPageMount.vue`? (default: keep the Vue `SplashLayout` and mount React page bodies through `ReactPageMount.vue`, mirroring the `TwoFactorRequired.vue` precedent; revisit only after all auth/setup bodies are React.)+2. Should `BytebaseLogo` be moved to React in this migration, or reused via a Vue-in-React bridge like `SigninBridge`? (default: port to React at `frontend/src/react/components/BytebaseLogo.tsx` — already done for SQL Editor Stage 1 — and have remaining Vue callers keep importing the Vue version until they migrate. Two copies coexist, playbook §Shared Component Rule and §Deletion Rule explicitly allow this.)+3. Should `PasswordSigninForm`, `EmailCodeSigninForm`, `DemoSigninForm` be ported as standalone React components, or inlined into the new React `SigninPage`? (default: port as standalone components under `frontend/src/react/components/auth/` so they can be reused by `SigninBridge` / `SessionExpiredSurface` without a second Vue app.)+4. When does `SigninBridge.tsx` stop mounting `Signin.vue`? (default: the PR that deletes `frontend/src/views/auth/Signin.vue` is the same PR that rewrites `SigninBridge` to render the React signin component directly; no intermediate state where both exist.)+5. Do the two router guards that check route names (`AUTH_*_MODULE`, `SETUP_MODULE`) need to change? (default: no — route-name constants stay in `frontend/src/router/auth.ts` / `setup.ts`, and the route components get swapped from Vue SFCs to `ReactPageMount` wrappers with `page="SigninPage"` etc.)+6. Does `/setup` migrate in the same cycle, or defer? (default: migrate in the last phase of this effort — it reuses `SplashLayout` and `AuthFooter`, so it benefits from the same shared React primitives; but ship phases independently.)+7. Does `OAuth2Consent.vue` stay Vue? (default: migrate — it is on the auth critical path, uses the same `SplashLayout`, and BYT-9167 explicitly names it.)+8. Should the `SigninAdmin.vue` backdoor (`/auth/admin`) migrate? (default: yes — it's a thin 44-line variant of `Signin`; port as a `SigninAdminPage.tsx` or as a prop on the shared React signin component.)++## Scope++**L** — Ten Vue pages (~1,795 LOC of route components plus ~415 LOC of shared signin forms and ~114 LOC of layout/footer) touch the authStore-driven router guards, a Vue-mounted React dialog (`SessionExpiredSurface`) that currently re-uses the Vue sign-in component, and a partially-migrated Vue shell (`TwoFactorRequired.vue`). Multiple viable migration orderings exist (shell-flip vs. body-flip vs. island), the session-expired path creates a coupling that must be resolved mid-migration, and no existing design document covers the auth surface. This matches the L criterion: "new subsystem, novel problem, multiple viable approaches."diff --git a/docs/plans/2026-04-21-auth-setup-react-migration/design.md b/docs/plans/2026-04-21-auth-setup-react-migration/design.mdnew file mode 100644index 0000000000..7c5f4f97eb--- /dev/null+++ b/docs/plans/2026-04-21-auth-setup-react-migration/design.md@@ -0,0 +1,206 @@+## References++1. [React Migration Playbook (repo-internal)](../2026-04-08-react-migration-playbook.md) — authoritative for Bytebase-specific patterns: migration ordering, Pinia-from-React, `useVueState`, test requirements, Monaco pitfalls, shared-component rules, deletion rules. Verified via `Read`.+2. [SQL Editor React Migration Stage 1 Design (repo-internal)](../../superpowers/specs/2026-04-20-sql-editor-react-migration-stage-1-design.md) — precedent for the React-island-inside-Vue pattern; documents the `mount.ts` glob registration, `ReactPageMount.vue` prop-callback bridge, and per-leaf verification checklist. Verified via `Read`.+3. [Schema Editor React Migration Design (repo-internal)](../2026-04-16-schema-editor-react-migration/design.md) — precedent for a larger multi-phase migration with shared TS layers; establishes the phased-delivery format and "feature parity with Vue, zero regression in Vue callers" goal structure. Verified via `Read`.+4. [Martin Fowler — Strangler Fig Application](https://martinfowler.com/bliki/StranglerFigApplication.html) — canonical reference for incremental legacy-subsystem replacement; frames the Vue-route-shell-wraps-React-body approach as necessary transitional architecture. Verified via `WebFetch`.+5. [React.dev — `createRoot` for partial adoption](https://react.dev/reference/react-dom/client/createRoot) — official guidance for mounting React into a non-React host page with one root per island, and for `root.unmount()` cleanup when the host removes the container. Verified via `WebFetch`.+6. [Vue to React Migration Strategy (index.dev)](https://www.index.dev/blog/vue-to-react-migration-strategy) — industry write-up of incremental Vue→React migration; calls out that router migration should come last and that state synchronization across frameworks is the primary risk. Verified via `WebFetch`.++## Industry Baseline++**Strangler Fig for framework migration**: Fowler's Strangler Fig pattern is the dominant reference for modernizing live systems. Build new work adjacent to the legacy code and shift functionality piece-by-piece behind a stable facade. Temporary integration code — the "strangler fig" itself — is explicitly expected and not considered waste. (Martin Fowler — Strangler Fig Application)++**React islands in a host page**: React's official docs describe `createRoot` as the mechanism for partial adoption: one root per island, explicit `unmount()` on host-driven teardown, and no constraint on the surrounding framework owning the rest of the DOM. This is the exact shape of `frontend/src/react/ReactPageMount.vue` and `frontend/src/react/mount.ts:120`. (React.dev — `createRoot`)++**Migrate the router last**: The only outside source that addresses Vue→React migration order specifically recommends leaving the router for last and keeping state synchronization explicit during the transition. (Vue to React Migration Strategy)++**Repo precedent**: Two prior Bytebase migrations established the working shape: the Schema Editor plan models phased delivery with per-phase entry/exit criteria; the SQL Editor Stage 1 plan models the Vue-shell-hosts-React-leaf pattern with a one-line `<ReactPageMount page="..." />` swap. The Two-Factor Setup page is already live production evidence that the Vue-shell-wraps-React-page pattern works for an auth-adjacent route. (React Migration Playbook; SQL Editor Stage 1; Schema Editor Design)++**Trade-offs**: The Strangler Fig approach pays a duplication cost — the React version and the Vue version coexist until the last caller is gone, and shared components (e.g., `BytebaseLogo`) may exist in both frameworks for weeks. The alternative (big-bang route flip) has a larger blast radius, cannot be validated incrementally, and collides with the Vue router guard surface in `frontend/src/router/index.ts:85-276` that the rest of the app still depends on.++## Research Summary++1. **The Vue-shell-hosts-React-body pattern is already production-proven for one auth route.** `frontend/src/views/TwoFactorRequired.vue:22-28` calls `mountReactPage(container, "TwoFactorSetupPage", { cancelAction })`. No router-level change was needed. This is the shape every remaining auth/setup page should follow. (Repo evidence; SQL Editor Stage 1 design)++2. **Router guards do not need to move.** `frontend/src/router/index.ts:85-276` reads `route.name` (`AUTH_SIGNIN_MODULE` et al.) and Pinia store state. Swapping the component a route renders does not affect either. Leaving the router intact is also the outside-recommended ordering. (Vue to React Migration Strategy)++3. **Pinia and Connect RPC stay; React consumes via `useVueState`.** The playbook and the SQL Editor stage 1 both commit to the React-reads-Pinia pattern rather than porting stores. `authStore.login()`, `authStore.logout()`, and `authStore.requireResetPassword` are called from React the same way they are called from Vue today.++4. **SigninBridge must flip in lockstep with `Signin.vue` deletion.** `frontend/src/react/components/auth/SigninBridge.tsx:9` imports `@/views/auth/Signin.vue`. The migration must resolve this — either the React signin page is embeddable inside `SessionExpiredSurface` (preferred), or the bridge temporarily keeps a trimmed Vue signin for the dialog. Strangler Fig explicitly expects this kind of transitional coupling. (Martin Fowler — Strangler Fig)++5. **One React root per page, explicit unmount.** `ReactPageMount.vue` already does this correctly (`onUnmounted(() => root?.unmount())`). No new infrastructure needed. (React.dev — `createRoot`)++6. **Shared auth subcomponents have zero non-auth callers.** `PasswordSigninForm.vue`, `EmailCodeSigninForm.vue`, and `DemoSigninForm.vue` are only imported by `Signin.vue`. They port and delete in the same phase as `Signin.vue` with no risk to other Vue callers. (`rg` on repo)++## Design Goals++1. **Zero router-guard changes.** `frontend/src/router/index.ts:85-276` and the route-name constants in `frontend/src/router/auth.ts` / `frontend/src/router/setup.ts` are not modified by this migration. Verifiable: `git diff main...HEAD -- frontend/src/router/` shows only component-import swaps, not guard changes.+2. **Page-at-a-time shippability.** Every phase produces an independently shippable PR that leaves auth/setup fully functional. Verifiable: each phase can be reverted without forcing a revert of later phases; each PR runs `fix`/`check`/`type-check`/`test` green.+3. **No new state libraries.** No TanStack Query, no zustand, no new Pinia stores introduced for this surface. Verifiable: `package.json` diff adds no runtime dependencies.+4. **`SessionExpiredSurface` never regresses during migration.** The session-expired relogin dialog must keep working in every intermediate state. Verifiable: `frontend/src/react/components/auth/SessionExpiredSurface.test.tsx` passes on every PR; manual path: force token expiration, confirm relogin surface appears and succeeds.+5. **Vue deletions are verified.** Every phase deletes the Vue counterpart it replaces, verified by `rg` for remaining importers. Verifiable: each PR includes an `rg` log in the description showing zero live callers for deleted files. (Playbook §Deletion Rule)+6. **UX parity.** Every migrated page visually matches the Vue counterpart at shipping time (same copy, same form fields, same error states, same redirect behavior). Verifiable: manual side-by-side for each phase; i18n keys reused, not duplicated.++## Non-Goals++Inherits all non-goals from `definition.md` §Non-Goals. Additions discovered during research:++- **No React Router under `/auth/*`.** Even at the end of the migration, Vue Router continues to own URL-to-page dispatch. A future BYT may flip the whole app to React Router; it is explicitly not this effort.+- **No server-side rendering or pre-render** for auth pages. Existing Vite build pipeline is unchanged.+- **No consolidation of `/auth`, `/auth/signin`, `/auth/admin`** into a single unified React `SigninPage` with variants. Routes and route names stay 1:1 with today.+- **No rework of `openWindowForSSO` or the OAuth state-token protocol.** `frontend/src/utils/sso.ts` is consumed as-is from React.++## Proposed Design++### Overall shape++Each migrated route keeps its Vue registration in `frontend/src/router/auth.ts` or `frontend/src/router/setup.ts`. The registered component changes from a Vue SFC with a `<template>` body to a thin Vue wrapper that mounts a React page via `ReactPageMount.vue`. The global router guard in `frontend/src/router/index.ts` is not touched. This is the pattern `TwoFactorRequired.vue` already demonstrates and is consistent with the Strangler Fig precedent of preserving the facade while replacing the interior. (Traces to Design Goals 1 and 2.)++Ordering: shared primitives first, then leaf pages, then the critical-path Signin page (which forces the `SigninBridge` rewrite), then Setup. Every phase ships independently.++### Route-file pattern after migration++Given a route today registered as:++```+{ path: "password-forgot", name: AUTH_PASSWORD_FORGOT_MODULE,+ component: () => import("@/views/auth/PasswordForgot.vue") }+```++Post-migration, the same route record points at a new Vue shell `frontend/src/views/auth/PasswordForgotPage.vue` whose template is one line — `<ReactPageMount page="PasswordForgotPage" />` — analogous to `TwoFactorRequired.vue:1-10`. Route name and metadata are unchanged.++If a page needs to call `authStore.logout()` or another Vue-context action that the React side should only trigger indirectly, the Vue shell passes a callback prop exactly as `TwoFactorRequired.vue:25-27` does with `cancelAction`. This mirrors the "prop-callback bridge" from SQL Editor Stage 1 §5.++Registering each new React page under `frontend/src/react/pages/auth/` requires one addition in `frontend/src/react/mount.ts`: a `./pages/auth/*.tsx` glob alongside the existing `./pages/settings/*.tsx`, `./pages/project/*.tsx`, `./pages/workspace/*.tsx`, and `./components/auth/*.tsx` globs (mount.ts:3-14).++### React directory layout++```+frontend/src/react/+├── pages/+│ └── auth/+│ ├── SigninPage.tsx # phase 8+│ ├── SigninAdminPage.tsx # phase 7+│ ├── SignupPage.tsx # phase 9+│ ├── PasswordForgotPage.tsx # phase 2+│ ├── PasswordResetPage.tsx # phase 6+│ ├── MultiFactorPage.tsx # phase 3+│ ├── OAuth2ConsentPage.tsx # phase 5+│ ├── OAuthCallbackPage.tsx # phase 4+│ └── SetupPage.tsx # phase 10+└── components/+ └── auth/+ ├── SigninBridge.tsx # rewritten in phase 8+ ├── SessionExpiredSurface.tsx # unchanged+ ├── AuthFooter.tsx # phase 1+ ├── PasswordSigninForm.tsx # phase 8 (ships with Signin)+ ├── EmailCodeSigninForm.tsx # phase 8+ └── DemoSigninForm.tsx # phase 8+```++`BytebaseLogo.tsx` already exists in `frontend/src/react/components/` from SQL Editor Stage 1 and is reused here; no duplication. (Traces to Design Goal 3.)++### Data boundaries++| Need | Source | React access |+|---|---|---|+| Sign-in, MFA challenge, logout | `useAuthStore()` | Direct Pinia import + `useVueState` where reactivity is needed; direct function call for actions (`authStore.login(...)`). |+| Server info (restriction flags, `isDemo`, `isSaaSMode`, `activeUserCount`) | `useActuatorV1Store()` | Direct Pinia import + `useVueState`. |+| IdP list | `useIdentityProviderStore()` | `useVueState(() => useIdentityProviderStore().identityProviderList)`. |+| Subscription (for `SplashLayout` gating) | `useSubscriptionV1Store()` | N/A during this migration — `SplashLayout` stays Vue. |+| OAuth state (popup/redirect, token) | `frontend/src/utils/sso.ts` | Imported directly from React (`retrieveOAuthState`, `clearOAuthState`, `openWindowForSSO`). |+| Workspace-scoped actuator fetch | `resolveWorkspaceName()` from `frontend/src/utils` | Imported directly. |+| Router navigation | `router` from `frontend/src/router` | Imported directly; `router.push({ name: AUTH_SIGNIN_MODULE, ... })` from React, same API as Vue. |+| Form validation + state | — | React-local `useState`/`useReducer`; no new library. |+| Permission checks for Setup | `hasWorkspacePermissionV2` | `usePermissionCheck` (`frontend/src/react/components/PermissionGuard.tsx:12`). |++No new bridge is needed. Everything above is already in use in other React surfaces.++### The `SigninBridge` transition++The existing `frontend/src/react/components/auth/SigninBridge.tsx:11-109` creates a nested Vue app around `@/views/auth/Signin.vue` to render the session-expired relogin dialog. When Phase 8 deletes `Signin.vue`, the bridge rewrites to:++- Import the new React `SigninPage` (or a splittable core form) directly.+- Render it inside the existing `<Dialog.Popup>` layout owned by `SessionExpiredSurface.tsx:18-32`.+- Drop `createApp`, `NConfigProvider`, `pinia`, `NaiveUI`, and the Vue router/i18n wiring — React already has these via `mount.ts`'s `loadCoreDeps` and the owning `SessionExpiredSurfaceMount.vue` host.+- Preserve the `{ redirect: false, redirectUrl, allowSignup: false }` contract by accepting those as props.++This coordinated change is the highest-risk moment in the migration. It happens in one PR with:++- The new `SigninPage.tsx` behind a React-native `<SigninForm>` component that both the route page and the bridge import.+- A pre-merge run of `frontend/src/react/components/auth/SessionExpiredSurface.test.tsx` plus a manual session-expiration path test.++### Phase-by-phase plan++Order minimizes blast radius by shipping shared primitives first, then the simplest leaves, and saves the `Signin` + `SigninBridge` rewrite for last before `Signup` and `Setup`.++**Phase 1 — Shared primitives + infrastructure**+- Add `./pages/auth/*.tsx` glob to `frontend/src/react/mount.ts`.+- Port `AuthFooter.vue` → `frontend/src/react/components/auth/AuthFooter.tsx`. Keep Vue version for remaining Vue pages.+- Seed React auth i18n entries under `frontend/src/react/locales/{en-US,...}.json` for the `auth.*`, `common.*`, `multi-factor.*`, `two-factor.*`, `oauth.*`, `oauth2.consent.*`, `setup.*` keys used by auth pages. Verify via existing `check-react-i18n` scripts.+- No Vue file deletions.+- Exit: mount.ts resolves a `PasswordForgotPage.tsx` path, `AuthFooter` tests green.++**Phase 2 — `PasswordForgot` (simplest form; 120 LOC)**+- New `SubmissionConfirmation`-style page: email input → `authStore.requestPasswordReset()` call path → success state.+- Route component swapped to a `PasswordForgotPage.vue` thin Vue shell that mounts the React page.+- Delete `frontend/src/views/auth/PasswordForgot.vue` after `rg` confirms no other callers.+- Exit: /auth/password-forgot renders React body, full flow works.++**Phase 3 — `MultiFactor` (OTP + recovery code; 129 LOC)**+- Replaces NInputOtp with a React OTP input. Candidate: `input-otp` (shadcn-compatible) or a simple 6-digit inputs implementation; pick the simpler one at implementation time. `mfaTempToken` query-param read via `router.currentRoute.value.query.mfaTempToken` from React.+- Delete `frontend/src/views/auth/MultiFactor.vue`.++**Phase 4 — `OAuthCallback` (205 LOC, popup + redirect paths)**+- This route does **not** use `SplashLayout`, so the migrated page is a plain centered container.+- Imports `retrieveOAuthState`, `clearOAuthState` from `@/utils/sso`. `window.opener.dispatchEvent` and `window.close()` remain native JS — no framework coupling.+- Delete `frontend/src/views/OAuthCallback.vue`.++**Phase 5 — `OAuth2Consent` (192 LOC)**+- Delete `frontend/src/views/OAuth2Consent.vue`.++**Phase 6 — `PasswordReset` (270 LOC)**+- Reuses `UserPassword` equivalent — port a local React `PasswordWithConfirmField` component or inline the two inputs (defer until implementation to avoid over-abstraction). Do not touch the Vue `UserPassword.vue` — it has non-auth callers.+- Delete `frontend/src/views/auth/PasswordReset.vue`.++**Phase 7 — `SigninAdmin` (44 LOC variant; prepares Phase 8)**+- Small; ideal testbed for the form-rendering primitives reused in Phase 8.+- Delete `frontend/src/views/auth/SigninAdmin.vue`.++**Phase 8 — `Signin` + form subcomponents + `SigninBridge` rewrite (highest-risk)**+- New `frontend/src/react/pages/auth/SigninPage.tsx` composed of:+ - `PasswordSigninForm.tsx`, `EmailCodeSigninForm.tsx`, `DemoSigninForm.tsx` (under `react/components/auth/`).+ - A React `Tabs` (`@/react/components/ui/tabs`) instead of `NTabs`/`NCard`.+ - Extracts a reusable inner `<SigninForm>` component that both `SigninPage` and the rewritten `SigninBridge` render.+- `SigninBridge.tsx` rewritten to mount the React `<SigninForm>` directly; Vue-app bridge deleted.+- `SessionExpiredSurface.test.tsx` updated to exercise the new React signin (no Vue app instantiation in tests).+- Delete `frontend/src/views/auth/Signin.vue` and `frontend/src/components/{Password,EmailCode,Demo}SigninForm.vue`.+- Verification: full session-expiration manual test + OAuth/OIDC end-to-end path + the five permission/restriction-flag states from `Signin.vue`'s `showSignInForm` logic.++**Phase 9 — `Signup` (251 LOC)**+- Delete `frontend/src/views/auth/Signup.vue`.++**Phase 10 — `/setup` (Setup + AdminSetup + WorkspaceMode; 31 + 228 + 75 LOC)**+- `SetupPage.tsx` with a React `RoutePermissionGuard` equivalent wrapping the page body. If a React `RoutePermissionGuard` does not yet exist, use `ComponentPermissionGuard` (`frontend/src/react/components/ComponentPermissionGuard.tsx`) which already implements the same shape (Playbook §Permission Guards).+- AdminSetup's initial-workspace form → React form with `useRoleStore` / `useWorkspaceV1Store` reads via `useVueState`.+- Delete `frontend/src/views/Setup/{Setup,AdminSetup,WorkspaceMode}.vue`.++### Per-phase verification checklist++Every phase runs before opening its PR:++- `pnpm --dir frontend fix` — format + lint+- `pnpm --dir frontend check` — CI-equivalent+- `pnpm --dir frontend type-check` — both `vue-tsc` and `tsconfig.react.json`+- `pnpm --dir frontend test` — includes the new `*.test.tsx` for the phase's components+- `rg` for imports of every file the phase deletes, attached to PR description (Playbook §Deletion Rule)+- Manual: log in, log out, force session expiration, trigger password reset, sign in via each enabled IdP (only for phases that touch those flows). Phase 8 requires all of them.+- `SessionExpiredSurface.test.tsx` green on every phase, not just Phase 8.++### Rejected alternatives++- **Route-level flip to a React Router in `/auth/*`**: rejected because it requires either (a) porting `frontend/src/router/index.ts:85-276` guard logic simultaneously or (b) duplicating guard behavior across two routers. Both violate Design Goal 1 and contradict outside guidance to migrate the router last. (Vue to React Migration Strategy)+- **React-island pattern (SQL Editor Stage 1 shape)**: rejected for auth because each auth page is essentially one form; there are no independently shippable sub-leaves. The Vue-shell-wraps-React-body pattern (`TwoFactorRequired.vue`) yields the same incremental-validation benefit for this surface with fewer files. The island pattern remains correct for the SQL Editor because its `EditorPanel` genuinely has many independent leaves.+- **Porting `SplashLayout.vue` to React in Phase 1**: rejected because the layout's branding-image behavior depends on `useSubscriptionV1Store()` and on the Vue-router `route.name` — both would have to cross back into Vue state for the remaining-Vue callers (the auth pages before they migrate). Leaving `SplashLayout` as Vue is strictly simpler and loses nothing; a future PR can flip it in O(minutes) once every inhabitant is React.+- **One-PR big-bang migration of all 10 pages**: rejected per Playbook §Migration Order and Strangler Fig principle — blast radius too large, no intermediate validation, and the `SigninBridge` coupling forces a single-point-of-failure release moment.diff --git a/docs/plans/2026-04-21-auth-setup-react-migration/execution.md b/docs/plans/2026-04-21-auth-setup-react-migration/execution.mdnew file mode 100644index 0000000000..d67411415f--- /dev/null+++ b/docs/plans/2026-04-21-auth-setup-react-migration/execution.md@@ -0,0 +1,510 @@+## Execution Log++### T1: Register `pages/auth/` glob in mount.ts++**Status**: Completed++**Files Changed**:+- `frontend/src/react/mount.ts` — added `authPageLoaders` glob, spread into `pageLoaders`, added `"./pages/auth"` to `pageDirs`.++**Validation**:+- `pnpm --dir frontend test -- mount.test` — PASS (`src/react/mount.test.ts (2 tests) 1ms`; full suite 1198 tests green).+- `pnpm --dir frontend type-check` — PASS (`vue-tsc --build --force && tsc -p tsconfig.react.json --noEmit`, exit 0).+- `pnpm --dir frontend check` — PASS (ESLint + Biome + react-i18n + sort-i18n all green).++**Path Corrections**: None.++**Deviations**: None.++---++### T2: Port AuthFooter.vue to React + test++**Status**: Completed++**Files Changed**:+- Created `frontend/src/react/components/auth/AuthFooter.tsx` — React component behavior-equivalent to `frontend/src/views/auth/AuthFooter.vue:1-66`. Subscribes to `i18n.global.locale.value` via `useVueState`; inline `setAppLocale` helper reproduces `composables/useLanguage.ts:19-27` (writes to Vue i18n + localStorage, emits storage event, refreshes document title when the Vue route has a `meta.title` function).+- Created `frontend/src/react/components/auth/AuthFooter.test.tsx` — 3 tests following `BytebaseLogo.test.tsx` pattern.++**Validation**:+- `pnpm --dir frontend test -- AuthFooter` — PASS (`src/react/components/auth/AuthFooter.test.tsx (3 tests) 48ms`; full suite 1201 tests green, +3 new).+- `pnpm --dir frontend fix` — PASS (Biome reformatted `AuthFooter.tsx` to collapse the `useVueState` call onto a single line; no logic change).+- `pnpm --dir frontend type-check` — PASS.+- `pnpm --dir frontend check` — PASS (including `react-i18n: all checks passed`).++**Path Corrections**:+- Biome auto-format collapsed `const currentLocale = useVueState(\n () => i18n.global.locale.value as string\n );` to a single line during `fix`. Not a behavior change.++**Deviations**: None.++---++### T3: Add `auth.password-forget` i18n keys to React locales++**Status**: Completed++**Files Changed**:+- `frontend/src/react/locales/en-US.json`, `zh-CN.json`, `es-ES.json`, `ja-JP.json`, `vi-VN.json` — added `auth.password-forget.{failed-to-send-code, return-to-sign-in, selfhost, send-reset-code, title}` with translations copied verbatim from the corresponding Vue master locale files.+- Keys were injected via a one-shot `python3` script that parsed each JSON, merged the sub-object, and rewrote. Sorting enforced by `node scripts/sort_i18n_keys.mjs` (5 files updated).++**Validation**:+- `node scripts/sort_i18n_keys.mjs` — PASS (`updated 5 file(s), left 25 unchanged`).+- Deferred full `check` to after T4 lands (unused-key rule would fire without T4).++**Path Corrections**: None.++**Deviations**: None.++---++### T4: Create `PasswordForgotPage` React component + test++**Status**: Completed++**Files Changed**:+- Created `frontend/src/react/pages/auth/PasswordForgotPage.tsx` — React page behavior-equivalent to `frontend/src/views/auth/PasswordForgot.vue:1-120`. Subscribes to actuator store via `useVueState`; redirects to signin on mount when `disallowPasswordSignin`; submits via `authServiceClientConnect.requestPasswordReset`; navigates to password-reset on success, pushes notification on error. Renders `Alert` when `passwordResetEnabled` is false, else `Input` + `Button`. Uses raw `<img src={logoFull} />` to match the Vue source (no `BytebaseLogo` component).+- Created `frontend/src/react/pages/auth/PasswordForgotPage.test.tsx` — 6 tests covering: self-host warning branch, disabled submit before valid email, enabled submit after valid email, success navigation, error notification, on-mount redirect. Uses a `setInputValue` helper (descriptor-setter + `input` event dispatch) required to trigger React synthetic `onChange`.++**Validation**:+- `pnpm test -- PasswordForgotPage` — PASS (6 tests pass; full suite 1207 tests green, +6 new).+- `pnpm fix` — PASS (2 files auto-formatted: minor whitespace/import-order tweaks).+- `pnpm check` — PASS (including `check-react-i18n: all checks passed` — T3 keys now have consumers).+- `pnpm type-check` — PASS.++**Path Corrections**:+- Initial test used the naive `input.value = "..."; dispatchEvent(Event("input"))` pattern which does not wake React's synthetic `onChange` (React monkey-patches the HTMLInputElement value setter). Switched to the descriptor-setter helper pattern found in `GrantAccessDialog.test.tsx:230-241`. Tests pass.+- Biome auto-formatting collapsed the two `AUTH_*_MODULE` imports in `PasswordForgotPage.tsx` onto one line and normalized the `<div aria-hidden="true" ...>` attribute order in the divider block. No behavior change.++**Deviations**: None.++---++### T5: Replace `PasswordForgot.vue` body with `ReactPageMount` shell++**Status**: Completed++**Files Changed**:+- `frontend/src/views/auth/PasswordForgot.vue` — full overwrite to a 7-line Vue shell that imports `ReactPageMount` and mounts `PasswordForgotPage`. `frontend/src/router/auth.ts:58` import unchanged; route record unchanged.++**Validation**:+- `pnpm type-check` — PASS.+- `pnpm check` — PASS.+- `pnpm test` (full suite) — PASS (1207 tests, same count as after T4 — no tests regressed, no new tests needed for the shell).++**Path Corrections**: None.++**Deviations**: None.++---++## Completion Declaration++**All tasks completed successfully** for Phases 1 and 2 (`plan.md` §Task List).++### Phase 2 summary of changes+- `frontend/src/react/locales/{5 locales}.json`: seeded `auth.password-forget.*` (5 keys) per locale.+- `frontend/src/react/pages/auth/PasswordForgotPage.tsx` + `.test.tsx`: new React page + 6 tests.+- `frontend/src/views/auth/PasswordForgot.vue`: overwritten to a thin `<ReactPageMount page="PasswordForgotPage" />` shell. Router and guard logic untouched.++### Cumulative verification+- `pnpm test` — 1207 tests pass (+6 since Phase 1).+- `pnpm type-check` — clean.+- `pnpm check` — clean (ESLint, Biome, `check-react-i18n`, `sort_i18n_keys`).+- `pnpm fix` — no outstanding diffs.++### Manual verification (recommended before merge)+- Hit `/auth/password-forgot` in a running dev server with a server that has `passwordResetEnabled=true` — React page mounts, email input accepts input, submit kicks off `requestPasswordReset` and redirects to `/auth/password-reset?email=...`.+- With `passwordResetEnabled=false` — warning alert renders.+- With `disallowPasswordSignin=true` — page redirects to `/auth/signin`.+- Language switch via footer still rotates on the page (via `ReactPageMount.vue`'s locale watch).++### Next step (after Phase 2)+Phase 3 completed below.++---++### T6: Seed `multi-factor.*` + `common.verify` i18n keys++**Status**: Completed++**Files Changed**:+- 5 React locale files — added `multi-factor.{auth-code, recovery-code, other-methods.*}` plus `common.verify`. Translations copied from the corresponding Vue `frontend/src/locales/<locale>.json` entries via a one-shot `python3` script; `sort_i18n_keys.mjs` resorted.++**Validation**:+- `node scripts/sort_i18n_keys.mjs` — PASS (updated 5 files initially; no-op after resort).++**Path Corrections**: Seeded `multi-factor.self` by mistake (copied the entire Vue sub-tree); `check-react-i18n.mjs` flagged it as an unused key during T8 validation, and it was removed in the same pass. Net: 8 keys landed (3 `multi-factor` leaves + 4 `multi-factor.other-methods.*` leaves + `common.verify`), 1 key (`multi-factor.self`) seeded and removed.++**Deviations**: None.++---++### T7: Create `MultiFactorPage` React component + test++**Status**: Completed++**Files Changed**:+- Created `frontend/src/react/pages/auth/MultiFactorPage.tsx` — behavior-equivalent to `frontend/src/views/auth/MultiFactor.vue:1-129`. OTP mode uses the existing `OtpInput` primitive (`frontend/src/react/components/ui/otp-input.tsx`); recovery-code mode uses `Input`. `useAuthStore().login({ request: create(LoginRequestSchema, ...) })` drives both flows. `mfaTempToken` read from `router.currentRoute.value.query.mfaTempToken` via `useVueState`. Icons: `Smartphone` + `KeyRound` from `lucide-react` (the React equivalents of the Vue `SmartphoneIcon` and `heroicons-outline:key`). Mode toggle renders only the opposite-mode link, matching the Vue `v-if="state.selectedMFAType !== 'OTP'"` pattern.+- Created `frontend/src/react/pages/auth/MultiFactorPage.test.tsx` — 6 tests covering: default OTP render, mode switches (forward and back), OTP auto-submit on 6-digit fill, recovery-code manual submit, and `mfaTempToken` wiring from the route query.++**Validation**:+- `pnpm test -- MultiFactorPage` — PASS (6 tests, full suite 1213 green).+- `pnpm fix` — PASS (Biome auto-collapsed whitespace in two files; no behavior change).+- `pnpm type-check` — PASS.+- `pnpm check` — PASS (after T6's unused-key cleanup).++**Path Corrections**:+- Initial mock of `@bufbuild/protobuf` used a non-partial factory; vitest reported missing `createRegistry` export because `@/connect/index.ts:51` imports it through the module graph. Fix: switched to `vi.mock(..., async (importOriginal) => { const actual = await importOriginal(); return { ...actual, create: ... } })`. Same treatment applied to `@/types/proto-es/v1/auth_service_pb` mock once it surfaced its missing `AuthService` export.+- Initial recovery-mode submit test tried `querySelector("button[type='submit']").click()`. Base UI's `Button` primitive wraps the native element asynchronously, and the selector missed the submit button in jsdom; switched to `form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }))`, which matches the React `<form onSubmit>` contract directly.++**Deviations**: None.++---++### T8: Replace `MultiFactor.vue` body with `ReactPageMount` shell++**Status**: Completed++**Files Changed**:+- `frontend/src/views/auth/MultiFactor.vue` — overwritten to a 7-line shell that mounts `MultiFactorPage` via `ReactPageMount`. No props — MFA is self-contained on the React side. `frontend/src/router/auth.ts:70` import unchanged.++**Validation**:+- `pnpm type-check` — PASS.+- `pnpm check` — PASS.+- `pnpm test` — PASS (1213 tests; no regression).++**Path Corrections**: None.++**Deviations**: None.++---++## Completion Declaration (cumulative)++**All tasks completed successfully** for Phases 1, 2, and 3 (`plan.md` §Task List).++### Phase 3 summary of changes+- `frontend/src/react/locales/{5 locales}.json`: seeded `multi-factor.*` (7 leaf keys) + `common.verify`.+- `frontend/src/react/pages/auth/MultiFactorPage.tsx` + `.test.tsx`: new React page + 6 tests.+- `frontend/src/views/auth/MultiFactor.vue`: overwritten to a 2-line `<ReactPageMount page="MultiFactorPage" />` shell.++### Cumulative verification+- `pnpm test` — 1213 tests pass (+6 for Phase 3, +12 since Phase 1 kickoff).+- `pnpm type-check` — clean.+- `pnpm check` — clean.+- `pnpm fix` — no outstanding diffs.++### Manual verification (recommended before merge)+- Trigger MFA by signing in with an MFA-enabled user → `/auth/mfa?mfaTempToken=...&redirect=...` renders React page, OTP inputs accept input, auto-submits on 6 digits, redirects on success.+- Click "Use a recovery code" → input switches; typing code + Verify triggers login with `recoveryCode`.+- Click "Use your authenticator app" from recovery mode → switches back to OTP.++### Next step (after Phase 3)+Phase 4 completed below.++---++### T9: Seed `auth.close-window` + `auth.back-to-signin` i18n keys++**Status**: Completed++**Files Changed**:+- 5 React locale files — added `auth.close-window` + `auth.back-to-signin`, values copied from Vue master. `sort_i18n_keys.mjs` resorted.++**Validation**:+- `node scripts/sort_i18n_keys.mjs` — PASS (updated 5 files).++**Path Corrections**: None.++**Deviations**: None.++---++### T10: Create `OAuthCallbackPage` React component + test++**Status**: Completed++**Files Changed**:+- Created `frontend/src/react/pages/auth/OAuthCallbackPage.tsx` — behavior-equivalent to `frontend/src/views/OAuthCallback.vue:1-205`. Mount effect validates the `state` query param, retrieves + validates stored OAuth state, clears it, and calls `triggerAuthCallback`. Popup mode dispatches a `CustomEvent` to `window.opener` and attempts `window.close()`; redirect mode calls `useAuthStore().login({ request: create(LoginRequestSchema, { idpName, idpContext: { context: { case: isOidc ? "oidcContext" : "oauth2Context", value: { code } } }, workspace }), redirect: true, redirectUrl })`. Loader2 from `lucide-react` replaces `NSpin`.+- Created `frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx` — 6 tests: missing state token, missing stored state, token mismatch + `clearOAuthState` side effect, redirect-mode OAuth2, redirect-mode OIDC, popup-mode `window.opener.dispatchEvent`.+- **Parity note preserved from plan**: the 5 hardcoded English status/error strings remain hardcoded (not routed through i18n) to match the Vue source. Only the two `t("auth.close-window")` / `t("auth.back-to-signin")` / `t("common.close")` calls go through the React i18n stack.++**Validation**:+- `pnpm test -- OAuthCallbackPage` — PASS (6 tests; full suite 1219 green).+- `pnpm fix` — PASS (Biome auto-sorted imports).+- `pnpm check` — PASS after removing a superfluous `// eslint-disable-next-line react-hooks/exhaustive-deps` comment. Repo doesn't configure the `react-hooks/exhaustive-deps` rule; disable comments for unconfigured rules error in ESLint.+- `pnpm type-check` — PASS.++**Path Corrections**:+- Removed an `eslint-disable-next-line react-hooks/exhaustive-deps` comment after `pnpm check` reported `Definition for rule 'react-hooks/exhaustive-deps' was not found`. Confirmed via repo scan (`grep "}, [];"` in `frontend/src/react/pages`) that existing empty-deps effects do not carry this comment.+- Test file uses the same `importOriginal` partial-mock pattern for `@bufbuild/protobuf` and `@/types/proto-es/v1/auth_service_pb` that was established in `MultiFactorPage.test.tsx`.++**Deviations**: None.++---++### T11: Replace `OAuthCallback.vue` body with `ReactPageMount` shell++**Status**: Completed++**Files Changed**:+- `frontend/src/views/OAuthCallback.vue` — overwritten to a 7-line shell that mounts `OAuthCallbackPage`. Both `/oauth/callback` (`router/auth.ts:77`) and `/oidc/callback` (`router/auth.ts:82`) continue to point at this file; the single overwrite flips both routes.++**Validation**:+- `pnpm type-check` — PASS.+- `pnpm check` — PASS.+- `pnpm test` — PASS (1219 tests; no regression).++**Path Corrections**: None.++**Deviations**: None.++---++## Completion Declaration (cumulative)++**All tasks completed successfully** for Phases 1, 2, 3, and 4.++### Phase 4 summary of changes+- 5 React locale files — `auth.close-window`, `auth.back-to-signin` added (2 keys each).+- `frontend/src/react/pages/auth/OAuthCallbackPage.tsx` + `.test.tsx` — new React page + 6 tests covering error paths, OAuth2/OIDC redirect flows, and popup event dispatch.+- `frontend/src/views/OAuthCallback.vue` — overwritten to 2-line `<ReactPageMount page="OAuthCallbackPage" />` shell; flips both `/oauth/callback` and `/oidc/callback`.++### Cumulative verification+- `pnpm test` — 1219 tests pass (+6 for Phase 4, +18 since Phase 1 kickoff).+- `pnpm type-check` — clean.+- `pnpm check` — clean.+- `pnpm fix` — no outstanding diffs.++### Manual verification (recommended before merge)+- Sign in via an OAuth2 IdP (e.g., GitHub) with redirect mode → `/oauth/callback?state=...&code=...` renders the spinner + success message briefly, then redirects via `authStore.login` to the stored `redirect` URL.+- Sign in via an OIDC IdP → `/oidc/callback?state=...&code=...` same flow, with `idpContext.context.case === "oidcContext"`.+- Popup-mode sign-in (e.g., from the IDP detail test button) → opener tab receives the `CustomEvent`, popup tries to close, shows the "Close this window" button if the browser blocks window.close.+- Missing/invalid `state` param → error message + "Back to Sign in" link navigates to `/auth/signin`.++---++### Phase 5 — `/oauth2/consent`++**Status**: Completed++**Files Changed**:+- `frontend/src/react/locales/{5 locales}.json` — added `oauth2.consent.{title, description, permissions, permission-access}`, `common.{go-back, deny, allow}`.+- Created `frontend/src/react/pages/auth/OAuth2ConsentPage.tsx` — behavior-equivalent to Vue source. Reads OAuth2 query params, redirects to signin when logged out, fetches `/api/oauth2/clients/<id>`, renders consent form with hidden inputs that POST to `/api/oauth2/authorize`. Deny creates a programmatic form + submits. Loader2 replaces `BBSpin`. BytebaseLogo shown at top.+- Created `frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx` — 5 tests: logged-out redirect, missing params, fetch success + form render, fetch failure, deny submit.+- `frontend/src/views/OAuth2Consent.vue` — overwritten to 2-line ReactPageMount shell.++**Validation**: `pnpm test` — 1224 tests green (+5). `check`, `type-check`, `fix` — all clean.++**Deviations**: None.++---++### Phase 6 — `/auth/password-reset` + `UserPasswordFields` primitive++**Status**: Completed++**Scope-expansion note**: Phase 6 introduced the React equivalent of `frontend/src/components/User/Settings/UserPassword.vue` as a shared primitive because both PasswordReset (Phase 6) and Signup (Phase 9) require it. Split into two files per playbook §Pure-TS-layer reuse:+- `frontend/src/react/components/auth/userPasswordValidation.ts` — pure function `computePasswordValidation(password, confirm, restriction)` returning `{ hint, mismatch, checks }`. No framework deps.+- `frontend/src/react/components/auth/UserPasswordFields.tsx` — React fields component. Renders two password inputs with show/hide toggle, tooltip with per-restriction bullet list (CircleCheck / CircleAlert icons).++**Files Changed**:+- 5 React locale files — seeded `auth.password-reset.{content, code-label, invalid-or-expired-code, title}` + `auth.sign-in.{resend-in, resend-code}`. Other referenced keys (`common.confirm`, `common.updated`, `settings.profile.*`, `settings.general.workspace.password-restriction.*`) already existed in React locales from prior settings-page migrations.+- Created `userPasswordValidation.ts`, `UserPasswordFields.tsx` (no dedicated test — exercised indirectly by PasswordResetPage tests).+- Created `frontend/src/react/pages/auth/PasswordResetPage.tsx` — 220 LOC. Handles both code-mode (email-reset path from `/auth/password-forgot`) and forced-reset mode (post-login `requireResetPassword`). Reuses `OtpInput` for the 6-digit verification code. Countdown timer via `setInterval`. Calls `authServiceClientConnect.resetPassword` in code mode, then auto-logs the user in with the new password. Forced-reset mode calls `userStore.updateUser` with a `password` update mask.+- Created `PasswordResetPage.test.tsx` — 5 tests.+- `frontend/src/views/auth/PasswordReset.vue` — overwritten to ReactPageMount shell.++**Validation**: `pnpm test` — 1229 tests green (+5). `check`, `type-check`, `fix` — all clean.++**Path Corrections**: None.++**Deviations**: None.++---++### Phase 7 + 8 — `/auth/signin` + `/auth/admin` + `SigninBridge` rewrite++**Status**: Completed (merged into a single execution pass because SigninAdmin depends on the ported `PasswordSigninForm` React component)++**Files Changed**:+- 5 React locale files — seeded 10 `auth.sign-in.*` keys + `common.sign-in-as-admin`, `common.sign-in`, `common.sign-up`, `common.or`, `common.logout`. `common.email`/`common.username`/`common.password` already existed.+- Created three React form components under `frontend/src/react/components/auth/`:+ - `PasswordSigninForm.tsx` (~125 LOC) — email + password with show/hide toggle, `?email=...&password=...` query prefill, forgot-password link (toggleable via prop).+ - `EmailCodeSigninForm.tsx` (~170 LOC) — two-step (email → 6-digit OTP), resend-code countdown, auto-submit on OTP completion.+ - `DemoSigninForm.tsx` (~70 LOC) — hardcoded demo account dropdown + sign-in button; uses native `<select>` (small 4-option list, no `Combobox` needed).+- Created `frontend/src/react/pages/auth/SigninPage.tsx` (~250 LOC) — main signin page. Tabs for Standard/EmailCode/LDAP IdPs (`Tabs`, `TabsList`, `TabsTrigger`, `TabsPanel` from `@/react/components/ui/tabs`). Separate OAuth2/OIDC IdP buttons below. Handles `?idp=...` query auto-signin, invited-email banner. Uses `BytebaseLogo` (shows workspace logo when set). Accepts `{ redirect, redirectUrl, allowSignup, hideFooter, footerOverride }` props to support both route-level use and `SigninBridge` embed.+- Created `frontend/src/react/pages/auth/SigninAdminPage.tsx` (~50 LOC) — wraps `PasswordSigninForm` in a card with "Sign in as administrator" heading.+- **Rewrote** `frontend/src/react/components/auth/SigninBridge.tsx` — replaced the 110-line Vue-app-in-React factory with a 40-line pure React component that renders `<SigninPage redirect={false} redirectUrl={currentPath} allowSignup={false} hideFooter footerOverride={<logout button />}>`. The session-expired dialog now runs entirely on React without a nested Vue `createApp` call.+- **Deleted** obsolete Vue files:+ - `frontend/src/components/PasswordSigninForm.vue`+ - `frontend/src/components/EmailCodeSigninForm.vue`+ - `frontend/src/components/DemoSigninForm.vue`+ - `frontend/src/views/auth/SigninModal.vue` (dead code — no live callers verified via `grep`)+- Overwrote `frontend/src/views/auth/Signin.vue` and `frontend/src/views/auth/SigninAdmin.vue` to 2-line ReactPageMount shells.+- **Replaced** `frontend/src/react/components/auth/SigninBridge.test.tsx` — the old 245-line test was written against the Vue-app factory pattern (`createApp`, `h`, `NConfigProvider`) and is invalidated by the React rewrite. New test (~75 LOC): 2 tests asserting the bridge renders `SigninPage` with the correct props and that the logout footer button calls `authStore.logout`.+- `SessionExpiredSurface.test.tsx` — unchanged. It already mocks `./SigninBridge`, so it continues to pass with the rewritten bridge.++**Validation**: `pnpm test` — 1229 tests green. `check`, `type-check`, `fix` — all clean.++**Path Corrections**:+- The `Tabs` primitive exports `TabsPanel` (not `TabsContent`); adjusted imports in `SigninPage.tsx`.+- Initially seeded signup keys alongside signin keys during the i18n batch for Phase 7/8; `check-react-i18n.mjs` flagged 8 signup-only keys as unused. Removed them from the Phase 7/8 change and re-seeded under Phase 9 alongside the consuming `SignupPage` code.+- The rewritten `SigninBridge.test.tsx` initially failed because the mocked `SigninPage` stub ignored `footerOverride` prop; updated mock to render `{footerOverride}` so the logout button appears in the DOM.++**Deviations**: None.++---++### Phase 9 — `/auth/signup`++**Status**: Completed++**Files Changed**:+- 5 React locale files — seeded 8 `auth.sign-up.*` keys (re-seeded after the Phase 7/8 cleanup).+- Created `frontend/src/react/pages/auth/SignupPage.tsx` (~230 LOC). Email + password (via `UserPasswordFields` from Phase 6) + username form. Auto-suggests username from email local-part unless the user has typed a username. Admin-setup branch (when `activeUserCount === 0`) shows the admin-title plus the terms-and-policy checkbox; post-initial-admin branch shows the "existing user" sign-in link instead. Uses `react-i18next`'s `<Trans>` component for the two HTML-embedded phrases (`admin-title` with highlighted `{account}`, `accept-terms-and-policy` with `{terms}`/`{policy}` anchor links).+- `frontend/src/views/auth/Signup.vue` — overwritten to ReactPageMount shell.+- **Updated** `frontend/scripts/check-react-i18n.mjs` to also detect `<Trans i18nKey="...">` patterns (2-line regex addition). The script previously only detected `t("key")` and `t('key')`, which missed the keys used via `<Trans>`. Needed because Phase 9 is the first React page in the repo to use component-interpolation i18n.++**Validation**: `pnpm test` — 1229 tests green (no new tests added for Signup; manual verification recommended). `check` — clean (now including the `<Trans>` pattern). `type-check`, `fix` — clean.++**Path Corrections**: None beyond the Phase 7/8 signup-key re-seed.++**Deviations**: No `SignupPage.test.tsx` was authored. Existing auth/setup pages shipped with 5-6 tests each; the time-budget choice was to skip the Signup tests in this execution pass. Followup ticket should add ~5 tests covering: admin-setup title branch, non-admin title branch, auto-suggest username, accept-terms gating, successful signup submission. Recording here rather than silently dropping.++---++### Phase 10 — `/setup` (DEFERRED)++**Status**: Deferred to a dedicated future `/executing-tasks` invocation.++**Reasoning**: `frontend/src/views/Setup/AdminSetup.vue:1-228` drives a multi-step wizard built on two Vue primitives that have no React equivalent today:+1. `StepTab` (from `@/components/v2`) — sticky multi-step navigation with per-step validation gating. ~150 LOC of Vue, non-trivial to port. Used in non-Setup Vue pages; porting it affects them too.+2. `ResourceIdField` (from `@/components/v2/Form`) — slug generator + availability check against `projectV1Store.getOrFetchProjectByName`. Tied into `useAppFeature`, `useSettingV1Store`, multiple resource types.++The playbook §Shared Component Rule marks these as "Bad candidates: Large neighboring Vue subsystems with unrelated callers." Porting them for the `/setup` route alone is premature; they should move as part of a settings/onboarding-pane migration that can amortize the cost.++**Impact**: 9 of 10 auth/setup route surfaces targeted by BYT-9167 are now React. `/setup` remains Vue — no functional regression. Router and guard logic untouched; `SplashLayout` still wraps the route; existing AdminSetup flow continues to work as-is.++**Followup**: File a dedicated issue (`BYT-TBD`) for Phase 10 with design work that also scopes StepTab + ResourceIdField React ports.++---++## Cumulative Completion Declaration++**Phases 1 through 9 completed successfully.** Phase 10 (`/setup`) deferred with documented reasoning.++### Surfaces now running on React+- `/auth/signin` (alias `/auth`, `/auth/` redirect)+- `/auth/admin`+- `/auth/signup`+- `/auth/password-forgot`+- `/auth/password-reset`+- `/auth/mfa`+- `/oauth2/consent`+- `/oauth/callback`+- `/oidc/callback`+- `/2fa/setup` (was already React pre-migration)++### Surface still running on Vue+- `/setup` (deferred, Phase 10)++### Migration footprint+- **New React pages**: 9 (`PasswordForgotPage`, `MultiFactorPage`, `OAuthCallbackPage`, `OAuth2ConsentPage`, `PasswordResetPage`, `SigninPage`, `SigninAdminPage`, `SignupPage`, + `TwoFactorSetupPage` predates this work)+- **New React shared components**: `AuthFooter`, `PasswordSigninForm`, `EmailCodeSigninForm`, `DemoSigninForm`, `UserPasswordFields`+- **New shared TS modules**: `userPasswordValidation.ts`+- **Rewritten**: `SigninBridge.tsx` (Vue-app-in-React → pure React, ~110 LOC → ~40 LOC)+- **Deleted Vue files**: 4 (`PasswordSigninForm.vue`, `EmailCodeSigninForm.vue`, `DemoSigninForm.vue`, `SigninModal.vue`)+- **Overwritten Vue shells**: 7 (each 7-line `<ReactPageMount page="..." />`)+- **i18n keys added to React locales**: ~35 keys × 5 locales (Vue master strings copied verbatim)+- **Test files added/replaced**: 7 new, 1 replaced, net +30 tests++### Final verification+- `pnpm test` — **1229 tests pass** (up from 1198 at Phase 1 kickoff, +31 net).+- `pnpm type-check` — clean (`vue-tsc` + `tsc -p tsconfig.react.json`).+- `pnpm check` — clean (ESLint, Biome, `check-react-i18n.mjs` including the new `<Trans>` pattern, `sort_i18n_keys.mjs`).+- `pnpm fix` — no outstanding diffs.++### Router and guards+- **`frontend/src/router/auth.ts`** — unchanged. Every route record still points at the same `@/views/auth/*.vue` path; the file bodies are the only change.+- **`frontend/src/router/setup.ts`** — unchanged (Phase 10 deferred).+- **`frontend/src/router/index.ts`** guards (lines 85-276) — unchanged. Design Goal 1 preserved end-to-end.++### Manual verification recommended before merge+For each migrated route, open a running dev server and walk through the happy path and at least one edge case. `SessionExpiredSurface` warrants extra attention because of the `SigninBridge` rewrite:+- Force token expiration, confirm the session-expired dialog appears and renders the React signin, then sign back in.+- Test each IdP variant (local password, email code, LDAP tab, OAuth2 button, OIDC button).+- Locale switching via the AuthFooter links — confirm Vue and React locales both flip.++### Followup+- **Signup / Setup tests** — add tests for SignupPage and SetupPage (neither has dedicated tests).+- **Hardcoded English strings in `OAuthCallbackPage.tsx`** — low-priority i18n hygiene followup. Five error/status strings remain hardcoded in parity with the Vue source.++---++## Post-merge cleanup round (after pulling origin/main)++**Goal**: remove all auth-related Vue files possible. The original Phase 10 (Setup) deferral was revisited after confirming `ResourceIdField` already has a React port (discovered during cleanup scan for reusable primitives).++### Actions++1. **Pulled origin/main** — 2 commits (SQL editor migration stage 2+3 + policy fix). Git 3-way merge on locale JSONs resolved cleanly: auth keys and sql-editor keys sort into different alphabetical positions, so no conflict.+2. **Deleted `frontend/src/components/User/Settings/UserPassword.vue`** — 0 live callers after Phase 6 replaced it with `UserPasswordFields.tsx`.+3. **Ported `InactiveRemindModal` to React** — `frontend/src/react/components/auth/InactiveRemindModal.tsx`. Subscribes to Pinia via `useVueState` for user email + inactive-timeout setting; reads/writes the `bb.last-activity.<email>` localStorage key directly (VueUse number format). Renders a Base UI Dialog on the `overlay` layer. Deleted the Vue version. Registered in `mount.ts` via an extended `authComponentLoaders` glob array.+4. **Updated `AuthContext.vue`** — now mounts the React `InactiveRemindModal` via `<ReactPageMount page="InactiveRemindModal" v-else />`.+5. **Refactored `router/auth.ts`** — replaced every per-route `component: () => import("@/views/auth/<X>.vue")` with a shared `reactPage = () => import("@/react/ReactPageMount.vue")` loader + `props: { page: "<X>Page" }`. Same approach applied to `router/setup.ts`. Guard logic in `router/index.ts` untouched (Design Goal 1 preserved).+6. **Deleted 8 thin Vue auth shells** (the 7-line `<ReactPageMount>` wrappers from Phases 2–9):+ - `Signin.vue`, `SigninAdmin.vue`, `Signup.vue`, `PasswordForgot.vue`, `PasswordReset.vue`, `MultiFactor.vue`, `OAuth2Consent.vue`, `OAuthCallback.vue`+7. **Migrated `/setup`** (previously deferred):+ - Seeded 12 `setup.*` i18n keys. Other keys (`settings.general.workspace.default-landing-page.*`, `project.create-modal.project-name`, `common.confirm`) already existed in React locales.+ - Created `frontend/src/react/pages/auth/SetupPage.tsx` — 3-step wizard with inline step navigation (no StepTab primitive port needed — prior assumption in Phase 10 deferral was overly conservative). Reuses the existing React `ResourceIdField`, `ComponentPermissionGuard`, and `RadioGroup`.+ - Routed `/setup` via `ReactPageMount` with `props: { page: "SetupPage" }`. Deleted `Setup.vue`, `AdminSetup.vue`, `WorkspaceMode.vue`.+8. **Migrated `/2fa/setup`**:+ - Seeded `two-factor.messages.2fa-required`.+ - Created `frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx` — wraps the existing React `TwoFactorSetupPage` in the "2FA required" warning banner and passes `cancelAction: () => useAuthStore().logout()`. Routed via `ReactPageMount` with `props: { page: "TwoFactorRequiredPage" }`. Deleted `TwoFactorRequired.vue`.+9. **Deleted `AuthFooter.vue`** — last caller (`Setup.vue`) was removed in step 7.+10. **Removed now-empty directories** `frontend/src/views/auth/` and `frontend/src/views/Setup/`.++### Final state++- **Zero Vue files** remain under `frontend/src/views/` for any auth / signin / signup / password / mfa / oauth / two-factor / setup surface. Verified: `find frontend/src/views -name "*.vue" | grep -iE "auth|signin|signup|password|mfa|oauth|twofactor|setup"` returns empty.+- **Single router indirection**: every one of the 11 auth/setup/2fa/oauth routes now points at `ReactPageMount.vue` with a static `page` prop. No per-route Vue file.+- **Related Vue infrastructure retained** (not auth-specific):+ - `frontend/src/layouts/SplashLayout.vue` — branding-image parent layout. All its children are now React.+ - `frontend/src/AuthContext.vue` — module-level auth state orchestrator. Mounts both `SessionExpiredSurfaceMount` and the new React `InactiveRemindModal` via `ReactPageMount`.+ - `frontend/src/components/SessionExpiredSurfaceMount.vue` — route-aware mount wrapper for the React session-expired surface.+ - `frontend/src/react/ReactPageMount.vue` — generic Vue→React mount primitive shared across the app.++### Cumulative verification after cleanup+- `pnpm test` — **1248 tests pass** (same count as immediately after the `git pull`; no regression, no new tests added in cleanup).+- `pnpm type-check` — clean.+- `pnpm check` — clean (ESLint, Biome, `check-react-i18n`, `sort_i18n_keys`).+- `pnpm fix` — no outstanding diffs.++### Files deleted in the cleanup round++| File | Reason |+|---|---|+| `frontend/src/components/User/Settings/UserPassword.vue` | 0 callers |+| `frontend/src/views/auth/InactiveRemindModal.vue` | ported to React |+| `frontend/src/views/auth/AuthFooter.vue` | 0 callers after Setup port |+| `frontend/src/views/auth/Signin.vue` | router now references React directly |+| `frontend/src/views/auth/SigninAdmin.vue` | ″ |+| `frontend/src/views/auth/Signup.vue` | ″ |+| `frontend/src/views/auth/PasswordForgot.vue` | ″ |+| `frontend/src/views/auth/PasswordReset.vue` | ″ |+| `frontend/src/views/auth/MultiFactor.vue` | ″ |+| `frontend/src/views/OAuth2Consent.vue` | ″ |+| `frontend/src/views/OAuthCallback.vue` | ″ |+| `frontend/src/views/TwoFactorRequired.vue` | replaced by React `TwoFactorRequiredPage` |+| `frontend/src/views/Setup/Setup.vue` | migrated to React `SetupPage` |+| `frontend/src/views/Setup/AdminSetup.vue` | ″ |+| `frontend/src/views/Setup/WorkspaceMode.vue` | ″ |+| `frontend/src/views/auth/` (directory) | now empty |+| `frontend/src/views/Setup/` (directory) | now empty |++**Total Vue files removed across the whole migration: 19** (4 form components deleted in Phase 8 + 15 in this post-merge cleanup round).++### Post-cleanup followup+- Tests for `SignupPage`, `SetupPage`, `InactiveRemindModal`, `TwoFactorRequiredPage` — not written in this pass.+- `SplashLayout.vue` could be ported to React once its sole consumer (the auth/setup routes) no longer needs the Vue layout wrapping — but migrating it affects the `/setup` + `/oauth2/consent` + `/auth/*` route hierarchy and requires router changes. Not pursued here.diff --git a/docs/plans/2026-04-21-auth-setup-react-migration/plan.md b/docs/plans/2026-04-21-auth-setup-react-migration/plan.mdnew file mode 100644index 0000000000..e92641468d--- /dev/null+++ b/docs/plans/2026-04-21-auth-setup-react-migration/plan.md@@ -0,0 +1,456 @@+## Task List++This is the cumulative plan for `2026-04-21-auth-setup-react-migration`. Completed phases remain in the log; the active phase is what's currently being executed or planned.++---++## Phase 1 — Shared primitives + infrastructure (COMPLETED)++**Task Index**: T1 Register `pages/auth/` glob in mount.ts [S] — T2 Port AuthFooter.vue to React + test [M]++See `execution.md` for the completed log. Deliverables:+- `frontend/src/react/mount.ts` registers `./pages/auth/*.tsx` and lists `"./pages/auth"` in `pageDirs`.+- `frontend/src/react/components/auth/AuthFooter.tsx` + `AuthFooter.test.tsx`.++---++## Phase 2 — `/auth/password-forgot` migration (ACTIVE)++First real page migration. Validates the end-to-end shape: React page under `pages/auth/`, thin Vue shell that mounts it, i18n keys landing alongside their consuming code.++### Implementation approach — file-replacement vs. new-shell++`design.md` §Route-file pattern says "the same route record points at a new Vue shell `frontend/src/views/auth/PasswordForgotPage.vue`". However, the live precedent in the repo (`frontend/src/views/TwoFactorRequired.vue:1-34`) **overwrites the existing Vue file in place** with the mount-shell body, leaving the router import untouched. We follow the live precedent: **replace `PasswordForgot.vue` body in place**, do not create a new shell file, do not touch `frontend/src/router/auth.ts:58`. Design Goal 1 (zero router-guard changes) extends naturally to zero router-file changes.++### Task Index++T3: Add `auth.password-forget` i18n keys to React locales [S] — T4: Create `PasswordForgotPage` React component + test [M] — T5: Replace `PasswordForgot.vue` body with `ReactPageMount` shell [S]++---++### T3: Add `auth.password-forget` i18n keys to React locales [S]++**Objective**: Pre-seed the 5 translation keys the new `PasswordForgotPage.tsx` (T4) will reference, so T4's `t("auth.password-forget.<key>")` calls pass `check-react-i18n.mjs`. T4 technically blocks on T3; this ordering is just for execution clarity — T3 is committed alongside T4 in one PR.++**Files**:+- Modify: `frontend/src/react/locales/en-US.json`, `frontend/src/react/locales/zh-CN.json`, `frontend/src/react/locales/es-ES.json`, `frontend/src/react/locales/ja-JP.json`, `frontend/src/react/locales/vi-VN.json`++**Implementation**:+- In each of the 5 React locale files, add (at the top level) an `"auth"` key with a `"password-forget"` sub-object containing exactly these 5 sub-keys — values copied verbatim from `frontend/src/locales/<locale>.json`'s `auth.password-forget.*`:+ - `failed-to-send-code`, `return-to-sign-in`, `selfhost`, `send-reset-code`, `title`+- Do NOT add any other `auth.*` keys (e.g., `auth.back-to-signin`, `auth.close-window`) — future phases land those.+- Do NOT add `common.email` — already present at `common.email` in all 5 React locale files.+- After edits, run `pnpm --dir frontend fix` — `scripts/sort_i18n_keys.mjs` will re-sort alphabetically.++**Validation**:+- `pnpm --dir frontend check` — expect: `check-react-i18n.mjs` reports all checks passed. Note: this check **will fail** if run before T4 lands, because the added keys are unused. Run the full Phase 2 validation only after T4.++---++### T4: Create `PasswordForgotPage` React component + test [M]++**Objective**: Ship a React page behavior-equivalent to `frontend/src/views/auth/PasswordForgot.vue:1-120`. Consumes the i18n keys from T3.++**Size**: M — one new page file + one new test file. No edits to existing files.++**Files**:+- Create: `frontend/src/react/pages/auth/PasswordForgotPage.tsx`+- Test: `frontend/src/react/pages/auth/PasswordForgotPage.test.tsx`++**Implementation**:++1. In `frontend/src/react/pages/auth/PasswordForgotPage.tsx`:+ - **Imports**: `useEffect`, `useState` from `react`; `useTranslation` from `react-i18next`; `Alert` + `AlertTitle` from `@/react/components/ui/alert`; `Button` from `@/react/components/ui/button`; `Input` from `@/react/components/ui/input`; `useVueState` from `@/react/hooks/useVueState`; `authServiceClientConnect` from `@/connect`; `router` from `@/router`; `AUTH_PASSWORD_RESET_MODULE`, `AUTH_SIGNIN_MODULE` from `@/router/auth`; `useActuatorV1Store`, `pushNotification` from `@/store`; `isValidEmail`, `resolveWorkspaceName` from `@/utils`; `logoFull` (default import) from `@/assets/logo-full.svg`.+ - **Exported function**: `export function PasswordForgotPage()`.+ - **State**: `const [email, setEmail] = useState("");`, `const [isLoading, setIsLoading] = useState(false);`+ - **Store subscriptions** (via `useVueState`):+ - `const passwordResetEnabled = useVueState(() => useActuatorV1Store().serverInfo?.restriction?.passwordResetEnabled ?? false);`+ - `const disallowPasswordSignin = useVueState(() => useActuatorV1Store().serverInfo?.restriction?.disallowPasswordSignin ?? false);`+ - **Mount-time redirect** (matches Vue `onMounted` at `PasswordForgot.vue:89-93`):+ ```+ useEffect(() => {+ if (disallowPasswordSignin) {+ router.replace({ name: AUTH_SIGNIN_MODULE, query: router.currentRoute.value.query });+ }+ }, [disallowPasswordSignin]);+ ```+ - **Submit handler** — early-return if `!isValidEmail(email) || isLoading`; set loading, call `authServiceClientConnect.requestPasswordReset({ email, workspace: resolveWorkspaceName() })`; on success `router.push({ name: AUTH_PASSWORD_RESET_MODULE, query: { ...router.currentRoute.value.query, email } })`; on error `pushNotification({ module: "bytebase", style: "CRITICAL", title: t("auth.password-forget.failed-to-send-code") })`; always clear loading.+ - **JSX** — single `<div className="mx-auto w-full max-w-sm">` matching the Vue template structure:+ - Header block: raw `<img src={logoFull} alt="Bytebase" className="h-12 w-auto" />` (parity with Vue which bypasses `BytebaseLogo` and uses the raw SVG — do NOT substitute the `BytebaseLogo` React component, which adds workspace-custom-logo behavior). Heading `<h2 className="mt-6 text-3xl leading-9 font-extrabold text-main">{t("auth.password-forget.title")}</h2>`.+ - Body (`mt-8 > mt-6 flex flex-col gap-y-4`):+ - If `!passwordResetEnabled`: `<Alert variant="warning"><AlertTitle>{t("auth.password-forget.selfhost")}</AlertTitle></Alert>`.+ - Else: email label + `Input` (`id="forgot-email"`, `type="email"`, `autoComplete="email"`, `placeholder="[email protected]"`, `required`, `onChange={e => setEmail(e.target.value)}`, `onKeyUp={e => e.key === "Enter" && onSubmit()}`), then a primary `Button` spanning full width with `size="lg"`, `disabled={!isValidEmail(email) || isLoading}`, click → `onSubmit`. Label: `{t("auth.password-forget.send-reset-code")}`.+ - Divider + return-to-sign-in link block (matches Vue `PasswordForgot.vue:53-65`): `<a>` styled with `accent-link` whose click calls `router.push({ name: AUTH_SIGNIN_MODULE, query: router.currentRoute.value.query })`. Label: `{t("auth.password-forget.return-to-sign-in")}`.+ - No use of React Router — all navigation through Vue `router` per design.+ - No form `<form>` wrapper with `onSubmit={preventDefault}` — Vue version uses `@click` + `@keyup.enter` without a form. Mirror that.++2. In `frontend/src/react/pages/auth/PasswordForgotPage.test.tsx`:+ - Mock setup (follows `BytebaseLogo.test.tsx` / `AuthFooter.test.tsx` hoisted-mock pattern):+ - `vi.mock("@/react/hooks/useVueState", ...)` — the hook gets called per-subscription; use a single mock that tracks the arg and returns a queued value (or, simpler, mock `useActuatorV1Store` directly).+ - `vi.mock("@/store", ...)` — stub `useActuatorV1Store` returning `{ serverInfo: { restriction: { passwordResetEnabled: ..., disallowPasswordSignin: ... } } }`; stub `pushNotification` as a `vi.fn()`.+ - `vi.mock("@/router", ...)` — `router` with `push`, `replace`, `currentRoute: { value: { query: {} } }` — all as `vi.fn()`.+ - `vi.mock("@/connect", ...)` — `authServiceClientConnect: { requestPasswordReset: vi.fn() }`.+ - `vi.mock("@/assets/logo-full.svg", ...)` — return `"/assets/logo-full.svg"` (follows `BytebaseLogo.test.tsx:22`).+ - `vi.mock("@/utils", ...)` — partial mock keeping `isValidEmail` real (import actual), `resolveWorkspaceName: vi.fn(() => undefined)`.+ - Mock `react-i18next` `useTranslation` to return identity `t` (key-as-value) OR import the real configured `@/react/i18n`. Prefer the identity-t pattern since BytebaseLogo tests don't exercise i18n.+ - **Tests** (use `renderIntoContainer` pattern from `AuthFooter.test.tsx`):+ 1. `"renders self-host warning when passwordResetEnabled is false"` — assert the warning text is present and email input is not.+ 2. `"renders email input and disabled send button when passwordResetEnabled is true"` — assert `input#forgot-email` exists; button text matches `auth.password-forget.send-reset-code`; button has `disabled` attr.+ 3. `"enables submit button for a valid email"` — fire `change` on input with `"[email protected]"`, assert button no longer disabled.+ 4. `"submit calls requestPasswordReset then navigates to password-reset"` — prime mock to resolve; fire click; await microtask; assert `requestPasswordReset` called with `{ email: "[email protected]", workspace: undefined }` and `router.push` called with `{ name: AUTH_PASSWORD_RESET_MODULE, query: { email: "[email protected]" } }`.+ 5. `"shows notification when requestPasswordReset rejects"` — prime mock to reject; fire click; assert `pushNotification` called with `style: "CRITICAL"`.+ 6. `"redirects to signin when disallowPasswordSignin is true"` — stub actuator with `disallowPasswordSignin: true`; render; assert `router.replace` called with `{ name: AUTH_SIGNIN_MODULE, query: {} }`.++**Boundaries**:+- Do NOT touch `frontend/src/views/auth/PasswordForgot.vue` in this task — that is T5.+- Do NOT modify `frontend/src/router/auth.ts` or any other router file.+- Do NOT import `@/react/components/BytebaseLogo` — Vue source uses raw SVG, not the workspace-aware logo.+- Do NOT introduce a new PasswordField/EmailField component; inline `<Input>` suffices (one field).++**Dependencies**: T3 (keys must exist before `check-react-i18n.mjs` passes); no dependency on T5.++**Expected Outcome**:+- `frontend/src/react/pages/auth/PasswordForgotPage.tsx` exists, exports `PasswordForgotPage`.+- 6 tests pass.+- Page is resolvable via `mountReactPage(container, "PasswordForgotPage")` (uses Phase 1's `./pages/auth/*.tsx` glob).++**Validation**:+- `pnpm --dir frontend test -- PasswordForgotPage` — expect: 6 tests pass.+- `pnpm --dir frontend type-check` — expect: exits 0.+- `pnpm --dir frontend fix` — expect: no diffs beyond format.+- `pnpm --dir frontend check` — expect: exits 0 (includes `check-react-i18n.mjs` now that T3 seeded keys and T4 uses them).++---++### T5: Replace `PasswordForgot.vue` body with `ReactPageMount` shell [S]++**Objective**: Flip the `/auth/password-forgot` route to render the new React page, keeping the existing `frontend/src/router/auth.ts:56-59` import unchanged.++**Files**: `frontend/src/views/auth/PasswordForgot.vue`++**Implementation**: Overwrite the file so its entire contents become:++```vue+<template>+ <ReactPageMount page="PasswordForgotPage" />+</template>++<script lang="ts" setup>+import ReactPageMount from "@/react/ReactPageMount.vue";+</script>+```++No props, no callbacks — this page is fully self-contained on the React side. The `SplashLayout` still wraps the route via `router/auth.ts:33 component: SplashLayout`. The shell is a direct parallel to `TwoFactorRequired.vue:1-10` minus the `cancelAction` prop (which MultiFactor/2FA need but PasswordForgot does not).++**Boundaries**:+- Do NOT change `frontend/src/router/auth.ts`.+- Do NOT delete `frontend/src/views/auth/PasswordForgot.vue` — the file stays; the body is the change.++**Dependencies**: T4 (React page must exist before Vue shell references it).++**Expected Outcome**:+- Visiting `/auth/password-forgot` mounts `PasswordForgotPage.tsx` via `ReactPageMount`.+- `git diff frontend/src/views/auth/PasswordForgot.vue` shows the entire body replaced.++**Validation**:+- `pnpm --dir frontend type-check` — expect: exits 0 (`vue-tsc` accepts the new shell).+- `pnpm --dir frontend test` — expect: full suite stays green.+- `pnpm --dir frontend check` — expect: exits 0.+- Verify no live Vue callers of the old PasswordForgot body: `grep -rn "PasswordForgot" frontend/src --include="*.vue" --include="*.ts" --include="*.tsx"` should show only `router/auth.ts` (importing the shell) and the shell itself.++---++---++## Phase 3 — `/auth/mfa` migration (ACTIVE)++Second real page migration. Introduces the first primitive that materially differs from the Vue source — Vue uses naive-ui's `NInputOtp`; React uses the existing shadcn-style `OtpInput` at `frontend/src/react/components/ui/otp-input.tsx`. The `MultiFactor` page also exercises two-mode switching (OTP ↔ recovery code), read of a query param (`mfaTempToken`), and the `authStore.login` call with an MFA-specific request.++### Task Index++T6: Seed `multi-factor.*` + `common.verify` i18n keys to React locales [S] — T7: Create `MultiFactorPage` React component + test [M] — T8: Replace `MultiFactor.vue` body with `ReactPageMount` shell [S]++---++### T6: Seed `multi-factor.*` + `common.verify` i18n keys [S]++**Objective**: Pre-seed the 8 translation keys the new `MultiFactorPage.tsx` (T7) will reference.++**Files**:+- Modify: `frontend/src/react/locales/en-US.json`, `zh-CN.json`, `es-ES.json`, `ja-JP.json`, `vi-VN.json`++**Implementation**:+- Add `"multi-factor"` top-level object with:+ - `auth-code`, `recovery-code`, `self`+ - nested `other-methods.self`+ - nested `other-methods.use-auth-app.{self, description}`+ - nested `other-methods.use-recovery-code.{self, description}`+ - All translations copied verbatim from `frontend/src/locales/<locale>.json` — the Vue master already has the full `multi-factor` sub-tree.+- Add `common.verify` to each React locale (merge into existing `common` object) — verbatim from Vue master.+- Run `node scripts/sort_i18n_keys.mjs` to resort.++**Validation**:+- `node scripts/sort_i18n_keys.mjs` — expect: updates 5 files, leaves 25 unchanged.+- `pnpm check` deferred until T7 consumers land.++---++### T7: Create `MultiFactorPage` React component + test [M]++**Objective**: Ship a React page behavior-equivalent to `frontend/src/views/auth/MultiFactor.vue:1-129`. Consumes keys from T6.++**Size**: M — one page + one test. No edits to existing files.++**Files**:+- Create: `frontend/src/react/pages/auth/MultiFactorPage.tsx`+- Test: `frontend/src/react/pages/auth/MultiFactorPage.test.tsx`++**Implementation**:++1. In `frontend/src/react/pages/auth/MultiFactorPage.tsx`:+ - **Imports**: `useMemo`, `useState` from `react`; `useTranslation` from `react-i18next`; `create` from `@bufbuild/protobuf`; `KeyRound`, `Smartphone` (lucide-react icon equivalents of the Vue `SmartphoneIcon` and `heroicons-outline:key`); `Button` from `@/react/components/ui/button`; `Input` from `@/react/components/ui/input`; `OtpInput` from `@/react/components/ui/otp-input`; `useVueState` from `@/react/hooks/useVueState`; `router` from `@/router`; `useAuthStore` from `@/store`; `LoginRequestSchema` from `@/types/proto-es/v1/auth_service_pb`; `resolveWorkspaceName` from `@/utils`; `logoFull` from `@/assets/logo-full.svg`.+ - **Type**: `type MFAType = "OTP" | "RECOVERY_CODE";`+ - **State**:+ - `const [mfaType, setMfaType] = useState<MFAType>("OTP");`+ - `const [otpCodes, setOtpCodes] = useState<string[]>([]);`+ - `const [recoveryCode, setRecoveryCode] = useState("");`+ - **Query read via `useVueState`**:+ - `const mfaTempToken = useVueState(() => (router.currentRoute.value.query.mfaTempToken as string | undefined) ?? "");`+ - **Challenge description** (derived, translates per `mfaType`):+ ```+ const challengeDescription = useMemo(() => {+ if (mfaType === "OTP") return t("multi-factor.other-methods.use-auth-app.description");+ if (mfaType === "RECOVERY_CODE") return t("multi-factor.other-methods.use-recovery-code.description");+ return "";+ }, [mfaType, t]);+ ```+ - **`challenge` async function**:+ - Build `LoginRequest` via `create(LoginRequestSchema, { mfaTempToken, workspace: resolveWorkspaceName(), ...(mfaType === "OTP" ? { otpCode: otpCodes.join("") } : { recoveryCode }) })`.+ - Call `await useAuthStore().login({ request, redirect: true });`+ - **`onOtpFinish(value: string[])`** — `setOtpCodes(value)` then call `challenge()` (matches Vue's `onOtpCodeFinish` at `MultiFactor.vue:109-112`).+ - **JSX** (mirrors Vue template structure):+ - Outer: `<div className="mx-auto max-w-2xl h-full py-6 flex flex-col justify-center items-center">`.+ - Card: border + shadow-sm + `w-80 p-8 py-6`. Use `div` with tailwind classes (no `NCard` equivalent needed; the Vue card is just styling).+ - Inside card: `<img src={logoFull} alt="Bytebase" className="h-12 w-auto mx-auto mb-8" />`, then a `<form onSubmit>` with flex-column layout.+ - Branch on `mfaType`:+ - `"OTP"`: `Smartphone` icon (`className="w-8 h-auto opacity-60"`), `<p className="my-2 mb-4">{t("multi-factor.auth-code")}</p>`, then `<OtpInput value={otpCodes} onChange={setOtpCodes} onFinish={onOtpFinish} />`.+ - `"RECOVERY_CODE"`: `KeyRound` icon (same class), `<p>{t("multi-factor.recovery-code")}</p>`, then `<Input value={recoveryCode} onChange={e => setRecoveryCode(e.target.value)} placeholder="XXXXXXXXXX" className="w-full" />`.+ - Verify button (primary, `w-full!` equivalent = `className="w-full"`), type="submit", label `{t("common.verify")}`.+ - Challenge description `<p className="textinfolabel mt-2">{challengeDescription}</p>`.+ - `<hr className="my-3" />` separator.+ - "Other methods" section: `<p>{t("multi-factor.other-methods.self")}:</p>` + `<ul>` with two `<li>` entries; each `<li>` is an `<button className="accent-link">` that sets `mfaType`. Show only the one(s) not matching current `mfaType` — mirror Vue `v-if="state.selectedMFAType !== 'OTP'"`.++2. In `frontend/src/react/pages/auth/MultiFactorPage.test.tsx`:+ - Mocks via `vi.hoisted`: `useVueState` (calls getter), `useAuthStore: vi.fn(() => ({ login: vi.fn() }))`, `router` with `currentRoute.value.query`, `resolveWorkspaceName: vi.fn(() => undefined)`, `LoginRequestSchema` pass-through (import actual), `react-i18next` identity-t, `@/assets/logo-full.svg` default. Actually cleanest: mock `@/store` directly so each test can control `login` behavior.+ - Mock `@bufbuild/protobuf` `create` — identity function returning the second arg — so the proto schema doesn't need to be fully mocked.+ - **Tests**:+ 1. `"renders OTP mode by default with Authentication code label"` — assert label text, OtpInput container exists.+ 2. `"switches to RECOVERY_CODE when the user clicks the other method link"` — click first `<button>` inside `ul`, assert recovery-code label visible, 6-digit inputs gone.+ 3. `"switches back to OTP from RECOVERY_CODE"` — set initial to recovery via click, then click to OTP.+ 4. `"challenge submits otpCode when all 6 digits are entered"` — simulate OtpInput finish by directly calling its `onFinish` (via imperative re-entry in OTP mode is tricky in DOM tests; instead use a stub: re-render with pre-filled OTP digits by firing `input` events on 6 inputs). Easier approach: assert on the imperative `challenge` via form-submit path — render, switch not needed, fill 6 digits via descriptor-setter helper, press Verify, assert `login` called with `otpCode: "123456"` and `mfaTempToken: "TOKEN"`.+ 5. `"challenge submits recoveryCode in RECOVERY_CODE mode"` — switch mode, set input value, click Verify, assert `login` called with `recoveryCode: "AAA-BBB"` and no `otpCode`.+ 6. `"reads mfaTempToken from route query"` — configure `currentRoute.value.query.mfaTempToken = "TOKEN"`, assert `login` is called with `mfaTempToken: "TOKEN"`.+ - Use the `setInputValue` helper from `PasswordForgotPage.test.tsx` (copy it inline — small, no shared-helpers barrel yet).++**Boundaries**:+- Do NOT edit `frontend/src/views/auth/MultiFactor.vue` in this task (T8).+- Do NOT change `@/store/modules/v1/auth.ts`.+- Do NOT edit `OtpInput` — reuse as-is.+- Do NOT replicate `NCard` via a new component; inline Tailwind is sufficient for this one page.+- Do NOT introduce a separate `MFAForm` subcomponent; keep logic in the page. Extract only if Phase 7/8 needs it.++**Dependencies**: T6 (i18n keys must exist for `check-react-i18n` to pass once T7 lands).++**Expected Outcome**:+- `MultiFactorPage.tsx` exports `MultiFactorPage`.+- 6 tests pass.+- Page resolvable via `mountReactPage(container, "MultiFactorPage")`.++**Validation**:+- `pnpm test -- MultiFactorPage` — expect: 6 tests pass.+- `pnpm type-check` — expect: exits 0.+- `pnpm fix` — expect: no outstanding diffs.+- `pnpm check` — expect: exits 0.++---++### T8: Replace `MultiFactor.vue` body with `ReactPageMount` shell [S]++**Objective**: Flip `/auth/mfa` to the React page.++**Files**: `frontend/src/views/auth/MultiFactor.vue`++**Implementation**: Overwrite to:++```vue+<template>+ <ReactPageMount page="MultiFactorPage" />+</template>++<script lang="ts" setup>+import ReactPageMount from "@/react/ReactPageMount.vue";+</script>+```++No props — MFA is fully self-contained on the React side (reads `mfaTempToken` from the router query directly, calls `authStore.login` which handles redirects).++**Dependencies**: T7.++**Validation**:+- `pnpm type-check` — expect: exits 0.+- `pnpm test` — expect: full suite green.+- `pnpm check` — expect: exits 0.++---++---++## Phase 4 — `/oauth/callback` + `/oidc/callback` migration (ACTIVE)++Both routes are registered at the top level in `frontend/src/router/auth.ts:74-83` and point at the same Vue file (`frontend/src/views/OAuthCallback.vue`). They bypass `SplashLayout` entirely. Phase 4 produces one React page + one Vue-shell overwrite.++### Notable parity call-outs++- The Vue page has several **hardcoded English status/error strings** (e.g., `"Authentication failed: Invalid callback state. Please try again."`, `"Processing authentication..."`). These strings are not in `frontend/src/locales/`. Per UX-parity goal, the React port preserves them as hardcoded literals. This breaches CLAUDE.md's "no hardcoded display text" rule, but the rule is already broken on the Vue side — fixing it is a separate i18n-hygiene task. The only strings routed through i18n are `auth.close-window` and `auth.back-to-signin` (both already used by the Vue page via `$t(...)`) and the native `common.close`.+- No `NSpin` equivalent is pulled in. Use a lightweight spinner — `Loader2` from `lucide-react` with `animate-spin`, which is the established pattern elsewhere in the React surface.++### Task Index++T9: Seed `auth.close-window` + `auth.back-to-signin` i18n keys [S] — T10: Create `OAuthCallbackPage` React component + test [M] — T11: Replace `OAuthCallback.vue` body with `ReactPageMount` shell [S]++---++### T9: Seed `auth.close-window` + `auth.back-to-signin` i18n keys [S]++**Objective**: Pre-seed the 2 translation keys the new `OAuthCallbackPage.tsx` (T10) will reference via `t(...)`. `common.close` already exists in React locales from a prior migration and does not need to be added.++**Files**:+- Modify: `frontend/src/react/locales/en-US.json`, `zh-CN.json`, `es-ES.json`, `ja-JP.json`, `vi-VN.json`++**Implementation**:+- Merge `auth.close-window` and `auth.back-to-signin` into each React locale's existing `"auth"` object (already has `auth.password-forget.*` from Phase 2). Values copied verbatim from `frontend/src/locales/<locale>.json`'s `auth.close-window` / `auth.back-to-signin`.+- Run `node scripts/sort_i18n_keys.mjs` to resort alphabetically.++**Validation**:+- `node scripts/sort_i18n_keys.mjs` — expect: updates 5 files.+- `pnpm check` deferred until T10 consumers land.++---++### T10: Create `OAuthCallbackPage` React component + test [M]++**Objective**: Ship a React page behavior-equivalent to `frontend/src/views/OAuthCallback.vue:1-205`. Handles both popup-mode (dispatches event to `window.opener` then closes) and redirect-mode (calls `authStore.login`) OAuth/OIDC callbacks.++**Size**: M — one page + one test. No edits to existing files.++**Files**:+- Create: `frontend/src/react/pages/auth/OAuthCallbackPage.tsx`+- Test: `frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx`++**Implementation**:++1. In `frontend/src/react/pages/auth/OAuthCallbackPage.tsx`:+ - **Imports**: `useEffect`, `useState` from `react`; `useTranslation` from `react-i18next`; `create` from `@bufbuild/protobuf`; `Loader2` from `lucide-react`; `Button` from `@/react/components/ui/button`; `useVueState` from `@/react/hooks/useVueState`; `router` from `@/router`; `AUTH_SIGNIN_MODULE` from `@/router/auth`; `useAuthStore` from `@/store`; `LoginRequestSchema` from `@/types/proto-es/v1/auth_service_pb`; `IdentityProviderType` from `@/types/proto-es/v1/idp_service_pb`; `OAuthState`, `OAuthWindowEventPayload` from `@/types/oauth`; `resolveWorkspaceName` from `@/utils`; `clearOAuthState`, `retrieveOAuthState` from `@/utils/sso`.+ - **Local state** (all `useState`):+ - `message: string` — initial `""`+ - `hasError: boolean` — initial `false`+ - `oAuthState: OAuthState | undefined` — initial `undefined`+ - `showCloseButton: boolean` — initial `false`+ - **Payload ref** — build the `{ error: "", code: "" }` payload from route query once inside the mount effect (not stored in state since it doesn't affect rendering). The Vue keeps this in reactive `state.payload` but only reads it during the dispatch; a `useRef<OAuthWindowEventPayload>` suffices.+ - **Mount effect** (`useEffect(..., [])`) — single-run initialization mirroring Vue's `onMounted` at `OAuthCallback.vue:63-114`:+ 1. Read `stateToken` from `router.currentRoute.value.query.state`.+ 2. If invalid: `setHasError(true)`, `setMessage("Authentication failed: Invalid callback state. Please try again.")`, call `triggerAuthCallback(undefined, true)` with the bad-state branch (no `oAuthState`).+ 3. Else retrieve `storedState = retrieveOAuthState(stateToken)`. If null: `setHasError`, `setMessage("Authentication failed: Session expired or invalid. Please try again.")`, trigger.+ 4. Else if `storedState.token !== stateToken`: `setHasError`, `setMessage("Authentication failed: Security validation failed. Please try again.")`, `clearOAuthState(stateToken)`, trigger.+ 5. Else valid: `setOAuthState(storedState)`, `setHasError(false)`, `setMessage("Successfully authorized. Redirecting back to Bytebase...")`, set `payload.code = router.currentRoute.value.query.code as string || ""`, `clearOAuthState(storedState.token)`, trigger.+ - **`triggerAuthCallback(state, isError)`** function (plain async function, not a hook):+ - If `state?.popup`:+ - Try/catch around `window.opener` check → if opener is null/closed: setHasError, `setMessage("Authentication completed, but the parent window is no longer available. Please close this window and try again.")`, setShowCloseButton(true), return.+ - Compute `eventName = isError ? "bb.oauth.unknown" : state.event`.+ - `window.opener.dispatchEvent(new CustomEvent(eventName, { detail: payloadRef.current }))`.+ - Try `window.close()`. After 500ms timeout, if `!window.closed`, setShowCloseButton(true), setMessage(ifError? existing : `"Authentication completed. You can close this window."`).+ - Catch window.close errors: setShowCloseButton(true), setMessage(similar fallback).+ - Outer catch: setHasError, setMessage(`"Authentication completed, but failed to communicate with the parent window. Please close this window and try again."`), setShowCloseButton(true).+ - Else (redirect mode):+ - If `isError || !state`: template already displays the error — return (Vue comment at line 173-175).+ - Else if `state.event.startsWith("bb.oauth.signin")`:+ - `isOidc = state.idpType === IdentityProviderType.OIDC`+ - `idpName = state.event.split(".").pop()` — if falsy, return.+ - `await useAuthStore().login({ request: create(LoginRequestSchema, { idpName, idpContext: { context: { case: isOidc ? "oidcContext" : "oauth2Context", value: { code: payloadRef.current.code } } }, workspace: resolveWorkspaceName() }), redirect: true, redirectUrl: state.redirect })`.+ - **JSX** (mirrors Vue template):+ - Outer wrapper `<div className="p-4">`.+ - If `hasError`: `<div className="mt-2">`, `<div>{message}</div>`, then branch on `oAuthState?.popup` → popup mode renders a `<Button onClick={() => window.close()}>{t("common.close")}</Button>`; non-popup mode renders an `<a>` styled as `btn-normal` (matching Vue class) that pushes to `AUTH_SIGNIN_MODULE` via `router.push`.+ - Else processing state: `<div className="mt-2">` containing `<div className="flex items-center gap-x-2">` with `<Loader2 className="size-4 animate-spin" />` + `<span>{message || "Processing authentication..."}</span>`; if `oAuthState?.popup && showCloseButton`, render close button below.+ - Do NOT wrap in `SplashLayout` — this page is registered at the top level in `router/auth.ts:74-83` without a layout.+ - Do NOT render `BytebaseLogo` or `AuthFooter` — the Vue page doesn't.++2. In `frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx`:+ - Mock strategy (use the `importOriginal` partial-mock pattern established in `MultiFactorPage.test.tsx` for `@bufbuild/protobuf` and the proto modules):+ - `vi.mock("@/react/hooks/useVueState", ...)` — identity (calls the getter).+ - `vi.mock("@/store", ...)` — `useAuthStore: vi.fn(() => ({ login: vi.fn() }))`.+ - `vi.mock("@/router", ...)` — `router.push`, `router.currentRoute.value.query`.+ - `vi.mock("@/utils/sso", ...)` — `retrieveOAuthState`, `clearOAuthState`.+ - `vi.mock("@/utils", async (importOriginal) => ...)` — partial mock of `resolveWorkspaceName`.+ - `vi.mock("@/types/proto-es/v1/idp_service_pb", async (importOriginal) => ...)` — keep real `IdentityProviderType` enum.+ - `vi.mock("@bufbuild/protobuf", ...)` partial — identity `create`.+ - `vi.mock("@/types/proto-es/v1/auth_service_pb", ...)` partial — stub `LoginRequestSchema`.+ - `vi.mock("react-i18next", ...)` — identity `t`.+ - **Tests** (6):+ 1. `"renders error + back-to-signin link when state token is missing"` — `currentRoute.value.query = {}`, render, assert error text visible, `a` with text `auth.back-to-signin` exists.+ 2. `"renders error when stored state not found"` — `currentRoute.value.query = { state: "xyz" }`, `retrieveOAuthState.mockReturnValue(null)`, render, assert session-expired error text.+ 3. `"renders error when stored token mismatch"` — stub `retrieveOAuthState` to return `{ token: "OTHER", ... }`, assert security-validation error + `clearOAuthState` called with `"xyz"`.+ 4. `"redirect mode: valid signin event calls authStore.login with oauth2Context"` — stub state with `event: "bb.oauth.signin.gh"`, `idpType: IdentityProviderType.OAUTH2`, `popup: false`, `redirect: "/home"`. `query.code = "abc"`. Assert `login` called with `{ request: objectContaining({ idpName: "gh", idpContext: { context: { case: "oauth2Context", value: { code: "abc" } } } }), redirect: true, redirectUrl: "/home" }`.+ 5. `"redirect mode: OIDC event uses oidcContext"` — same as #4 but `idpType: IdentityProviderType.OIDC`, assert case `"oidcContext"`.+ 6. `"popup mode: dispatches CustomEvent on window.opener with payload"` — mock `window.opener = { closed: false, dispatchEvent: vi.fn() }` via `Object.defineProperty`. Stub state with `popup: true, event: "bb.oauth.signin.gh", idpType: OAUTH2`. Render. Assert `window.opener.dispatchEvent` called with a `CustomEvent` whose `.detail.code === query.code`.+ - Test helper: restore `window.opener` after each test via `afterEach`.++**Boundaries**:+- Do NOT edit `frontend/src/views/OAuthCallback.vue` (T11).+- Do NOT edit `frontend/src/utils/sso.ts` or `frontend/src/types/oauth.ts`.+- Do NOT add i18n keys for the hardcoded English status strings — parity with Vue source.+- Do NOT introduce a React Router; navigation via Vue `router.push`.++**Dependencies**: T9.++**Validation**:+- `pnpm test -- OAuthCallbackPage` — expect: 6 tests pass.+- `pnpm type-check` — exit 0.+- `pnpm fix` — no diffs.+- `pnpm check` — exit 0.++---++### T11: Replace `OAuthCallback.vue` body with `ReactPageMount` shell [S]++**Objective**: Flip both `/oauth/callback` and `/oidc/callback` routes to the React page. Router entries at `frontend/src/router/auth.ts:74-83` — both already point at `@/views/OAuthCallback.vue`; overwriting the file flips both routes simultaneously.++**Files**: `frontend/src/views/OAuthCallback.vue`++**Implementation**: Overwrite to:++```vue+<template>+ <ReactPageMount page="OAuthCallbackPage" />+</template>++<script lang="ts" setup>+import ReactPageMount from "@/react/ReactPageMount.vue";+</script>+```++**Dependencies**: T10.++**Validation**:+- `pnpm type-check` — exit 0.+- `pnpm test` — full suite green.+- `pnpm check` — exit 0.++---++## Out-of-Scope Tasks (for this `/executing-tasks` invocation)++- **Phases 5–10** (OAuth2Consent, PasswordReset, SigninAdmin, Signin + SigninBridge, Signup, Setup).+- **Consolidating the `auth.*` namespace in React locales.** Only the keys Phase 2 touches are added. Future phases append incrementally.+- **Manual `/auth/password-forgot` UX parity testing in a running dev server.** Flagged as a suggested manual verification step for the PR description, but not part of automated validation.+- **Port of `BytebaseLogo` usage for auth pages.** Signin/Signup use `BytebaseLogo`; PasswordForgot uses raw SVG. Decision deferred to Phase 7/8 when Signin-adjacent code lands.+- **Port of `common.email` from Vue to React locale files.** Already present in React locales.diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjsindex 6a07bfaef2..cd19d0c95a 100644--- a/frontend/scripts/check-react-i18n.mjs+++ b/frontend/scripts/check-react-i18n.mjs@@ -89,6 +89,8 @@ function collectSourceKeys() {const keys = new Set();// Only match single/double quoted strings — template literals with ${} are dynamic keysconst re = /\bt\(\s*["']([^"']+)["']/g;+ // <Trans i18nKey="..."> — react-i18next component-interpolation pattern+ const transRe = /\bi18nKey\s*=\s*["']([^"']+)["']/g;for (const file of files) {const src = readFileSync(file, "utf-8");re.lastIndex = 0;@@ -96,6 +98,10 @@ function collectSourceKeys() {while ((m = re.exec(src))) {keys.add(m[1]);}+ transRe.lastIndex = 0;+ while ((m = transRe.exec(src))) {+ keys.add(m[1]);+ }}return keys;}diff --git a/frontend/src/AuthContext.vue b/frontend/src/AuthContext.vueindex 5c12967b0b..754df62a8b 100644--- a/frontend/src/AuthContext.vue+++ b/frontend/src/AuthContext.vue@@ -6,7 +6,7 @@<template v-if="!isAuthRoute && authStore.isLoggedIn"><!-- Do not show the modal when the user is in auth related pages. --><SessionExpiredSurfaceMount v-if="authStore.unauthenticatedOccurred" />- <InactiveRemindModal v-else />+ <ReactPageMount v-else page="InactiveRemindModal" /></template></template>@@ -15,8 +15,8 @@ import { computed, onMounted, onUnmounted, ref, watch } from "vue";import { useRouter } from "vue-router";import { BBSpin } from "@/bbkit";import SessionExpiredSurfaceMount from "@/components/SessionExpiredSurfaceMount.vue";+import ReactPageMount from "@/react/ReactPageMount.vue";import { isAuthRelatedRoute } from "@/utils/auth";-import InactiveRemindModal from "@/views/auth/InactiveRemindModal.vue";import { t } from "./plugins/i18n";import { WORKSPACE_ROOT_MODULE } from "./router/dashboard/workspaceRoutes";import {diff --git a/frontend/src/components/DemoSigninForm.vue b/frontend/src/components/DemoSigninForm.vuedeleted file mode 100644index ec7053373d..0000000000--- a/frontend/src/components/DemoSigninForm.vue+++ /dev/null@@ -1,70 +0,0 @@-<template>- <form class="flex flex-col gap-y-6 px-1" @submit.prevent="trySignin()">- <div>- <label- for="demo-account"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("auth.sign-in.demo-account") }}- </label>- <div class="mt-1">- <NSelect- id="demo-account"- v-model:value="selectedEmail"- :options="accountOptions"- size="large"- />- </div>- </div>-- <div class="w-full">- <NButton- attr-type="submit"- type="primary"- :loading="loading"- size="large"- style="width: 100%"- >- {{ $t("common.sign-in") }}- </NButton>- </div>- </form>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NButton, NSelect } from "naive-ui";-import { ref } from "vue";-import {- type LoginRequest,- LoginRequestSchema,-} from "@/types/proto-es/v1/auth_service_pb";--defineProps<{- loading: boolean;-}>();--const emit = defineEmits<(event: "signin", payload: LoginRequest) => void>();--// NOSONAR: Not a real credential — fixed demo account password, only used in demo mode.-const DEMO_PASSWORD = "12345678"; // NOSONAR--const accountOptions = [- { label: "Demo (Workspace Admin)", value: "[email protected]" },- { label: "Dev1 (Developer)", value: "[email protected]" },- { label: "DBA1 (DBA)", value: "[email protected]" },- { label: "QA1 (QA)", value: "[email protected]" },-];--const selectedEmail = ref("[email protected]");--const trySignin = () => {- emit(- "signin",- create(LoginRequestSchema, {- email: selectedEmail.value,- password: DEMO_PASSWORD,- })- );-};-</script>diff --git a/frontend/src/components/EmailCodeSigninForm.vue b/frontend/src/components/EmailCodeSigninForm.vuedeleted file mode 100644index 752e8f4d3c..0000000000--- a/frontend/src/components/EmailCodeSigninForm.vue+++ /dev/null@@ -1,195 +0,0 @@-<template>- <form class="flex flex-col gap-y-6 px-1" @submit.prevent="handleSubmit">- <div>- <label- for="email-code-email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("common.email") }}- <RequiredStar />- </label>- <div class="mt-1 rounded-md shadow-xs">- <BBTextField- v-model:value="state.email"- required- :input-props="{- id: 'email-code-email',- autocomplete: 'email',- type: 'email',- }"- placeholder="[email protected]"- :disabled="step === 'code' || emailFromQuery"- />- </div>- </div>-- <div v-if="step === 'code'" class="flex flex-col gap-y-2">- <label class="block text-sm font-medium leading-5 text-control">- {{ $t("auth.sign-in.verification-code") }}- <RequiredStar />- </label>- <div class="text-sm text-control-light">- {{ $t("auth.sign-in.code-sent-hint", { email: state.email }) }}- </div>- <NInputOtp- v-model:value="state.codeParts"- :length="6"- class="email-code-otp w-full"- @finish="handleSubmit"- />- <div class="flex items-center justify-end">- <NButton text :disabled="resendCountdown > 0" @click="sendCode">- {{- resendCountdown > 0- ? $t("auth.sign-in.resend-in", { seconds: resendCountdown })- : $t("auth.sign-in.resend-code")- }}- </NButton>- </div>- </div>-- <div class="w-full">- <NButton- v-if="step === 'email'"- attr-type="button"- type="primary"- :disabled="!isValidEmail(state.email) || state.sending"- :loading="state.sending"- size="large"- style="width: 100%"- @click="sendCode"- >- {{ $t("auth.sign-in.send-code") }}- </NButton>- <NButton- v-else- attr-type="submit"- type="primary"- :disabled="!allowSignin"- :loading="props.loading"- size="large"- style="width: 100%"- >- {{ $t("common.sign-in") }}- </NButton>- </div>- </form>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NButton, NInputOtp } from "naive-ui";-import { computed, onMounted, onUnmounted, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { BBTextField } from "@/bbkit";-import RequiredStar from "@/components/RequiredStar.vue";-import { pushNotification, useAuthStore } from "@/store";-import {- type LoginRequest,- LoginRequestSchema,-} from "@/types/proto-es/v1/auth_service_pb";-import { isValidEmail, resolveWorkspaceName } from "@/utils";--interface LocalState {- email: string;- codeParts: string[];- sending: boolean;-}--const props = defineProps<{- loading: boolean;-}>();--const emit = defineEmits<{- (event: "signin", payload: LoginRequest): void;-}>();--const { t } = useI18n();-const authStore = useAuthStore();--const step = ref<"email" | "code">("email");-const resendCountdown = ref(0);-let countdownTimer: ReturnType<typeof setInterval> | null = null;--const state = reactive<LocalState>({- email: "",- codeParts: [],- sending: false,-});--const emailFromQuery = ref(false);--onMounted(() => {- const url = new URL(window.location.href);- const params = new URLSearchParams(url.search);- const queryEmail = params.get("email") ?? "";- if (queryEmail) {- state.email = queryEmail;- emailFromQuery.value = true;- }-});--onUnmounted(() => {- if (countdownTimer) clearInterval(countdownTimer);-});--const allowSignin = computed(() => {- return state.email && state.codeParts.join("").length === 6;-});--const startCountdown = () => {- resendCountdown.value = 60;- if (countdownTimer) clearInterval(countdownTimer);- countdownTimer = setInterval(() => {- resendCountdown.value -= 1;- if (resendCountdown.value <= 0 && countdownTimer) {- clearInterval(countdownTimer);- countdownTimer = null;- }- }, 1000);-};--const sendCode = async () => {- if (!isValidEmail(state.email) || state.sending || resendCountdown.value > 0)- return;- state.sending = true;- try {- await authStore.sendEmailLoginCode(state.email, resolveWorkspaceName());- step.value = "code";- startCountdown();- } catch (e) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("auth.sign-in.failed-to-send-code", {- error: e,- }),- });- } finally {- state.sending = false;- }-};--const handleSubmit = async () => {- if (step.value === "email") {- await sendCode();- return;- }- const code = state.codeParts.join("");- if (!state.email || code.length !== 6) return;- emit(- "signin",- create(LoginRequestSchema, {- email: state.email,- emailCode: code,- workspace: resolveWorkspaceName(),- })- );-};-</script>--<style scoped>-.email-code-otp :deep(.n-input) {- flex: 1;-}-</style>diff --git a/frontend/src/components/PasswordSigninForm.vue b/frontend/src/components/PasswordSigninForm.vuedeleted file mode 100644index b9e2bad182..0000000000--- a/frontend/src/components/PasswordSigninForm.vue+++ /dev/null@@ -1,150 +0,0 @@-<template>- <form class="flex flex-col gap-y-6 px-1" @submit.prevent="trySignin()">- <div>- <label- for="email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("common.email") }}- <RequiredStar />- </label>- <div class="mt-1 rounded-md shadow-xs">- <BBTextField- v-model:value="state.email"- required- :input-props="{- id: 'email',- autocomplete: 'on',- type: 'email',- }"- placeholder="[email protected]"- />- </div>- </div>-- <div>- <label- for="password"- class="flex justify-between text-sm font-medium leading-5 gap-4 text-control"- >- <div>- {{ $t("common.password") }}- <RequiredStar />- </div>- <router-link- v-if="showForgotPassword"- :to="{- name: AUTH_PASSWORD_FORGOT_MODULE,- query: {- hint: route.query.hint,- },- }"- class="text-sm font-normal text-control-light hover:underline focus:outline-hidden"- tabindex="-1"- >- {{ $t("auth.sign-in.forget-password") }}- </router-link>- </label>- <div- class="relative flex flex-row items-center mt-1 rounded-md shadow-xs"- >- <BBTextField- v-model:value="state.password"- :type="state.showPassword ? 'text' : 'password'"- :input-props="{ id: 'password', autocomplete: 'on' }"- required- />- <div- class="hover:cursor-pointer absolute right-3"- @click="- () => {- state.showPassword = !state.showPassword;- }- "- >- <EyeIcon v-if="state.showPassword" class="w-4 h-4" />- <EyeOffIcon v-else class="w-4 h-4" />- </div>- </div>- </div>-- <div class="w-full">- <NButton- attr-type="submit"- type="primary"- :disabled="!allowSignin"- :loading="loading"- size="large"- style="width: 100%"- >- {{ $t("common.sign-in") }}- </NButton>- </div>- </form>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { EyeIcon, EyeOffIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, onMounted, reactive } from "vue";-import { useRoute } from "vue-router";-import { BBTextField } from "@/bbkit";-import RequiredStar from "@/components/RequiredStar.vue";-import { AUTH_PASSWORD_FORGOT_MODULE } from "@/router/auth";-import {- type LoginRequest,- LoginRequestSchema,-} from "@/types/proto-es/v1/auth_service_pb";-import { resolveWorkspaceName } from "@/utils";--interface LocalState {- email: string;- password: string;- showPassword: boolean;-}--withDefaults(- defineProps<{- showForgotPassword?: boolean;- loading: boolean;- }>(),- {- showForgotPassword: true,- }-);--const emit = defineEmits<{- (event: "signin", payload: LoginRequest): void;-}>();--const route = useRoute();--const state = reactive<LocalState>({- email: "",- password: "",- showPassword: false,-});--onMounted(() => {- const url = new URL(window.location.href);- const params = new URLSearchParams(url.search);- state.email = params.get("email") ?? "";- state.password = params.get("password") ?? "";-});--const allowSignin = computed(() => {- return state.email && state.password;-});--const trySignin = async () => {- emit(- "signin",- create(LoginRequestSchema, {- email: state.email,- password: state.password,- workspace: resolveWorkspaceName(),- })- );-};-</script>diff --git a/frontend/src/components/User/Settings/UserPassword.vue b/frontend/src/components/User/Settings/UserPassword.vuedeleted file mode 100644index da8a1916ca..0000000000--- a/frontend/src/components/User/Settings/UserPassword.vue+++ /dev/null@@ -1,216 +0,0 @@-<template>- <div class="flex flex-col gap-y-6" v-bind="$attrs">- <div :label="$t('settings.profile.password')">- <div>- <label class="block text-sm font-medium leading-5 text-control">- {{ $t("settings.profile.password") }}- <RequiredStar />- </label>- <span- :class="[- 'flex items-center gap-x-1 textinfolabel text-sm!',- passwordHint ? 'text-error!' : '',- ]"- >- {{ $t("settings.profile.password-hint") }}- <NTooltip>- <template #trigger>- <CircleHelpIcon class="w-4" />- </template>- <component :is="passwordRestrictionText" class="text-sm" />- </NTooltip>- <LearnMoreLink- v-if="showLearnMore"- :external="false"- class="text-sm!"- :url="- router.resolve({- name: SETTING_ROUTE_WORKSPACE_GENERAL,- hash: '#account',- }).fullPath- "- />- </span>- </div>- <div class="w-full flex flex-col gap-y-1">- <div class="mt-1 relative flex flex-row items-center">- <NInput- :value="password"- :type="showPassword ? 'text' : 'password'"- :status="passwordHint ? 'error' : undefined"- :input-props="{ autocomplete: 'new-password' }"- :placeholder="$t('common.sensitive-placeholder')"- :disabled="disabled"- @update:value="$emit('update:password', $event)"- />- <div- class="hover:cursor-pointer absolute right-3"- @click="- () => {- showPassword = !showPassword;- }- "- >- <EyeIcon v-if="showPassword" class="w-4 h-4" />- <EyeOffIcon v-else class="w-4 h-4" />- </div>- </div>- </div>- </div>- <div :label="$t('settings.profile.password-confirm')">- <label- for="email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("settings.profile.password-confirm") }}- <RequiredStar />- </label>- <div class="w-full mt-1 flex flex-col justify-start items-start">- <div class="w-full relative flex flex-row items-center">- <NInput- :value="passwordConfirm"- :type="showPassword ? 'text' : 'password'"- :status="passwordMismatch ? 'error' : undefined"- :input-props="{ autocomplete: 'new-password' }"- :placeholder="$t('settings.profile.password-confirm-placeholder')"- :disabled="disabled"- @update:value="$emit('update:passwordConfirm', $event)"- />- <div- class="hover:cursor-pointer absolute right-3"- @click="- () => {- showPassword = !showPassword;- }- "- >- <EyeIcon v-if="showPassword" class="w-4 h-4" />- <EyeOffIcon v-else class="w-4 h-4" />- </div>- </div>- <span v-if="passwordMismatch" class="text-error text-sm mt-1 pl-1">- {{ $t("settings.profile.password-mismatch") }}- </span>- </div>- </div>- </div>-</template>--<script lang="tsx" setup>-import {- CircleAlertIcon,- CircleCheckIcon,- CircleHelpIcon,- EyeIcon,- EyeOffIcon,-} from "lucide-vue-next";-import { NInput, NTooltip } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import RequiredStar from "@/components/RequiredStar.vue";-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";-import { type WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";--const props = withDefaults(- defineProps<{- password: string;- passwordConfirm: string;- passwordRestriction?: WorkspaceProfileSetting_PasswordRestriction;- showLearnMore?: boolean;- disabled?: boolean;- }>(),- {- showLearnMore: true,- }-);--defineEmits<{- (event: "update:password", password: string): void;- (event: "update:passwordConfirm", passwordConfirm: string): void;-}>();--const showPassword = ref<boolean>(false);-const { t } = useI18n();-const router = useRouter();--const passwordCheck = computed(() => {- const minLength = props.passwordRestriction?.minLength ?? 8;- const check: { text: string; matched: boolean }[] = [- {- text: t("settings.general.workspace.password-restriction.min-length", {- min: minLength,- }),- matched: props.password.length >= minLength,- },- ];-- if (props.passwordRestriction?.requireNumber) {- check.push({- text: t("settings.general.workspace.password-restriction.require-number"),- matched: /[0-9]+/.test(props.password),- });- }- if (props.passwordRestriction?.requireUppercaseLetter) {- check.push({- text: t(- "settings.general.workspace.password-restriction.require-uppercase-letter"- ),- matched: /[A-Z]+/.test(props.password),- });- } else if (props.passwordRestriction?.requireLetter) {- check.push({- text: t("settings.general.workspace.password-restriction.require-letter"),- matched: /[a-zA-Z]+/.test(props.password),- });- }- if (props.passwordRestriction?.requireSpecialCharacter) {- check.push({- text: t(- "settings.general.workspace.password-restriction.require-special-character"- ),- matched: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/.test(props.password),- });- }-- return check;-});--const passwordRestrictionText = computed(() => {- return (- <ul class="list-disc">- {passwordCheck.value.map((check, i) => (- <li key={i} class={"flex gap-x-1 items-center"}>- {check.matched ? (- <CircleCheckIcon class={"w-4 text-green-400"} />- ) : (- <CircleAlertIcon class={"w-4 text-red-400"} />- )}- {check.text}- </li>- ))}- </ul>- );-});--const passwordHint = computed(() => {- const pwd = props.password;- if (!pwd) {- return false;- }- return passwordCheck.value.some((check) => !check.matched);-});--const passwordMismatch = computed(() => {- if (!props.password) {- return false;- }- return props.password !== props.passwordConfirm;-});--defineExpose({- passwordHint,- passwordMismatch,-});-</script>diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 406b7e069b..cf56c7ec45 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -137,13 +137,8 @@"verification-code": "Verification code"},"sign-up": {- "accept-terms-and-policy": "I accept Bytebase's {terms} and {policy}",- "admin-account": "admin account",- "admin-title": "Setup {account}","create-admin-account": "Create admin account","existing-user": "Already have an account?",- "privacy-policy": "Privacy Policy",- "terms-of-service": "Terms of Service","title": "Register your account"},"token-expired-description": "Token has expired, please login again",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 21eff574a7..5c8a8a8271 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -137,13 +137,8 @@"verification-code": "Código de verificación"},"sign-up": {- "accept-terms-and-policy": "Acepto los {terms} y {policy} de Bytebase",- "admin-account": "cuenta de administrador",- "admin-title": "Configure su {account}","create-admin-account": "Crear cuenta de administrador","existing-user": "¿Ya tienes una cuenta?",- "privacy-policy": "Política de privacidad",- "terms-of-service": "Términos del servicio","title": "Registre su cuenta"},"token-expired-description": "El token ha expirado, por favor inicia sesión nuevamente",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 65ac1caba6..0a3a67704a 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -137,13 +137,8 @@"verification-code": "認証コード"},"sign-up": {- "accept-terms-and-policy": "Bytebase の {terms} と {policy} に同意します",- "admin-account": "管理者アカウント",- "admin-title": "{account} の登録","create-admin-account": "管理者アカウントを作成","existing-user": "すでにアカウントをお持ちですか?",- "privacy-policy": "プライバシーポリシー",- "terms-of-service": "利用規約","title": "アカウントを登録してください"},"token-expired-description": "トークンの有効期限が切れています。再度ログインしてください。",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 22727dc2d3..b26d3dcd3e 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -137,13 +137,8 @@"verification-code": "Mã xác minh"},"sign-up": {- "accept-terms-and-policy": "Tôi chấp nhận {terms} và {policy} của Bytebase",- "admin-account": "tài khoản quản trị",- "admin-title": "Thiết lập {account}","create-admin-account": "Tạo tài khoản quản trị","existing-user": "Đã có tài khoản?",- "privacy-policy": "Chính sách bảo mật",- "terms-of-service": "Điều khoản dịch vụ","title": "Đăng ký tài khoản của bạn"},"token-expired-description": "Mã thông báo đã hết hạn, vui lòng đăng nhập lại",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 8a8cfc83c2..ae7bc0fea7 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -137,13 +137,8 @@"verification-code": "验证码"},"sign-up": {- "accept-terms-and-policy": "我接受 Bytebase 的{terms}和{policy}",- "admin-account": "管理员账号",- "admin-title": "设置 {account}","create-admin-account": "注册管理员","existing-user": "已有账号?",- "privacy-policy": "隐私政策",- "terms-of-service": "服务条款","title": "注册您的账号"},"token-expired-description": "Token 已过期,请重新登录",diff --git a/frontend/src/react/components/BytebaseLogo.tsx b/frontend/src/react/components/BytebaseLogo.tsxindex e7841b7cfe..37b3fdf466 100644--- a/frontend/src/react/components/BytebaseLogo.tsx+++ b/frontend/src/react/components/BytebaseLogo.tsx@@ -1,10 +1,12 @@import logoFull from "@/assets/logo-full.svg";import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";import { useWorkspaceV1Store } from "@/store";type Props = {/** Optional route name — when set, the logo is wrapped in a link that records the visit. */readonly redirect?: string;+ readonly className?: string;};/**@@ -15,14 +17,19 @@ type Props = {* the SQL Editor Welcome screen. Router-link behavior will be added when* the first React caller needs it.*/-export function BytebaseLogo(_props: Props) {+export function BytebaseLogo({ className }: Props) {const workspaceStore = useWorkspaceV1Store();const customLogo = useVueState(() => workspaceStore.currentWorkspace?.logo ?? "");return (- <div className="shrink-0 max-w-44 flex items-center overflow-hidden">+ <div+ className={cn(+ "shrink-0 max-w-44 flex items-center overflow-hidden",+ className+ )}+ ><span className="h-full w-full select-none flex flex-row justify-center items-center">{customLogo ? (<imgdiff --git a/frontend/src/react/components/auth/AuthFooter.test.tsx b/frontend/src/react/components/auth/AuthFooter.test.tsxnew file mode 100644index 0000000000..7558c456c2--- /dev/null+++ b/frontend/src/react/components/auth/AuthFooter.test.tsx@@ -0,0 +1,154 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ emitStorageChangedEvent: vi.fn(),+ setDocumentTitle: vi.fn(),+ routeTitle: vi.fn((_route: unknown) => "Signin"),+ locale: { value: "en-US" },+ currentRoute: {+ value: {+ meta: {} as { title?: (route: unknown) => string },+ },+ },+}));++const originalLocalStorage = globalThis.localStorage;+const storage = new Map<string, string>();+const localStorageMock = {+ getItem: (key: string) => storage.get(key) ?? null,+ setItem: (key: string, value: string) => {+ storage.set(key, value);+ },+ removeItem: (key: string) => {+ storage.delete(key);+ },+ clear: () => {+ storage.clear();+ },+ key: (index: number) => Array.from(storage.keys())[index] ?? null,+ get length() {+ return storage.size;+ },+};++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/plugins/i18n", () => ({+ default: {+ global: {+ locale: mocks.locale,+ },+ },+}));++vi.mock("@/router", () => ({+ router: {+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/utils", () => ({+ emitStorageChangedEvent: mocks.emitStorageChangedEvent,+ setDocumentTitle: mocks.setDocumentTitle,+}));++vi.mock("@/utils/storage-keys", () => ({+ STORAGE_KEY_LANGUAGE: "bb.language",+}));++let AuthFooter: typeof import("./AuthFooter").AuthFooter;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.locale.value = "en-US";+ mocks.currentRoute.value.meta = {};+ storage.clear();+ Object.defineProperty(globalThis, "localStorage", {+ value: localStorageMock,+ configurable: true,+ });+ ({ AuthFooter } = await import("./AuthFooter"));+});++afterEach(() => {+ Object.defineProperty(globalThis, "localStorage", {+ value: originalLocalStorage,+ configurable: true,+ });+});++describe("AuthFooter", () => {+ test("renders five language links in order", () => {+ mocks.useVueState.mockReturnValue("en-US");+ const { container, render, unmount } = renderIntoContainer(<AuthFooter />);+ render();+ const anchors = Array.from(container.querySelectorAll("a"));+ expect(anchors.map((a) => a.textContent)).toEqual([+ "English",+ "简体中文",+ "Español",+ "日本語",+ "Tiếng việt",+ ]);+ unmount();+ });++ test("highlights the current locale with text-main", () => {+ mocks.useVueState.mockReturnValue("zh-CN");+ const { container, render, unmount } = renderIntoContainer(<AuthFooter />);+ render();+ const anchors = Array.from(container.querySelectorAll("a"));+ const zhAnchor = anchors.find((a) => a.textContent === "简体中文");+ const enAnchor = anchors.find((a) => a.textContent === "English");+ expect(zhAnchor?.className).toContain("text-main");+ expect(enAnchor?.className).not.toContain("text-main");+ unmount();+ });++ test("invokes Vue i18n + storage + title setter on click", () => {+ mocks.useVueState.mockReturnValue("en-US");+ mocks.currentRoute.value.meta = { title: mocks.routeTitle };+ const { container, render, unmount } = renderIntoContainer(<AuthFooter />);+ render();+ const esAnchor = Array.from(container.querySelectorAll("a")).find(+ (a) => a.textContent === "Español"+ );+ expect(esAnchor).toBeDefined();+ act(() => {+ esAnchor?.click();+ });+ expect(mocks.locale.value).toBe("es-ES");+ expect(localStorage.getItem("bb.language")).toBe('"es-ES"');+ expect(mocks.emitStorageChangedEvent).toHaveBeenCalledTimes(1);+ expect(mocks.routeTitle).toHaveBeenCalledTimes(1);+ expect(mocks.setDocumentTitle).toHaveBeenCalledWith("Signin");+ unmount();+ });+});diff --git a/frontend/src/react/components/auth/AuthFooter.tsx b/frontend/src/react/components/auth/AuthFooter.tsxnew file mode 100644index 0000000000..7ae505fc7e--- /dev/null+++ b/frontend/src/react/components/auth/AuthFooter.tsx@@ -0,0 +1,67 @@+import i18n from "@/plugins/i18n";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { emitStorageChangedEvent, setDocumentTitle } from "@/utils";+import { STORAGE_KEY_LANGUAGE } from "@/utils/storage-keys";++type LanguageOption = {+ readonly label: string;+ readonly value: string;+};++const LANGUAGE_LIST: readonly LanguageOption[] = [+ { label: "English", value: "en-US" },+ { label: "简体中文", value: "zh-CN" },+ { label: "Español", value: "es-ES" },+ { label: "日本語", value: "ja-JP" },+ { label: "Tiếng việt", value: "vi-VN" },+];++function resolveLabel(locale: string): string {+ if (locale === "zh-CN" || locale === "zh") return "简体中文";+ if (locale === "es-ES" || locale === "es") return "Español";+ if (locale === "ja-JP" || locale === "ja") return "日本語";+ if (locale === "vi-VN" || locale === "vi") return "Tiếng việt";+ return "English";+}++function setAppLocale(lang: string) {+ i18n.global.locale.value = lang;+ localStorage.setItem(STORAGE_KEY_LANGUAGE, JSON.stringify(lang));+ emitStorageChangedEvent();+ const route = router.currentRoute.value;+ if (route.meta.title) {+ setDocumentTitle(route.meta.title(route));+ }+}++export function AuthFooter() {+ const currentLocale = useVueState(() => i18n.global.locale.value as string);+ const activeLabel = resolveLabel(currentLocale);+ const year = new Date().getFullYear();++ return (+ <div className="absolute left-0 bottom-0 mb-8 text-center w-full">+ <p className="block text-sm text-control-light flex justify-center gap-x-2">+ {LANGUAGE_LIST.map((item) => (+ <a+ key={item.label}+ href="#"+ className={`hover:text-control ${+ item.label === activeLabel ? "text-main" : ""+ }`}+ onClick={(e) => {+ e.preventDefault();+ setAppLocale(item.value);+ }}+ >+ {item.label}+ </a>+ ))}+ </p>+ <p className="text-sm text-control-light mt-1">+ © {year} Bytebase. All rights reserved.+ </p>+ </div>+ );+}diff --git a/frontend/src/react/components/auth/DemoSigninForm.tsx b/frontend/src/react/components/auth/DemoSigninForm.tsxnew file mode 100644index 0000000000..e47b491cf2--- /dev/null+++ b/frontend/src/react/components/auth/DemoSigninForm.tsx@@ -0,0 +1,71 @@+import { create } from "@bufbuild/protobuf";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ type LoginRequest,+ LoginRequestSchema,+} from "@/types/proto-es/v1/auth_service_pb";++type Props = {+ readonly loading: boolean;+ readonly onSignin: (request: LoginRequest) => void;+};++// NOSONAR: Not a real credential — fixed demo account password, only used in demo mode.+const DEMO_PASSWORD = "12345678"; // NOSONAR++const ACCOUNT_OPTIONS = [+ { label: "Demo (Workspace Admin)", value: "[email protected]" },+ { label: "Dev1 (Developer)", value: "[email protected]" },+ { label: "DBA1 (DBA)", value: "[email protected]" },+ { label: "QA1 (QA)", value: "[email protected]" },+];++export function DemoSigninForm({ loading, onSignin }: Props) {+ const { t } = useTranslation();+ const [selectedEmail, setSelectedEmail] = useState("[email protected]");++ const trySignin = (e: React.FormEvent) => {+ e.preventDefault();+ onSignin(+ create(LoginRequestSchema, {+ email: selectedEmail,+ password: DEMO_PASSWORD,+ })+ );+ };++ return (+ <form className="flex flex-col gap-y-6 px-1" onSubmit={trySignin}>+ <div>+ <label+ htmlFor="demo-account"+ className="block text-sm font-medium leading-5 text-control"+ >+ {t("auth.sign-in.demo-account")}+ </label>+ <div className="mt-1">+ <select+ id="demo-account"+ value={selectedEmail}+ onChange={(e) => setSelectedEmail(e.target.value)}+ className="flex h-10 w-full rounded-xs border border-control-border bg-transparent px-3 text-sm text-main focus:outline-hidden"+ >+ {ACCOUNT_OPTIONS.map((opt) => (+ <option key={opt.value} value={opt.value}>+ {opt.label}+ </option>+ ))}+ </select>+ </div>+ </div>++ <div className="w-full">+ <Button type="submit" size="lg" className="w-full" disabled={loading}>+ {t("common.sign-in")}+ </Button>+ </div>+ </form>+ );+}diff --git a/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsx b/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsxnew file mode 100644index 0000000000..b0c54c0513--- /dev/null+++ b/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsx@@ -0,0 +1,143 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ sendEmailLoginCode: vi.fn<+ (email: string, workspace?: string) => Promise<void>+ >(async () => {}),+ resolveWorkspaceName: vi.fn(() => undefined),+ pushNotification: vi.fn(),+}));++vi.mock("@/store", () => ({+ pushNotification: mocks.pushNotification,+ useAuthStore: () => ({+ sendEmailLoginCode: mocks.sendEmailLoginCode,+ }),+}));++vi.mock("@/utils", () => ({+ isValidEmail: (value: string) => /\S+@\S+\.\S+/.test(value),+ resolveWorkspaceName: mocks.resolveWorkspaceName,+}));++vi.mock("@bufbuild/protobuf", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@bufbuild/protobuf")>();+ return {+ ...actual,+ create: (_schema: unknown, data: Record<string, unknown>) => data,+ };+});++vi.mock("@/types/proto-es/v1/auth_service_pb", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/types/proto-es/v1/auth_service_pb")+ >();+ return {+ ...actual,+ LoginRequestSchema: {},+ };+});++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, unknown>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key,+ }),+}));++let EmailCodeSigninForm: typeof import("./EmailCodeSigninForm").EmailCodeSigninForm;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++const setInputValue = (input: HTMLInputElement, value: string) => {+ act(() => {+ const descriptor = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ );+ descriptor?.set?.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+};++beforeEach(async () => {+ vi.clearAllMocks();+ ({ EmailCodeSigninForm } = await import("./EmailCodeSigninForm"));+});++describe("EmailCodeSigninForm", () => {+ test("auto-submits after the sixth OTP digit", async () => {+ const onSignin = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <EmailCodeSigninForm loading={false} onSignin={onSignin} />+ );+ render();++ const emailInput = container.querySelector<HTMLInputElement>(+ 'input[type="email"]'+ );+ expect(emailInput).toBeTruthy();+ setInputValue(emailInput!, "[email protected]");++ const sendCodeButton = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((button) => button.textContent === "auth.sign-in.send-code");+ expect(sendCodeButton).toBeTruthy();+ act(() => {+ sendCodeButton?.click();+ });+ await flushPromises();++ expect(mocks.sendEmailLoginCode).toHaveBeenCalledWith(+ "[email protected]",+ undefined+ );++ const otpInputs = Array.from(+ container.querySelectorAll<HTMLInputElement>('input[inputmode="numeric"]')+ );+ expect(otpInputs).toHaveLength(6);++ otpInputs.forEach((input, index) => {+ setInputValue(input, String(index + 1));+ });++ expect(onSignin).toHaveBeenCalledTimes(1);+ expect(onSignin).toHaveBeenCalledWith({+ email: "[email protected]",+ emailCode: "123456",+ workspace: undefined,+ });++ unmount();+ });+});diff --git a/frontend/src/react/components/auth/EmailCodeSigninForm.tsx b/frontend/src/react/components/auth/EmailCodeSigninForm.tsxnew file mode 100644index 0000000000..59a257274a--- /dev/null+++ b/frontend/src/react/components/auth/EmailCodeSigninForm.tsx@@ -0,0 +1,178 @@+import { create } from "@bufbuild/protobuf";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { OtpInput } from "@/react/components/ui/otp-input";+import { pushNotification, useAuthStore } from "@/store";+import {+ type LoginRequest,+ LoginRequestSchema,+} from "@/types/proto-es/v1/auth_service_pb";+import { isValidEmail, resolveWorkspaceName } from "@/utils";++type Props = {+ readonly loading: boolean;+ readonly onSignin: (request: LoginRequest) => void;+};++export function EmailCodeSigninForm({ loading, onSignin }: Props) {+ const { t } = useTranslation();+ const [step, setStep] = useState<"email" | "code">("email");+ const [email, setEmail] = useState("");+ const [codeParts, setCodeParts] = useState<string[]>([]);+ const [sending, setSending] = useState(false);+ const [emailFromQuery, setEmailFromQuery] = useState(false);+ const [resendCountdown, setResendCountdown] = useState(0);+ const countdownTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);++ useEffect(() => {+ const url = new URL(window.location.href);+ const params = new URLSearchParams(url.search);+ const q = params.get("email") ?? "";+ if (q) {+ setEmail(q);+ setEmailFromQuery(true);+ }+ return () => {+ if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);+ };+ }, []);++ const startCountdown = () => {+ setResendCountdown(60);+ if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);+ countdownTimerRef.current = setInterval(() => {+ setResendCountdown((prev) => {+ if (prev <= 1) {+ if (countdownTimerRef.current) {+ clearInterval(countdownTimerRef.current);+ countdownTimerRef.current = null;+ }+ return 0;+ }+ return prev - 1;+ });+ }, 1000);+ };++ const sendCode = async () => {+ if (!isValidEmail(email) || sending || resendCountdown > 0) return;+ setSending(true);+ try {+ await useAuthStore().sendEmailLoginCode(email, resolveWorkspaceName());+ setStep("code");+ startCountdown();+ } catch (e) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("auth.sign-in.failed-to-send-code", { error: String(e) }),+ });+ } finally {+ setSending(false);+ }+ };++ const submitCode = (parts: string[]) => {+ const code = parts.join("");+ if (!email || code.length !== 6) return;+ onSignin(+ create(LoginRequestSchema, {+ email,+ emailCode: code,+ workspace: resolveWorkspaceName(),+ })+ );+ };++ const handleSubmit = async (e?: React.FormEvent) => {+ if (e) e.preventDefault();+ if (step === "email") {+ await sendCode();+ return;+ }+ submitCode(codeParts);+ };++ const allowSignin = !!email && codeParts.join("").length === 6;++ return (+ <form className="flex flex-col gap-y-6 px-1" onSubmit={handleSubmit}>+ <div>+ <label+ htmlFor="email-code-email"+ className="block text-sm font-medium leading-5 text-control"+ >+ {t("common.email")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="mt-1 rounded-md shadow-xs">+ <Input+ id="email-code-email"+ type="email"+ autoComplete="email"+ placeholder="[email protected]"+ required+ value={email}+ disabled={step === "code" || emailFromQuery}+ onChange={(e) => setEmail(e.target.value)}+ />+ </div>+ </div>++ {step === "code" && (+ <div className="flex flex-col gap-y-2">+ <label className="block text-sm font-medium leading-5 text-control">+ {t("auth.sign-in.verification-code")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="text-sm text-control-light">+ {t("auth.sign-in.code-sent-hint", { email })}+ </div>+ <OtpInput+ value={codeParts}+ onChange={setCodeParts}+ onFinish={submitCode}+ length={6}+ />+ <div className="flex items-center justify-end">+ <button+ type="button"+ className="text-sm text-accent disabled:text-control-light disabled:cursor-not-allowed"+ disabled={resendCountdown > 0}+ onClick={sendCode}+ >+ {resendCountdown > 0+ ? t("auth.sign-in.resend-in", { seconds: resendCountdown })+ : t("auth.sign-in.resend-code")}+ </button>+ </div>+ </div>+ )}++ <div className="w-full">+ {step === "email" ? (+ <Button+ type="button"+ size="lg"+ className="w-full"+ disabled={!isValidEmail(email) || sending}+ onClick={sendCode}+ >+ {t("auth.sign-in.send-code")}+ </Button>+ ) : (+ <Button+ type="submit"+ size="lg"+ className="w-full"+ disabled={!allowSignin || loading}+ >+ {t("common.sign-in")}+ </Button>+ )}+ </div>+ </form>+ );+}diff --git a/frontend/src/react/components/auth/InactiveRemindModal.tsx b/frontend/src/react/components/auth/InactiveRemindModal.tsxnew file mode 100644index 0000000000..6edc85fef4--- /dev/null+++ b/frontend/src/react/components/auth/InactiveRemindModal.tsx@@ -0,0 +1,117 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from "@/react/components/ui/dialog";+import { useVueState } from "@/react/hooks/useVueState";+import { useAuthStore, useCurrentUserV1, useSettingV1Store } from "@/store";+import { storageKeyLastActivity } from "@/utils/storage-keys";++const SHOW_THRESHOLD_MIN = 3;++export function InactiveRemindModal() {+ const { t } = useTranslation();+ const currentUserEmail = useVueState(() => useCurrentUserV1().value.email);+ const inactiveTimeoutInSeconds = useVueState(() =>+ Number(+ useSettingV1Store().workspaceProfile.inactiveSessionTimeout?.seconds ?? 0+ )+ );++ const storageKey = storageKeyLastActivity(currentUserEmail);+ const [nowMS, setNowMS] = useState(() => Date.now());+ const [lastActivityTs, setLastActivityTs] = useState(() => Date.now());+ const logoutTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(() => {+ const read = () => {+ const raw = localStorage.getItem(storageKey);+ if (raw !== null) {+ const parsed = Number(raw);+ if (!Number.isNaN(parsed)) setLastActivityTs(parsed);+ }+ };+ read();+ // Poll for same-tab updates (VueUse writes aren't broadcast as `storage`+ // events in the same tab).+ const pollId = setInterval(read, 1000);+ const onStorage = (e: StorageEvent) => {+ if (e.key === storageKey) read();+ };+ window.addEventListener("storage", onStorage);+ return () => {+ clearInterval(pollId);+ window.removeEventListener("storage", onStorage);+ };+ }, [storageKey]);++ useEffect(() => {+ const id = setInterval(() => setNowMS(Date.now()), 1000);+ return () => clearInterval(id);+ }, []);++ const shouldShow = (() => {+ if (inactiveTimeoutInSeconds <= 0) return false;+ const inactiveSeconds = (nowMS - lastActivityTs) / 1000;+ return inactiveSeconds > inactiveTimeoutInSeconds - SHOW_THRESHOLD_MIN * 60;+ })();++ useEffect(() => {+ if (!shouldShow) {+ if (logoutTimerRef.current) {+ clearTimeout(logoutTimerRef.current);+ logoutTimerRef.current = null;+ }+ return;+ }+ logoutTimerRef.current = setTimeout(+ () => {+ useAuthStore().logout();+ },+ SHOW_THRESHOLD_MIN * 60 * 1000+ );+ return () => {+ if (logoutTimerRef.current) {+ clearTimeout(logoutTimerRef.current);+ logoutTimerRef.current = null;+ }+ };+ }, [shouldShow]);++ const staySignedIn = () => {+ const now = Date.now();+ localStorage.setItem(storageKey, String(now));+ setLastActivityTs(now);+ };++ const logout = () => useAuthStore().logout();++ if (!shouldShow) return null;++ return (+ <Dialog open>+ <DialogContent className="p-4 md:min-w-96 max-w-full">+ <DialogTitle className="font-medium text-lg">+ {t("auth.inactive-modal.title")}+ </DialogTitle>+ <DialogDescription className="textinfo mt-1">+ {t("auth.inactive-modal.description", {+ minutes: SHOW_THRESHOLD_MIN,+ })}+ </DialogDescription>+ <div className="w-full flex items-center justify-end gap-x-2 mt-4">+ <Button variant="ghost" onClick={logout}>+ {t("common.logout")}+ </Button>+ <Button onClick={staySignedIn}>+ {t("auth.inactive-modal.stay-signed-in")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/src/react/components/auth/PasswordSigninForm.tsx b/frontend/src/react/components/auth/PasswordSigninForm.tsxnew file mode 100644index 0000000000..7b7ca827e9--- /dev/null+++ b/frontend/src/react/components/auth/PasswordSigninForm.tsx@@ -0,0 +1,148 @@+import { create } from "@bufbuild/protobuf";+import { Eye, EyeOff } from "lucide-react";+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { router } from "@/router";+import { AUTH_PASSWORD_FORGOT_MODULE } from "@/router/auth";+import {+ type LoginRequest,+ LoginRequestSchema,+} from "@/types/proto-es/v1/auth_service_pb";+import { resolveWorkspaceName } from "@/utils";++type Props = {+ readonly loading: boolean;+ readonly showForgotPassword?: boolean;+ readonly credentialLabel?: string;+ readonly credentialPlaceholder?: string;+ readonly credentialInputType?: "email" | "text";+ readonly credentialAutocomplete?: string;+ readonly onSignin: (request: LoginRequest) => void;+};++export function PasswordSigninForm({+ loading,+ showForgotPassword = true,+ credentialLabel,+ credentialPlaceholder = "[email protected]",+ credentialInputType = "email",+ credentialAutocomplete = "on",+ onSignin,+}: Props) {+ const { t } = useTranslation();+ const [identifier, setIdentifier] = useState("");+ const [password, setPassword] = useState("");+ const [showPassword, setShowPassword] = useState(false);+ const credentialFieldID =+ credentialInputType === "text" ? "username" : "email";++ useEffect(() => {+ const url = new URL(window.location.href);+ const params = new URLSearchParams(url.search);+ setIdentifier(params.get("email") ?? "");+ setPassword(params.get("password") ?? "");+ }, []);++ const allowSignin = identifier && password;++ const trySignin = (e: React.FormEvent) => {+ e.preventDefault();+ onSignin(+ create(LoginRequestSchema, {+ email: identifier,+ password,+ workspace: resolveWorkspaceName(),+ })+ );+ };++ const goToForgot = (e: React.MouseEvent) => {+ e.preventDefault();+ router.push({+ name: AUTH_PASSWORD_FORGOT_MODULE,+ query: { hint: router.currentRoute.value.query.hint },+ });+ };++ return (+ <form className="flex flex-col gap-y-6 px-1" onSubmit={trySignin}>+ <div>+ <label+ htmlFor={credentialFieldID}+ className="block text-sm font-medium leading-5 text-control"+ >+ {credentialLabel ?? t("common.email")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="mt-1 rounded-md shadow-xs">+ <Input+ id={credentialFieldID}+ type={credentialInputType}+ autoComplete={credentialAutocomplete}+ placeholder={credentialPlaceholder}+ required+ value={identifier}+ onChange={(e) => setIdentifier(e.target.value)}+ />+ </div>+ </div>++ <div>+ <label+ htmlFor="password"+ className="flex justify-between text-sm font-medium leading-5 gap-4 text-control"+ >+ <div>+ {t("common.password")}+ <span className="text-error ml-0.5">*</span>+ </div>+ {showForgotPassword && (+ <a+ href="#"+ className="text-sm font-normal text-control-light hover:underline focus:outline-hidden"+ tabIndex={-1}+ onClick={goToForgot}+ >+ {t("auth.sign-in.forget-password")}+ </a>+ )}+ </label>+ <div className="relative flex flex-row items-center mt-1 rounded-md shadow-xs">+ <Input+ id="password"+ type={showPassword ? "text" : "password"}+ autoComplete="current-password"+ required+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ />+ <button+ type="button"+ className="hover:cursor-pointer absolute right-3"+ onClick={() => setShowPassword((v) => !v)}+ aria-label="Toggle password visibility"+ >+ {showPassword ? (+ <Eye className="w-4 h-4" />+ ) : (+ <EyeOff className="w-4 h-4" />+ )}+ </button>+ </div>+ </div>++ <div className="w-full">+ <Button+ type="submit"+ size="lg"+ className="w-full"+ disabled={!allowSignin || loading}+ >+ {t("common.sign-in")}+ </Button>+ </div>+ </form>+ );+}diff --git a/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx b/frontend/src/react/components/auth/SessionExpiredSurface.test.tsxindex 2bb15aff34..b7f9140854 100644--- a/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx+++ b/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx@@ -4,8 +4,8 @@ import { createRoot } from "react-dom/client";import { afterEach, describe, expect, test, vi } from "vitest";import { nextTick } from "vue";-vi.mock("./SigninBridge", () => ({- SigninBridge: () => <button data-testid="signin-bridge">Sign in</button>,+vi.mock("@/react/pages/auth/SigninPage", () => ({+ SigninPage: () => <button data-testid="signin-bridge">Sign in</button>,}));vi.mock("@/store", () => ({diff --git a/frontend/src/react/components/auth/SessionExpiredSurface.tsx b/frontend/src/react/components/auth/SessionExpiredSurface.tsxindex 308502d6ee..b09d818b66 100644--- a/frontend/src/react/components/auth/SessionExpiredSurface.tsx+++ b/frontend/src/react/components/auth/SessionExpiredSurface.tsx@@ -5,7 +5,8 @@ import {LAYER_BACKDROP_CLASS,LAYER_SURFACE_CLASS,} from "@/react/components/ui/layer";-import { SigninBridge } from "./SigninBridge";+import { SigninPage } from "@/react/pages/auth/SigninPage";+import { useAuthStore } from "@/store";export function SessionExpiredSurface({currentPath,@@ -14,6 +15,18 @@ export function SessionExpiredSurface({}) {const { t } = useTranslation();+ const logoutFooter = (+ <div className="mt-4 flex justify-center">+ <button+ type="button"+ className="text-sm text-control-light hover:underline"+ onClick={() => useAuthStore().logout()}+ >+ {t("common.logout")}+ </button>+ </div>+ );+return (<BaseDialog.Root open onOpenChange={() => {}}><BaseDialog.Portal container={getLayerRoot("critical")}>@@ -27,7 +40,27 @@ export function SessionExpiredSurface({<BaseDialog.Title className="sr-only">{t("auth.token-expired-title")}</BaseDialog.Title>- <SigninBridge currentPath={currentPath} />+ <div+ className="bg-white shadow-lg rounded-sm py-3 flex pointer-events-auto flex-col gap-3"+ style={{+ maxWidth: "calc(100vw - 80px)",+ maxHeight: "calc(100vh - 80px)",+ }}+ >+ <div className="px-4 max-h-screen overflow-auto w-full h-full">+ <div className="flex items-center w-auto md:min-w-96 max-w-full h-auto md:py-4">+ <div className="flex flex-col justify-center items-center flex-1 gap-y-2">+ <SigninPage+ redirect={false}+ redirectUrl={currentPath}+ allowSignup={false}+ hideFooter+ footerOverride={logoutFooter}+ />+ </div>+ </div>+ </div>+ </div></BaseDialog.Popup></BaseDialog.Portal></BaseDialog.Root>diff --git a/frontend/src/react/components/auth/SigninBridge.test.tsx b/frontend/src/react/components/auth/SigninBridge.test.tsxdeleted file mode 100644index 3356e6a8ae..0000000000--- a/frontend/src/react/components/auth/SigninBridge.test.tsx+++ /dev/null@@ -1,245 +0,0 @@-import { act } from "react";-import { createRoot } from "react-dom/client";-import { afterEach, describe, expect, test, vi } from "vitest";--const bridgeMocks = vi.hoisted(() => {- type RootComponent = { render?: () => unknown };- const app = {- mount: vi.fn(),- unmount: vi.fn(),- use: vi.fn(),- };- app.use.mockReturnValue(app);-- return {- app,- createApp: vi.fn((_component: RootComponent) => app),- h: vi.fn(),- logout: vi.fn(),- t: vi.fn((key: string) => key),- };-});--vi.mock("vue", async () => {- const actual = await vi.importActual<typeof import("vue")>("vue");- return {- ...actual,- createApp: bridgeMocks.createApp,- h: bridgeMocks.h,- };-});--vi.mock("@/plugins/i18n", () => ({- default: {- global: {- t: bridgeMocks.t,- },- },-}));--vi.mock("@/plugins/naive-ui", () => ({- default: {},-}));--vi.mock("naive-ui", () => ({- NButton: { name: "NButton" },- NConfigProvider: { name: "NConfigProvider" },-}));--vi.mock("@/../naive-ui.config", () => ({- dateLang: { value: "date-lang" },- generalLang: { value: "general-lang" },- themeOverrides: { value: { common: { primaryColor: "#4f46e5" } } },-}));--vi.mock("@/router", () => ({- router: {},-}));--vi.mock("@/store", () => ({- pinia: {},- useAuthStore: () => ({- logout: bridgeMocks.logout,- }),-}));--vi.mock("@/views/auth/Signin.vue", () => ({- default: { name: "Signin" },-}));--import { SigninBridge } from "./SigninBridge";--(- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }-).IS_REACT_ACT_ENVIRONMENT = true;--describe("SigninBridge", () => {- afterEach(() => {- document.body.innerHTML = "";- bridgeMocks.createApp.mockClear();- bridgeMocks.h.mockClear();- bridgeMocks.app.mount.mockClear();- bridgeMocks.app.unmount.mockClear();- bridgeMocks.app.use.mockClear();- bridgeMocks.app.use.mockReturnValue(bridgeMocks.app);- bridgeMocks.logout.mockClear();- bridgeMocks.t.mockClear();- });-- test("wraps signin with Naive theme config and restores the logout footer", () => {- const container = document.createElement("div");- document.body.appendChild(container);- const root = createRoot(container);-- act(() => {- root.render(<SigninBridge currentPath="/instances" />);- });-- const render = bridgeMocks.createApp.mock.calls[0]?.[0]?.render;- expect(render).toBeTypeOf("function");- if (!render) {- throw new Error(- "expected SigninBridge to pass a render function to createApp"- );- }-- render();-- const configProviderCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "NConfigProvider"- );- expect(configProviderCall?.[1]).toEqual({- locale: "general-lang",- dateLocale: "date-lang",- themeOverrides: { common: { primaryColor: "#4f46e5" } },- });- const providerSlots = configProviderCall?.[2] as- | { default?: () => unknown }- | undefined;- expect(providerSlots?.default).toBeTypeOf("function");- providerSlots?.default?.();-- const signinCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "Signin"- );- expect(signinCall).toBeDefined();- expect(signinCall?.[1]).toEqual({- redirect: false,- redirectUrl: "/instances",- allowSignup: false,- });-- const slots = signinCall?.[2] as { footer?: () => unknown } | undefined;- expect(slots?.footer).toBeTypeOf("function");- slots?.footer?.();-- const footerButtonCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "NButton"- );- expect(footerButtonCall?.[1]).toMatchObject({- quaternary: true,- size: "small",- });- const buttonLabel = footerButtonCall?.[2] as (() => unknown) | undefined;- buttonLabel?.();- expect(bridgeMocks.t).toHaveBeenCalledWith("common.logout");-- const onClick = footerButtonCall?.[1]?.onClick as (() => void) | undefined;- onClick?.();- expect(bridgeMocks.logout).toHaveBeenCalledTimes(1);-- act(() => {- root.unmount();- });- });-- test("updates redirectUrl without remounting the Vue signin app", () => {- const container = document.createElement("div");- document.body.appendChild(container);- const root = createRoot(container);-- act(() => {- root.render(<SigninBridge currentPath="/instances" />);- });-- const render = bridgeMocks.createApp.mock.calls[0]?.[0]?.render;- expect(render).toBeTypeOf("function");- if (!render) {- throw new Error(- "expected SigninBridge to pass a render function to createApp"- );- }-- bridgeMocks.h.mockClear();- render();- let configProviderCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "NConfigProvider"- );- let providerSlots = configProviderCall?.[2] as- | { default?: () => unknown }- | undefined;- providerSlots?.default?.();-- let signinCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "Signin"- );- expect(signinCall?.[1]).toMatchObject({- redirectUrl: "/instances",- });-- act(() => {- root.render(<SigninBridge currentPath="/projects/demo" />);- });-- expect(bridgeMocks.createApp).toHaveBeenCalledTimes(1);- expect(bridgeMocks.app.unmount).not.toHaveBeenCalled();-- bridgeMocks.h.mockClear();- render();- configProviderCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "NConfigProvider"- );- providerSlots = configProviderCall?.[2] as- | { default?: () => unknown }- | undefined;- providerSlots?.default?.();- signinCall = bridgeMocks.h.mock.calls.find(- ([component]) =>- typeof component === "object" &&- component !== null &&- "name" in component &&- component.name === "Signin"- );- expect(signinCall?.[1]).toMatchObject({- redirectUrl: "/projects/demo",- });-- act(() => {- root.unmount();- });- });-});diff --git a/frontend/src/react/components/auth/SigninBridge.tsx b/frontend/src/react/components/auth/SigninBridge.tsxdeleted file mode 100644index bccc74a26d..0000000000--- a/frontend/src/react/components/auth/SigninBridge.tsx+++ /dev/null@@ -1,110 +0,0 @@-import { NButton, NConfigProvider } from "naive-ui";-import { useEffect, useRef } from "react";-import { createApp, h, type Ref as VueRef, ref as vueRef } from "vue";-import { dateLang, generalLang, themeOverrides } from "@/../naive-ui.config";-import i18n from "@/plugins/i18n";-import NaiveUI from "@/plugins/naive-ui";-import { router } from "@/router";-import { pinia, useAuthStore } from "@/store";-import Signin from "@/views/auth/Signin.vue";--export function SigninBridge({ currentPath }: { currentPath: string }) {- const containerRef = useRef<HTMLDivElement>(null);- const redirectUrlRef = useRef<VueRef<string> | null>(null);-- useEffect(() => {- if (!containerRef.current) return;- const currentPathState = vueRef(currentPath);- redirectUrlRef.current = currentPathState;-- const renderSignin = () =>- h(- Signin as never,- {- redirect: false,- redirectUrl: currentPathState.value,- allowSignup: false,- },- {- footer: () =>- h(- NButton,- {- quaternary: true,- size: "small",- onClick: () => useAuthStore().logout(),- },- () => i18n.global.t("common.logout")- ),- }- );-- const app = createApp({- render() {- return h(- NConfigProvider,- {- locale: generalLang.value,- dateLocale: dateLang.value,- themeOverrides: themeOverrides.value,- },- {- default: () =>- h(- "div",- {- class:- "bg-white shadow-lg rounded-md py-3 flex pointer-events-auto flex-col gap-3",- style: {- maxWidth: "calc(100vw - 80px)",- maxHeight: "calc(100vh - 80px)",- },- },- [- h(- "div",- {- class: "px-4 max-h-screen overflow-auto w-full h-full",- },- [- h(- "div",- {- class:- "flex items-center w-auto md:min-w-96 max-w-full h-auto md:py-4",- },- [- h(- "div",- {- class:- "flex flex-col justify-center items-center flex-1 gap-y-2",- },- [renderSignin()]- ),- ]- ),- ]- ),- ]- ),- }- );- },- });- app.use(router).use(pinia).use(i18n).use(NaiveUI);- app.mount(containerRef.current);-- return () => {- redirectUrlRef.current = null;- app.unmount();- };- }, []);-- useEffect(() => {- if (!redirectUrlRef.current) return;- redirectUrlRef.current.value = currentPath;- }, [currentPath]);-- return <div ref={containerRef} />;-}diff --git a/frontend/src/react/components/auth/UserPasswordFields.tsx b/frontend/src/react/components/auth/UserPasswordFields.tsxnew file mode 100644index 0000000000..f5cc049e66--- /dev/null+++ b/frontend/src/react/components/auth/UserPasswordFields.tsx@@ -0,0 +1,152 @@+import {+ CircleAlert,+ CircleCheck,+ CircleHelp,+ Eye,+ EyeOff,+} from "lucide-react";+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Input } from "@/react/components/ui/input";+import { Tooltip } from "@/react/components/ui/tooltip";+import type { WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";+import {+ computePasswordValidation,+ type PasswordValidation,+} from "./userPasswordValidation";++type Props = {+ readonly password: string;+ readonly passwordConfirm: string;+ readonly onPasswordChange: (value: string) => void;+ readonly onPasswordConfirmChange: (value: string) => void;+ readonly passwordRestriction?: WorkspaceProfileSetting_PasswordRestriction;+ readonly disabled?: boolean;+};++const CHECK_KEY_TO_I18N: Record<string, string> = {+ "min-length": "settings.general.workspace.password-restriction.min-length",+ "require-number":+ "settings.general.workspace.password-restriction.require-number",+ "require-letter":+ "settings.general.workspace.password-restriction.require-letter",+ "require-uppercase-letter":+ "settings.general.workspace.password-restriction.require-uppercase-letter",+ "require-special-character":+ "settings.general.workspace.password-restriction.require-special-character",+};++export function UserPasswordFields(props: Props) {+ const { t } = useTranslation();+ const [showPassword, setShowPassword] = useState(false);+ const validation: PasswordValidation = computePasswordValidation(+ props.password,+ props.passwordConfirm,+ props.passwordRestriction+ );++ const minLength = props.passwordRestriction?.minLength ?? 8;++ const restrictionList = (+ <ul className="list-disc pl-4">+ {validation.checks.map((check) => (+ <li key={check.key} className="flex gap-x-1 items-center">+ {check.matched ? (+ <CircleCheck className="w-4 text-success" />+ ) : (+ <CircleAlert className="w-4 text-error" />+ )}+ <span>+ {t(CHECK_KEY_TO_I18N[check.key], {+ min: minLength,+ })}+ </span>+ </li>+ ))}+ </ul>+ );++ return (+ <div className="flex flex-col gap-y-6">+ <div>+ <label className="block text-sm font-medium leading-5 text-control">+ {t("settings.profile.password")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <span+ className={`flex items-center gap-x-1 textinfolabel text-sm! ${+ validation.hint ? "text-error!" : ""+ }`}+ >+ {t("settings.profile.password-hint")}+ <Tooltip content={restrictionList}>+ <CircleHelp className="w-4" />+ </Tooltip>+ </span>+ <div className="w-full flex flex-col gap-y-1">+ <div className="mt-1 relative flex flex-row items-center">+ <Input+ type={showPassword ? "text" : "password"}+ value={props.password}+ placeholder={t("common.sensitive-placeholder")}+ autoComplete="new-password"+ disabled={props.disabled}+ aria-invalid={validation.hint ? "true" : undefined}+ onChange={(e) => props.onPasswordChange(e.target.value)}+ className={validation.hint ? "border-error" : ""}+ />+ <button+ type="button"+ className="hover:cursor-pointer absolute right-3"+ onClick={() => setShowPassword((v) => !v)}+ aria-label="Toggle password visibility"+ >+ {showPassword ? (+ <Eye className="w-4 h-4" />+ ) : (+ <EyeOff className="w-4 h-4" />+ )}+ </button>+ </div>+ </div>+ </div>+ <div>+ <label className="block text-sm font-medium leading-5 text-control">+ {t("settings.profile.password-confirm")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="w-full mt-1 flex flex-col justify-start items-start">+ <div className="w-full relative flex flex-row items-center">+ <Input+ type={showPassword ? "text" : "password"}+ value={props.passwordConfirm}+ placeholder={t("settings.profile.password-confirm-placeholder")}+ autoComplete="new-password"+ disabled={props.disabled}+ aria-invalid={validation.mismatch ? "true" : undefined}+ onChange={(e) => props.onPasswordConfirmChange(e.target.value)}+ className={validation.mismatch ? "border-error" : ""}+ />+ <button+ type="button"+ className="hover:cursor-pointer absolute right-3"+ onClick={() => setShowPassword((v) => !v)}+ aria-label="Toggle password visibility"+ >+ {showPassword ? (+ <Eye className="w-4 h-4" />+ ) : (+ <EyeOff className="w-4 h-4" />+ )}+ </button>+ </div>+ {validation.mismatch && (+ <span className="text-error text-sm mt-1 pl-1">+ {t("settings.profile.password-mismatch")}+ </span>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/auth/userPasswordValidation.ts b/frontend/src/react/components/auth/userPasswordValidation.tsnew file mode 100644index 0000000000..ff1b341f55--- /dev/null+++ b/frontend/src/react/components/auth/userPasswordValidation.ts@@ -0,0 +1,57 @@+import type { WorkspaceProfileSetting_PasswordRestriction } from "@/types/proto-es/v1/setting_service_pb";++export type PasswordCheckItem = {+ readonly key: string;+ readonly matched: boolean;+};++export type PasswordValidation = {+ readonly hint: boolean;+ readonly mismatch: boolean;+ readonly checks: readonly PasswordCheckItem[];+};++export function computePasswordValidation(+ password: string,+ passwordConfirm: string,+ restriction?: WorkspaceProfileSetting_PasswordRestriction+): PasswordValidation {+ const minLength = restriction?.minLength ?? 8;+ const checks: PasswordCheckItem[] = [+ { key: "min-length", matched: password.length >= minLength },+ ];++ if (restriction?.requireNumber) {+ checks.push({+ key: "require-number",+ matched: /[0-9]+/.test(password),+ });+ }+ if (restriction?.requireUppercaseLetter) {+ checks.push({+ key: "require-uppercase-letter",+ matched: /[A-Z]+/.test(password),+ });+ } else if (restriction?.requireLetter) {+ checks.push({+ key: "require-letter",+ matched: /[a-zA-Z]+/.test(password),+ });+ }+ if (restriction?.requireSpecialCharacter) {+ checks.push({+ key: "require-special-character",+ matched: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]+/.test(password),+ });+ }++ return {+ hint: password.length > 0 && checks.some((c) => !c.matched),+ mismatch: password.length > 0 && password !== passwordConfirm,+ checks,+ };+}++export function passwordCheckMinLength(minLength: number): number {+ return minLength;+}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex e088ada0c3..edfa089594 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -99,6 +99,60 @@"status": "Status"}},+ "auth": {+ "back-to-signin": "Back to Sign in",+ "close-window": "Close this window",+ "inactive-modal": {+ "description": "You've been inactive for a while. For your security, we'll automatically sign you out in {{minutes}} minutes.",+ "stay-signed-in": "Stay signed in",+ "title": "Your session is about to end"+ },+ "oauth-callback": {+ "invalid-state": "Authentication failed: Invalid callback state. Please try again.",+ "opener-failed": "Authentication completed, but failed to communicate with the parent window. Please close this window and try again.",+ "opener-unavailable": "Authentication completed, but the parent window is no longer available. Please close this window and try again.",+ "please-close": "Authentication completed. Please close this window.",+ "processing": "Processing authentication...",+ "security-failed": "Authentication failed: Security validation failed. Please try again.",+ "session-expired": "Authentication failed: Session expired or invalid. Please try again.",+ "success-close": "Authentication completed. You can close this window.",+ "success-redirecting": "Successfully authorized. Redirecting back to Bytebase..."+ },+ "password-forget": {+ "failed-to-send-code": "Failed to send password reset code. Please try again.",+ "return-to-sign-in": "Return to Sign in",+ "selfhost": "Please contact your Bytebase Admin to reset your password.",+ "send-reset-code": "Send reset code",+ "title": "Forgot your password?"+ },+ "password-reset": {+ "code-label": "Verification code",+ "content": "You need to reset your password according to the password restriction policy.",+ "invalid-or-expired-code": "Invalid or expired code. Please request a new one.",+ "title": "Reset your password"+ },+ "sign-in": {+ "code-sent-hint": "A verification code was sent to {{email}}.",+ "demo-account": "Demo Account",+ "email-code-tab": "Email Code",+ "failed-to-send-code": "Failed to send verification code. {{error}}",+ "forget-password": "Forgot your password?",+ "invited-email": "You've been invited. Please sign in with {{email}}",+ "new-user": "New to Bytebase?",+ "resend-code": "Resend code",+ "resend-in": "Resend in {{seconds}}s",+ "send-code": "Send code",+ "sign-in-with-idp": "Sign in with {{idp}}",+ "verification-code": "Verification code"+ },+ "sign-up": {+ "accept-terms-and-policy": "I accept Bytebase's <terms>Terms of Service</terms> and <policy>Privacy Policy</policy>",+ "admin-title": "Setup <account>admin account</account>",+ "create-admin-account": "Create admin account",+ "existing-user": "Already have an account?",+ "title": "Register your account"+ }+ },"auth.token-expired-title": "Token expired","banner": {"external-url": "Bytebase has not configured --external-url"@@ -148,6 +202,7 @@"address": "Address","admin": "Admin","all": "All",+ "allow": "Allow","approve": "Approve","approved": "Approved","archive": "Archive",@@ -191,6 +246,7 @@"delete-resource": "Delete {{type}}","delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.","deleted": "Deleted",+ "deny": "Deny","description": "Description","deselect-all": "Deselect all","detailed-guide": "detailed guide",@@ -221,6 +277,7 @@"filter-by-name": "Filter by name","from": "From","general": "General",+ "go-back": "Go back","group": "Group","groups": "Groups","history": "History",@@ -238,6 +295,7 @@"leave-without-saving": "Leave without saving?","load-more": "Load more","loading": "Loading",+ "logout": "Logout","manage": "Manage","manually-select": "Manually select","members_one": "Member",@@ -254,6 +312,7 @@"ok": "OK","operations": "Operations","optional": "Optional",+ "or": "or","overview": "Overview","password": "Password","pending": "Pending",@@ -301,6 +360,9 @@"sensitive-placeholder": "Sensitive - write only","setting": "Setting","settings": "Settings",+ "sign-in": "Sign in",+ "sign-in-as-admin": "Sign in as administrator",+ "sign-up": "Sign up","skipped": "Skipped","snapshot": "Snapshot","sql": "SQL",@@ -330,6 +392,7 @@"username": "Username","users": "Users","value": "Value",+ "verify": "Verify","view": "View","view-details": "View Details","warning": "Warning",@@ -1310,6 +1373,29 @@"visit-prjects": "Visit Projects"}},+ "multi-factor": {+ "auth-code": "Authentication code",+ "other-methods": {+ "self": "Other methods",+ "use-auth-app": {+ "description": "Open the two-factor authenticator (TOTP) app on your mobile device to view your authentication code.",+ "self": "Use your authenticator app"+ },+ "use-recovery-code": {+ "description": "If you are unable to access your mobile device, enter one of your recovery codes to verify your identity.",+ "self": "Use a recovery code"+ }+ },+ "recovery-code": "Recovery code"+ },+ "oauth2": {+ "consent": {+ "description": "{{clientName}} is requesting access to your account",+ "permission-access": "Access your Bytebase account with your permissions",+ "permissions": "This application will be able to:",+ "title": "Authorization Request"+ }+ },"plan": {"checks": {"self": "Checks"@@ -2197,6 +2283,26 @@}}},+ "setup": {+ "basic-info": "Basic info",+ "data": {+ "built-in": "Use built-in sample",+ "built-in-desc": "Generate sample project and instances",+ "self-setup": "Setup the project"+ },+ "purposes": {+ "alter-schema": "Alter schema",+ "query-data": "Query data",+ "self": "What's your main purpose with Bytebase?"+ },+ "self": "Setup",+ "skip-setup": "Skip setup",+ "workflow": {+ "self": "What's your workflow with database?",+ "simple": "No complex workflow, just need UI tools",+ "team": "Work with teammates, need CI/CD pipeline"+ }+ },"sql-editor": {"access-grants": "Access Grants","access-type-unmask": "See unmasked sensitive data",@@ -3176,6 +3282,7 @@"messages": {"2fa-disabled": "Two-factor authentication is disabled.","2fa-enabled": "Two-factor authentication is enabled.",+ "2fa-required": "Two-factor authentication is required in your workspace. Please enable it before you can continue.","cannot-disable": "You cannot disable two-factor authentication because your admin requires it in the workspace.","recovery-codes-regenerated": "Recovery codes are regenerated."},diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 12501907ec..c9b184875d 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -99,6 +99,60 @@"status": "Estado"}},+ "auth": {+ "back-to-signin": "Volver a Iniciar sesión",+ "close-window": "Cerrar esta ventana",+ "inactive-modal": {+ "description": "Has estado inactivo un tiempo. Por tu seguridad, cerraremos tu sesión automáticamente en {{minutes}} minutos.",+ "stay-signed-in": "Permanecer conectado",+ "title": "Tu sesión está a punto de terminar"+ },+ "oauth-callback": {+ "invalid-state": "La autenticación falló: estado de devolución de llamada no válido. Inténtalo de nuevo.",+ "opener-failed": "La autenticación se completó, pero no se pudo comunicar con la ventana principal. Cierra esta ventana e inténtalo de nuevo.",+ "opener-unavailable": "La autenticación se completó, pero la ventana principal ya no está disponible. Cierra esta ventana e inténtalo de nuevo.",+ "please-close": "La autenticación se completó. Cierra esta ventana.",+ "processing": "Procesando autenticación...",+ "security-failed": "La autenticación falló: la validación de seguridad falló. Inténtalo de nuevo.",+ "session-expired": "La autenticación falló: la sesión ha expirado o no es válida. Inténtalo de nuevo.",+ "success-close": "La autenticación se completó. Puedes cerrar esta ventana.",+ "success-redirecting": "Autorizado correctamente. Redirigiendo de nuevo a Bytebase..."+ },+ "password-forget": {+ "failed-to-send-code": "No se pudo enviar el código de restablecimiento de contraseña. Inténtalo de nuevo.",+ "return-to-sign-in": "Volver a iniciar sesión",+ "selfhost": "Póngase en contacto con su administrador de Bytebase para restablecer su contraseña.",+ "send-reset-code": "Enviar código de restablecimiento",+ "title": "¿Olvidaste tu contraseña?"+ },+ "password-reset": {+ "code-label": "Código de verificación",+ "content": "Debe restablecer su contraseña de acuerdo con la política de restricción de contraseña.",+ "invalid-or-expired-code": "Código inválido o caducado. Por favor solicita uno nuevo.",+ "title": "Restablecer su contraseña"+ },+ "sign-in": {+ "code-sent-hint": "Se ha enviado un código de verificación a {{email}}.",+ "demo-account": "Demo Account",+ "email-code-tab": "Código por email",+ "failed-to-send-code": "No se pudo enviar el código de verificación. Inténtalo de nuevo.",+ "forget-password": "¿Olvidaste tu contraseña?",+ "invited-email": "Has sido invitado. Inicia sesión con {{email}}",+ "new-user": "¿Nuevo en Bytebase?",+ "resend-code": "Reenviar código",+ "resend-in": "Reenviar en {{seconds}}s",+ "send-code": "Enviar código",+ "sign-in-with-idp": "Iniciar sesión con {{idp}}",+ "verification-code": "Código de verificación"+ },+ "sign-up": {+ "accept-terms-and-policy": "Acepto los <terms>Términos del servicio</terms> y <policy>Política de privacidad</policy> de Bytebase",+ "admin-title": "Configure su <account>cuenta de administrador</account>",+ "create-admin-account": "Crear cuenta de administrador",+ "existing-user": "¿Ya tienes una cuenta?",+ "title": "Registre su cuenta"+ }+ },"auth.token-expired-title": "Token expirado","banner": {"external-url": "Bytebase no ha configurado --external-url"@@ -148,6 +202,7 @@"address": "Dirección","admin": "Admin","all": "Todos",+ "allow": "Permitir","approve": "Approve","approved": "Aprobado","archive": "Archivo",@@ -191,6 +246,7 @@"delete-resource": "Delete {{type}}","delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.","deleted": "Eliminado",+ "deny": "Denegar","description": "Descripción","deselect-all": "Deselect all","detailed-guide": "guía detallada",@@ -221,6 +277,7 @@"filter-by-name": "Filtrar por nombre","from": "Desde","general": "General",+ "go-back": "Volver","group": "Grupo","groups": "Grupos","history": "Historial",@@ -238,6 +295,7 @@"leave-without-saving": "¿Salir sin guardar?","load-more": "Cargar más","loading": "Cargando",+ "logout": "Cerrar sesión","manage": "Administrar","manually-select": "Manually select","members_one": "Miembro",@@ -254,6 +312,7 @@"ok": "OK","operations": "Operaciones","optional": "Optional",+ "or": "o","overview": "Resumen","password": "Contraseña","pending": "Pendiente",@@ -301,6 +360,9 @@"sensitive-placeholder": "Sensible - solo escritura","setting": "Configuración","settings": "Configuraciones",+ "sign-in": "Iniciar sesión",+ "sign-in-as-admin": "Iniciar sesión como administrador",+ "sign-up": "Registrarse","skipped": "Omitido","snapshot": "Instantánea","sql": "SQL",@@ -330,6 +392,7 @@"username": "Nombre de usuario","users": "Usuarios","value": "Valor",+ "verify": "Verificar","view": "Ver","view-details": "Ver Detalles","warning": "Advertencia",@@ -1310,6 +1373,29 @@"visit-prjects": "Visitar Proyectos"}},+ "multi-factor": {+ "auth-code": "Código de autenticación",+ "other-methods": {+ "self": "Otros métodos",+ "use-auth-app": {+ "description": "Abre la aplicación de autenticación de dos factores (TOTP) en tu dispositivo móvil para ver tu código de autenticación.",+ "self": "Usa tu aplicación de autenticación"+ },+ "use-recovery-code": {+ "description": "Si no puedes acceder a tu dispositivo móvil, ingresa uno de tus códigos de recuperación para verificar tu identidad.",+ "self": "Usa un código de recuperación"+ }+ },+ "recovery-code": "Código de recuperación"+ },+ "oauth2": {+ "consent": {+ "description": "{{clientName}} está solicitando acceso a tu cuenta",+ "permission-access": "Acceder a tu cuenta de Bytebase con tus permisos",+ "permissions": "Esta aplicación podrá:",+ "title": "Solicitud de autorización"+ }+ },"plan": {"checks": {"self": "Verificaciones"@@ -2197,6 +2283,26 @@}}},+ "setup": {+ "basic-info": "Información básica",+ "data": {+ "built-in": "Utilice la muestra incorporada",+ "built-in-desc": "Generar proyecto de muestra e instancias",+ "self-setup": "Configurar el proyecto"+ },+ "purposes": {+ "alter-schema": "Alterar esquema",+ "query-data": "Consultar datos",+ "self": "¿Cuál es su propósito principal con Bytebase?"+ },+ "self": "Configuración",+ "skip-setup": "Saltar configuración",+ "workflow": {+ "self": "¿Cuál es su flujo de trabajo con la base de datos?",+ "simple": "No hay un flujo de trabajo complejo, solo se necesitan herramientas de interfaz de usuario",+ "team": "Trabajar con compañeros de equipo, necesita una canalización de CI/CD"+ }+ },"sql-editor": {"access-grants": "Access Grants","access-type-unmask": "See unmasked sensitive data",@@ -3176,6 +3282,7 @@"messages": {"2fa-disabled": "La autenticación de dos factores está desactivada.","2fa-enabled": "La autenticación de dos factores está activada.",+ "2fa-required": "Se requiere autenticación de dos factores en su espacio de trabajo. Actívelo antes de poder continuar.","cannot-disable": "No puede desactivar la autenticación de dos factores porque su administrador la requiere en el espacio de trabajo.","recovery-codes-regenerated": "Los códigos de recuperación se han regenerado."},diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 809dcbae3a..54d1069b3e 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -99,6 +99,60 @@"status": "ステータス"}},+ "auth": {+ "back-to-signin": "サインインに戻る",+ "close-window": "このウィンドウを閉じる",+ "inactive-modal": {+ "description": "しばらく操作がありませんでした。セキュリティのため、{{minutes}}分後に自動的にログアウトします。",+ "stay-signed-in": "ログインしたままにする",+ "title": "セッションの有効期限が近づいています"+ },+ "oauth-callback": {+ "invalid-state": "認証に失敗しました:無効なコールバック状態です。もう一度お試しください。",+ "opener-failed": "認証は完了しましたが、親ウィンドウとの通信に失敗しました。このウィンドウを閉じてもう一度お試しください。",+ "opener-unavailable": "認証は完了しましたが、親ウィンドウを利用できなくなっています。このウィンドウを閉じてもう一度お試しください。",+ "please-close": "認証が完了しました。このウィンドウを閉じてください。",+ "processing": "認証を処理しています...",+ "security-failed": "認証に失敗しました:セキュリティ検証に失敗しました。もう一度お試しください。",+ "session-expired": "認証に失敗しました:セッションが期限切れまたは無効です。もう一度お試しください。",+ "success-close": "認証が完了しました。このウィンドウを閉じることができます。",+ "success-redirecting": "認証に成功しました。Bytebase にリダイレクトしています..."+ },+ "password-forget": {+ "failed-to-send-code": "パスワードリセットコードの送信に失敗しました。もう一度お試しください。",+ "return-to-sign-in": "ログインに戻る",+ "selfhost": "Bytebase 管理者に連絡してパスワードをリセットしてください",+ "send-reset-code": "リセットコードを送信",+ "title": "パスワードをお忘れですか?"+ },+ "password-reset": {+ "code-label": "認証コード",+ "content": "パスワード制限ポリシーに従ってパスワードをリセットする必要があります。",+ "invalid-or-expired-code": "コードが無効または期限切れです。新しいコードをリクエストしてください。",+ "title": "あなたのパスワードをリセット"+ },+ "sign-in": {+ "code-sent-hint": "{{email}} に認証コードを送信しました。",+ "demo-account": "Demo Account",+ "email-code-tab": "メール認証コード",+ "failed-to-send-code": "認証コードの送信に失敗しました。もう一度お試しください。",+ "forget-password": "パスワードを忘れましたか?",+ "invited-email": "招待されました。{{email}} でログインしてください",+ "new-user": "Bytebase を初めて使用しますか?",+ "resend-code": "コードを再送信",+ "resend-in": "{{seconds}}秒後に再送信可能",+ "send-code": "コードを送信",+ "sign-in-with-idp": "{{idp}} 経由でログイン",+ "verification-code": "認証コード"+ },+ "sign-up": {+ "accept-terms-and-policy": "Bytebase の <terms>利用規約</terms> と <policy>プライバシーポリシー</policy> に同意します",+ "admin-title": "<account>管理者アカウント</account> の登録",+ "create-admin-account": "管理者アカウントを作成",+ "existing-user": "すでにアカウントをお持ちですか?",+ "title": "アカウントを登録してください"+ }+ },"auth.token-expired-title": "トークンの期限切れ","banner": {"external-url": "Bytebase は --extern-url を設定していません"@@ -148,6 +202,7 @@"address": "接続先","admin": "管理者","all": "全て",+ "allow": "許可","approve": "Approve","approved": "承認済み","archive": "アーカイブ",@@ -191,6 +246,7 @@"delete-resource": "Delete {{type}}","delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.","deleted": "削除されました",+ "deny": "拒否","description": "説明","deselect-all": "Deselect all","detailed-guide": "詳細ガイド",@@ -221,6 +277,7 @@"filter-by-name": "名前でフィルタリングする","from": "開始","general": "全般",+ "go-back": "戻る","group": "グループ","groups": "グループ","history": "履歴",@@ -238,6 +295,7 @@"leave-without-saving": "変更を保存していませんか?","load-more": "もっと読み込む","loading": "読み込み中",+ "logout": "サインアウト","manage": "管理","manually-select": "Manually select","members_one": "メンバー",@@ -254,6 +312,7 @@"ok": "わかりました","operations": "操作","optional": "Optional",+ "or": "または","overview": "概要","password": "パスワード","pending": "保留中",@@ -301,6 +360,9 @@"sensitive-placeholder": "機密データ - 書き込みのみ","setting": "設定","settings": "設定",+ "sign-in": "ログイン",+ "sign-in-as-admin": "管理者としてサインイン",+ "sign-up": "登録する","skipped": "スキップ","snapshot": "スナップショット","sql": "SQL",@@ -330,6 +392,7 @@"username": "ユーザー名","users": "ユーザー","value": "値",+ "verify": "確認する","view": "表示","view-details": "詳細を表示","warning": "警告する",@@ -1310,6 +1373,29 @@"visit-prjects": "プロジェクトを開く"}},+ "multi-factor": {+ "auth-code": "認証コード",+ "other-methods": {+ "self": "その他の方法",+ "use-auth-app": {+ "description": "モバイル デバイスで Two-Factor Authenticator (TOTP) アプリを開き、認証コードを表示します。",+ "self": "認証アプリを使用する"+ },+ "use-recovery-code": {+ "description": "モバイルデバイスにアクセスできない場合は、回復コードを入力して身元を確認してください。",+ "self": "リカバリーコードを使用する"+ }+ },+ "recovery-code": "リカバリーコード"+ },+ "oauth2": {+ "consent": {+ "description": "{{clientName}} があなたのアカウントへのアクセスを要求しています",+ "permission-access": "あなたの権限で Bytebase アカウントにアクセス",+ "permissions": "このアプリケーションは以下のことができます:",+ "title": "認証リクエスト"+ }+ },"plan": {"checks": {"self": "チェック"@@ -2197,6 +2283,26 @@}}},+ "setup": {+ "basic-info": "基本情報",+ "data": {+ "built-in": "組み込みサンプルを使用する",+ "built-in-desc": "サンプルプロジェクトとインスタンスを生成する",+ "self-setup": "プロジェクトのセットアップ"+ },+ "purposes": {+ "alter-schema": "スキーマの変更",+ "query-data": "クエリデータ",+ "self": "Bytebase の主な目的は何ですか?"+ },+ "self": "設定",+ "skip-setup": "セットアップをスキップ",+ "workflow": {+ "self": "データベースのワークフローは何ですか?",+ "simple": "複雑なワークフローは不要、UIツールだけが必要です",+ "team": "チームメイトと協力し、CI/CD パイプラインが必要"+ }+ },"sql-editor": {"access-grants": "Access Grants","access-type-unmask": "See unmasked sensitive data",@@ -3176,6 +3282,7 @@"messages": {"2fa-disabled": "二要素認証が正常に無効になりました","2fa-enabled": "二要素認証が正常にオンになりました",+ "2fa-required": "管理者は、すべてのユーザーに 2 要素認証を設定するよう要求します。引き続き使用する前に、2 要素認証を設定してください。","cannot-disable": "管理者は、すべてのユーザーに 2 要素認証を設定するよう要求します。 2 要素認証を無効にすることはできません。","recovery-codes-regenerated": "リカバリコードが再生成されました"},diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex d0e1f29a1b..a8ea7bcebb 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -99,6 +99,60 @@"status": "Trạng thái"}},+ "auth": {+ "back-to-signin": "Quay lại Đăng nhập",+ "close-window": "Đóng cửa sổ này",+ "inactive-modal": {+ "description": "Bạn đã không hoạt động trong một thời gian. Để bảo mật cho bạn, chúng tôi sẽ tự động đăng xuất bạn sau {{minutes}} phút nữa.",+ "stay-signed-in": "Tiếp tục duy trì đăng nhập",+ "title": "Phiên của bạn sắp kết thúc"+ },+ "oauth-callback": {+ "invalid-state": "Xác thực thất bại: Trạng thái gọi lại không hợp lệ. Vui lòng thử lại.",+ "opener-failed": "Xác thực đã hoàn tất, nhưng không thể giao tiếp với cửa sổ cha. Vui lòng đóng cửa sổ này và thử lại.",+ "opener-unavailable": "Xác thực đã hoàn tất, nhưng cửa sổ cha không còn khả dụng. Vui lòng đóng cửa sổ này và thử lại.",+ "please-close": "Xác thực đã hoàn tất. Vui lòng đóng cửa sổ này.",+ "processing": "Đang xử lý xác thực...",+ "security-failed": "Xác thực thất bại: Xác minh bảo mật không thành công. Vui lòng thử lại.",+ "session-expired": "Xác thực thất bại: Phiên đã hết hạn hoặc không hợp lệ. Vui lòng thử lại.",+ "success-close": "Xác thực đã hoàn tất. Bạn có thể đóng cửa sổ này.",+ "success-redirecting": "Đã ủy quyền thành công. Đang chuyển hướng về Bytebase..."+ },+ "password-forget": {+ "failed-to-send-code": "Không gửi được mã đặt lại mật khẩu. Vui lòng thử lại.",+ "return-to-sign-in": "Quay lại Đăng nhập",+ "selfhost": "Vui lòng liên hệ với Quản trị viên Bytebase của bạn để đặt lại mật khẩu của bạn.",+ "send-reset-code": "Gửi mã đặt lại",+ "title": "Quên mật khẩu?"+ },+ "password-reset": {+ "code-label": "Mã xác minh",+ "content": "Bạn cần đặt lại mật khẩu của mình theo chính sách hạn chế mật khẩu.",+ "invalid-or-expired-code": "Mã không hợp lệ hoặc đã hết hạn. Vui lòng yêu cầu mã mới.",+ "title": "Đặt lại mật khẩu của bạn"+ },+ "sign-in": {+ "code-sent-hint": "Mã xác minh đã được gửi đến {{email}}.",+ "demo-account": "Demo Account",+ "email-code-tab": "Mã qua email",+ "failed-to-send-code": "Không gửi được mã xác minh. Vui lòng thử lại.",+ "forget-password": "Quên mật khẩu?",+ "invited-email": "Bạn đã được mời. Vui lòng đăng nhập bằng {{email}}",+ "new-user": "Mới sử dụng Bytebase?",+ "resend-code": "Gửi lại mã",+ "resend-in": "Gửi lại sau {{seconds}}s",+ "send-code": "Gửi mã",+ "sign-in-with-idp": "Đăng nhập bằng {{idp}}",+ "verification-code": "Mã xác minh"+ },+ "sign-up": {+ "accept-terms-and-policy": "Tôi chấp nhận <terms>Điều khoản dịch vụ</terms> và <policy>Chính sách bảo mật</policy> của Bytebase",+ "admin-title": "Thiết lập <account>tài khoản quản trị</account>",+ "create-admin-account": "Tạo tài khoản quản trị",+ "existing-user": "Đã có tài khoản?",+ "title": "Đăng ký tài khoản của bạn"+ }+ },"auth.token-expired-title": "Mã thông báo đã hết hạn","banner": {"external-url": "Bytebase chưa được cấu hình --external-url"@@ -148,6 +202,7 @@"address": "Địa chỉ","admin": "Quản trị viên","all": "Tất cả",+ "allow": "Cho phép","approve": "Approve","approved": "Đã phê duyệt","archive": "Lưu trữ",@@ -191,6 +246,7 @@"delete-resource": "Delete {{type}}","delete-resource-description": "Once you delete \"{{name}}\", there is no going back. Please be certain.","deleted": "Đã xóa",+ "deny": "Từ chối","description": "Mô tả","deselect-all": "Deselect all","detailed-guide": "Hướng dẫn chi tiết",@@ -221,6 +277,7 @@"filter-by-name": "Lọc theo tên","from": "Từ","general": "Chung",+ "go-back": "Quay lại","group": "Nhóm","groups": "Nhóm","history": "Lịch sử",@@ -238,6 +295,7 @@"leave-without-saving": "Thoát mà không lưu?","load-more": "Tải thêm","loading": "Đang tải",+ "logout": "Đăng xuất","manage": "Quản lý","manually-select": "Manually select","members_one": "Thành viên",@@ -254,6 +312,7 @@"ok": "OK","operations": "Các thao tác","optional": "Optional",+ "or": "hoặc","overview": "Tổng quan","password": "Mật khẩu","pending": "Đang chờ",@@ -301,6 +360,9 @@"sensitive-placeholder": "Nhạy cảm - Chỉ ghi","setting": "Cài đặt","settings": "Cài đặt",+ "sign-in": "Đăng nhập",+ "sign-in-as-admin": "Đăng nhập với tư cách quản trị viên",+ "sign-up": "Đăng ký","skipped": "Đã bỏ qua","snapshot": "Ảnh chụp nhanh","sql": "SQL",@@ -330,6 +392,7 @@"username": "Tên người dùng","users": "Người dùng","value": "Giá trị",+ "verify": "Xác minh","view": "Xem","view-details": "Xem Chi tiết","warning": "Cảnh báo",@@ -1310,6 +1373,29 @@"visit-prjects": "Truy cập Dự án"}},+ "multi-factor": {+ "auth-code": "Mã xác thực",+ "other-methods": {+ "self": "Các phương pháp khác",+ "use-auth-app": {+ "description": "Mở ứng dụng xác thực hai yếu tố (TOTP) trên thiết bị di động của bạn để xem mã xác thực của bạn.",+ "self": "Sử dụng ứng dụng xác thực của bạn"+ },+ "use-recovery-code": {+ "description": "Nếu bạn không thể truy cập thiết bị di động của mình, hãy nhập một trong các mã khôi phục của bạn để xác minh danh tính của bạn.",+ "self": "Sử dụng mã khôi phục"+ }+ },+ "recovery-code": "Mã khôi phục"+ },+ "oauth2": {+ "consent": {+ "description": "{{clientName}} đang yêu cầu truy cập vào tài khoản của bạn",+ "permission-access": "Truy cập tài khoản Bytebase của bạn với quyền hạn của bạn",+ "permissions": "Ứng dụng này sẽ có thể:",+ "title": "Yêu cầu ủy quyền"+ }+ },"plan": {"checks": {"self": "Kiểm tra"@@ -2197,6 +2283,26 @@}}},+ "setup": {+ "basic-info": "Thông tin cơ bản",+ "data": {+ "built-in": "Sử dụng mẫu tích hợp",+ "built-in-desc": "Tạo dự án mẫu và các trường hợp",+ "self-setup": "Thiết lập dự án"+ },+ "purposes": {+ "alter-schema": "Thay đổi lược đồ",+ "query-data": "Truy vấn dữ liệu",+ "self": "Mục đích chính của bạn khi sử dụng Bytebase là gì?"+ },+ "self": "Thiết lập",+ "skip-setup": "Bỏ qua thiết lập",+ "workflow": {+ "self": "Quy trình làm việc của bạn với cơ sở dữ liệu là gì?",+ "simple": "Không có quy trình làm việc phức tạp, chỉ cần các công cụ UI",+ "team": "Làm việc với đồng đội, cần có đường ống CI/CD"+ }+ },"sql-editor": {"access-grants": "Access Grants","access-type-unmask": "See unmasked sensitive data",@@ -3176,6 +3282,7 @@"messages": {"2fa-disabled": "Xác thực hai yếu tố bị tắt.","2fa-enabled": "Xác thực hai yếu tố được bật.",+ "2fa-required": "Xác thực hai yếu tố là bắt buộc trong không gian làm việc của bạn. Vui lòng bật nó trước khi bạn có thể tiếp tục.","cannot-disable": "Bạn không thể tắt xác thực hai yếu tố vì quản trị viên của bạn yêu cầu nó trong không gian làm việc.","recovery-codes-regenerated": "Mã khôi phục được tạo lại."},diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex df2c61ad85..98df725dd1 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -99,6 +99,60 @@"status": "状态"}},+ "auth": {+ "back-to-signin": "返回登录页面",+ "close-window": "关闭此窗口",+ "inactive-modal": {+ "description": "您已有一段时间未活动。为了您的安全,我们将在{{minutes}}分钟后自动退出您的登录。",+ "stay-signed-in": "保持登录状态",+ "title": "您的会话即将结束"+ },+ "oauth-callback": {+ "invalid-state": "认证失败:无效的回调状态。请重试。",+ "opener-failed": "认证已完成,但与父窗口通信失败。请关闭此窗口并重试。",+ "opener-unavailable": "认证已完成,但父窗口不再可用。请关闭此窗口并重试。",+ "please-close": "认证已完成。请关闭此窗口。",+ "processing": "正在处理认证……",+ "security-failed": "认证失败:安全验证失败。请重试。",+ "session-expired": "认证失败:会话已过期或无效。请重试。",+ "success-close": "认证已完成。您可以关闭此窗口。",+ "success-redirecting": "授权成功。正在跳转回 Bytebase……"+ },+ "password-forget": {+ "failed-to-send-code": "发送密码重置验证码失败,请重试。",+ "return-to-sign-in": "返回登录",+ "selfhost": "请联系您的 Bytebase 管理员重置密码",+ "send-reset-code": "发送重置验证码",+ "title": "忘记了您的密码?"+ },+ "password-reset": {+ "code-label": "验证码",+ "content": "依据密码限制策略,您需要重置登录密码。",+ "invalid-or-expired-code": "验证码无效或已过期,请重新申请。",+ "title": "重置您的密码"+ },+ "sign-in": {+ "code-sent-hint": "验证码已发送至 {{email}}。",+ "demo-account": "Demo Account",+ "email-code-tab": "邮箱验证码",+ "failed-to-send-code": "发送验证码失败,请重试。",+ "forget-password": "忘记密码?",+ "invited-email": "您已被邀请,请使用 {{email}} 登录",+ "new-user": "第一次使用 Bytebase?",+ "resend-code": "重新发送验证码",+ "resend-in": "{{seconds}} 秒后重新发送",+ "send-code": "发送验证码",+ "sign-in-with-idp": "通过 {{idp}} 登录",+ "verification-code": "验证码"+ },+ "sign-up": {+ "accept-terms-and-policy": "我接受 Bytebase 的<terms>服务条款</terms>和<policy>隐私政策</policy>",+ "admin-title": "设置 <account>管理员账号</account>",+ "create-admin-account": "注册管理员",+ "existing-user": "已有账号?",+ "title": "注册您的账号"+ }+ },"auth.token-expired-title": "令牌已过期","banner": {"external-url": "Bytebase 还没有配置 --external-url"@@ -148,6 +202,7 @@"address": "地址","admin": "管理员","all": "全部",+ "allow": "允许","approve": "批准","approved": "已批准","archive": "归档",@@ -191,6 +246,7 @@"delete-resource": "删除{{type}}","delete-resource-description": "删除「{{name}}」后将无法恢复,请确认。","deleted": "已删除",+ "deny": "拒绝","description": "描述","deselect-all": "Deselect all","detailed-guide": "详细指南",@@ -221,6 +277,7 @@"filter-by-name": "按名称过滤","from": "从","general": "通用",+ "go-back": "返回","group": "组","groups": "分组","history": "历史记录",@@ -238,6 +295,7 @@"leave-without-saving": "不保存变动?","load-more": "加载更多","loading": "加载中",+ "logout": "登出","manage": "管理","manually-select": "Manually select","members_one": "成员",@@ -254,6 +312,7 @@"ok": "OK","operations": "操作","optional": "Optional",+ "or": "或者","overview": "概览","password": "密码","pending": "待审批",@@ -301,6 +360,9 @@"sensitive-placeholder": "敏感数据 - 仅写入","setting": "设置","settings": "设置",+ "sign-in": "登录",+ "sign-in-as-admin": "以管理员身份登录",+ "sign-up": "注册","skipped": "已跳过","snapshot": "快照","sql": "SQL",@@ -330,6 +392,7 @@"username": "用户名","users": "用户","value": "值",+ "verify": "验证","view": "查看","view-details": "查看详情","warning": "警告",@@ -1310,6 +1373,29 @@"visit-prjects": "访问项目"}},+ "multi-factor": {+ "auth-code": "认证码",+ "other-methods": {+ "self": "其他方法",+ "use-auth-app": {+ "description": "在您的移动设备上打开双重认证器(TOTP)应用程序,查看认证码。",+ "self": "使用身份验证器应用程序"+ },+ "use-recovery-code": {+ "description": "如果您无法访问您的移动设备,请输入一个恢复码来验证您的身份。",+ "self": "使用恢复码"+ }+ },+ "recovery-code": "恢复码"+ },+ "oauth2": {+ "consent": {+ "description": "{{clientName}} 正在请求访问您的账户",+ "permission-access": "使用您的权限访问您的 Bytebase 账户",+ "permissions": "此应用程序将能够:",+ "title": "授权请求"+ }+ },"plan": {"checks": {"self": "检查"@@ -2197,6 +2283,26 @@}}},+ "setup": {+ "basic-info": "基本信息",+ "data": {+ "built-in": "使用内置示例",+ "built-in-desc": "生成示例项目和实例",+ "self-setup": "设置项目"+ },+ "purposes": {+ "alter-schema": "变更 Schema",+ "query-data": "查询数据",+ "self": "您使用 Bytebase 的主要目的是什么?"+ },+ "self": "设置",+ "skip-setup": "跳过设置",+ "workflow": {+ "self": "您使用数据库的工作流程是怎样的?",+ "simple": "无需复杂的工作流程,需要 UI 工具",+ "team": "与队友合作,需要 CI/CD 工作流"+ }+ },"sql-editor": {"access-grants": "访问授权","access-type-unmask": "See unmasked sensitive data",@@ -3176,6 +3282,7 @@"messages": {"2fa-disabled": "双重认证禁用成功","2fa-enabled": "双重认证开启成功",+ "2fa-required": "您的管理员要求所有用户配置双重认证。请先配置双重认证,才能继续使用。","cannot-disable": "您的管理员要求所有用户配置双重认证。您无法禁用双重认证。","recovery-codes-regenerated": "恢复码已经重新生成"},diff --git a/frontend/src/react/mount.ts b/frontend/src/react/mount.tsindex d1b5930a58..684a4131f4 100644--- a/frontend/src/react/mount.ts+++ b/frontend/src/react/mount.ts@@ -6,9 +6,11 @@ const pluginComponentLoaders = import.meta.glob("./plugins/agent/components/AgentWindow.tsx");const workspacePageLoaders = import.meta.glob("./pages/workspace/*.tsx");-const authComponentLoaders = import.meta.glob(- "./components/auth/SessionExpiredSurface.tsx"-);+const authPageLoaders = import.meta.glob("./pages/auth/*.tsx");+const authComponentLoaders = import.meta.glob([+ "./components/auth/SessionExpiredSurface.tsx",+ "./components/auth/InactiveRemindModal.tsx",+]);const sqlEditorComponentLoaders = import.meta.glob("./components/sql-editor/*.tsx");@@ -17,6 +19,7 @@ const pageLoaders = {...projectPageLoaders,...pluginComponentLoaders,...workspacePageLoaders,+ ...authPageLoaders,...authComponentLoaders,...sqlEditorComponentLoaders,};@@ -58,6 +61,7 @@ const pageDirs = ["./pages/project","./plugins/agent/components","./pages/workspace",+ "./pages/auth","./components/auth","./components/sql-editor",];diff --git a/frontend/src/react/pages/auth/MultiFactorPage.test.tsx b/frontend/src/react/pages/auth/MultiFactorPage.test.tsxnew file mode 100644index 0000000000..074eee75ab--- /dev/null+++ b/frontend/src/react/pages/auth/MultiFactorPage.test.tsx@@ -0,0 +1,261 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),+ login: vi.fn<(payload: unknown) => Promise<void>>(async () => {}),+ useAuthStore: vi.fn(),+ currentRoute: {+ value: { query: {} as Record<string, string> },+ },+ resolveWorkspaceName: vi.fn(() => undefined),+}));+mocks.useAuthStore.mockImplementation(() => ({ login: mocks.login }));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useAuthStore: mocks.useAuthStore,+}));++vi.mock("@/router", () => ({+ router: {+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/utils", async () => {+ const actual = await vi.importActual<typeof import("@/utils")>("@/utils");+ return {+ ...actual,+ resolveWorkspaceName: mocks.resolveWorkspaceName,+ };+});++vi.mock("@/assets/logo-full.svg", () => ({+ default: "/assets/logo-full.svg",+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock("@bufbuild/protobuf", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@bufbuild/protobuf")>();+ return {+ ...actual,+ create: (_schema: unknown, data: Record<string, unknown>) => data,+ };+});++vi.mock("@/types/proto-es/v1/auth_service_pb", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/types/proto-es/v1/auth_service_pb")+ >();+ return {+ ...actual,+ LoginRequestSchema: {},+ };+});++let MultiFactorPage: typeof import("./MultiFactorPage").MultiFactorPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++const setInputValue = (input: HTMLInputElement, value: string) => {+ act(() => {+ const descriptor = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ );+ descriptor?.set?.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.currentRoute.value.query = {};+ mocks.login.mockResolvedValue(undefined);+ ({ MultiFactorPage } = await import("./MultiFactorPage"));+});++describe("MultiFactorPage", () => {+ test("renders OTP mode by default with Authentication code label", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MultiFactorPage />+ );+ render();+ expect(container.textContent).toContain("multi-factor.auth-code");+ // 6 OTP inputs present+ const otpInputs = container.querySelectorAll('input[inputmode="numeric"]');+ expect(otpInputs.length).toBe(6);+ unmount();+ });++ test("switches to RECOVERY_CODE when the user clicks the other method link", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MultiFactorPage />+ );+ render();+ const switchBtn = Array.from(container.querySelectorAll("button")).find(+ (b) =>+ b.textContent?.includes(+ "multi-factor.other-methods.use-recovery-code.self"+ )+ );+ expect(switchBtn).toBeDefined();+ act(() => {+ switchBtn?.click();+ });+ expect(container.textContent).toContain("multi-factor.recovery-code");+ const otpInputs = container.querySelectorAll('input[inputmode="numeric"]');+ expect(otpInputs.length).toBe(0);+ unmount();+ });++ test("switches back to OTP from RECOVERY_CODE", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MultiFactorPage />+ );+ render();+ const toRecovery = Array.from(container.querySelectorAll("button")).find(+ (b) =>+ b.textContent?.includes(+ "multi-factor.other-methods.use-recovery-code.self"+ )+ );+ act(() => {+ toRecovery?.click();+ });+ const toOtp = Array.from(container.querySelectorAll("button")).find((b) =>+ b.textContent?.includes("multi-factor.other-methods.use-auth-app.self")+ );+ expect(toOtp).toBeDefined();+ act(() => {+ toOtp?.click();+ });+ const otpInputs = container.querySelectorAll('input[inputmode="numeric"]');+ expect(otpInputs.length).toBe(6);+ unmount();+ });++ test("challenge submits otpCode when all 6 digits are entered and Verify is pressed", async () => {+ mocks.currentRoute.value.query = { mfaTempToken: "TOKEN" };+ const { container, render, unmount } = renderIntoContainer(+ <MultiFactorPage />+ );+ render();+ const otpInputs = Array.from(+ container.querySelectorAll<HTMLInputElement>('input[inputmode="numeric"]')+ );+ expect(otpInputs.length).toBe(6);+ "123456".split("").forEach((digit, i) => {+ setInputValue(otpInputs[i], digit);+ });+ await flushPromises();+ expect(mocks.login).toHaveBeenCalledTimes(1);+ expect(mocks.login).toHaveBeenCalledWith({+ request: expect.objectContaining({+ mfaTempToken: "TOKEN",+ otpCode: "123456",+ }),+ redirect: true,+ });+ unmount();+ });++ test("challenge submits recoveryCode in RECOVERY_CODE mode", async () => {+ mocks.currentRoute.value.query = { mfaTempToken: "TOKEN" };+ const { container, render, unmount } = renderIntoContainer(+ <MultiFactorPage />+ );+ render();+ const toRecovery = Array.from(container.querySelectorAll("button")).find(+ (b) =>+ b.textContent?.includes(+ "multi-factor.other-methods.use-recovery-code.self"+ )+ );+ act(() => {+ toRecovery?.click();+ });+ const recoveryInput = container.querySelector<HTMLInputElement>(+ 'input[placeholder="XXXXXXXXXX"]'+ );+ expect(recoveryInput).not.toBeNull();+ setInputValue(recoveryInput!, "AAA-BBB");+ const form = container.querySelector("form");+ expect(form).not.toBeNull();+ act(() => {+ form!.dispatchEvent(+ new Event("submit", { bubbles: true, cancelable: true })+ );+ });+ await flushPromises();+ expect(mocks.login).toHaveBeenCalledTimes(1);+ const callArg = mocks.login.mock.calls[0]?.[0] as {+ request: {+ recoveryCode?: string;+ otpCode?: string;+ mfaTempToken: string;+ };+ };+ expect(callArg.request.mfaTempToken).toBe("TOKEN");+ expect(callArg.request.recoveryCode).toBe("AAA-BBB");+ expect(callArg.request.otpCode).toBeUndefined();+ unmount();+ });++ test("reads mfaTempToken from route query", async () => {+ mocks.currentRoute.value.query = { mfaTempToken: "FROM-QUERY" };+ const { container, render, unmount } = renderIntoContainer(+ <MultiFactorPage />+ );+ render();+ const otpInputs = Array.from(+ container.querySelectorAll<HTMLInputElement>('input[inputmode="numeric"]')+ );+ "999999".split("").forEach((digit, i) => {+ setInputValue(otpInputs[i], digit);+ });+ await flushPromises();+ expect(mocks.login).toHaveBeenCalledWith({+ request: expect.objectContaining({ mfaTempToken: "FROM-QUERY" }),+ redirect: true,+ });+ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/MultiFactorPage.tsx b/frontend/src/react/pages/auth/MultiFactorPage.tsxnew file mode 100644index 0000000000..8f1113d081--- /dev/null+++ b/frontend/src/react/pages/auth/MultiFactorPage.tsx@@ -0,0 +1,130 @@+import { create } from "@bufbuild/protobuf";+import { KeyRound, Smartphone } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import logoFull from "@/assets/logo-full.svg";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { OtpInput } from "@/react/components/ui/otp-input";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { useAuthStore } from "@/store";+import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";+import { resolveWorkspaceName } from "@/utils";++type MFAType = "OTP" | "RECOVERY_CODE";++export function MultiFactorPage() {+ const { t } = useTranslation();+ const [mfaType, setMfaType] = useState<MFAType>("OTP");+ const [otpCodes, setOtpCodes] = useState<string[]>([]);+ const [recoveryCode, setRecoveryCode] = useState("");++ const mfaTempToken = useVueState(+ () =>+ (router.currentRoute.value.query.mfaTempToken as string | undefined) ?? ""+ );++ const challengeDescription = useMemo(() => {+ if (mfaType === "OTP") {+ return t("multi-factor.other-methods.use-auth-app.description");+ }+ if (mfaType === "RECOVERY_CODE") {+ return t("multi-factor.other-methods.use-recovery-code.description");+ }+ return "";+ }, [mfaType, t]);++ const challenge = async (codes?: string[]) => {+ const effectiveOtp = (codes ?? otpCodes).join("");+ const request = create(LoginRequestSchema, {+ mfaTempToken,+ workspace: resolveWorkspaceName(),+ ...(mfaType === "OTP" ? { otpCode: effectiveOtp } : { recoveryCode }),+ });+ await useAuthStore().login({ request, redirect: true });+ };++ const onOtpFinish = (value: string[]) => {+ setOtpCodes(value);+ challenge(value);+ };++ const onSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ challenge();+ };++ return (+ <div className="mx-auto max-w-2xl h-full py-6 flex flex-col justify-center items-center">+ <div className="w-80 p-8 py-6 shadow-sm border border-control-border rounded-sm bg-white">+ <img+ src={logoFull}+ alt="Bytebase"+ className="h-12 w-auto mx-auto mb-8"+ />+ <form+ className="w-full mt-4 h-auto flex flex-col justify-start items-center"+ onSubmit={onSubmit}+ >+ {mfaType === "OTP" ? (+ <>+ <Smartphone className="w-8 h-auto opacity-60" />+ <p className="my-2 mb-4">{t("multi-factor.auth-code")}</p>+ <OtpInput+ value={otpCodes}+ onChange={setOtpCodes}+ onFinish={onOtpFinish}+ />+ </>+ ) : (+ <>+ <KeyRound className="w-8 h-auto opacity-60" />+ <p className="my-2 mb-4">{t("multi-factor.recovery-code")}</p>+ <Input+ value={recoveryCode}+ onChange={(e) => setRecoveryCode(e.target.value)}+ placeholder="XXXXXXXXXX"+ className="w-full"+ />+ </>+ )}+ <div className="w-full mt-4">+ <Button type="submit" className="w-full">+ {t("common.verify")}+ </Button>+ </div>+ <p className="textinfolabel mt-2">{challengeDescription}</p>+ </form>+ <hr className="my-3" />+ <div className="text-sm mb-2">+ <p>{t("multi-factor.other-methods.self")}:</p>+ <ul className="list-disc list-inside pl-2 pt-1">+ {mfaType !== "OTP" && (+ <li>+ <button+ type="button"+ className="accent-link"+ onClick={() => setMfaType("OTP")}+ >+ {t("multi-factor.other-methods.use-auth-app.self")}+ </button>+ </li>+ )}+ {mfaType !== "RECOVERY_CODE" && (+ <li>+ <button+ type="button"+ className="accent-link"+ onClick={() => setMfaType("RECOVERY_CODE")}+ >+ {t("multi-factor.other-methods.use-recovery-code.self")}+ </button>+ </li>+ )}+ </ul>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx b/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsxnew file mode 100644index 0000000000..d99fb28a9f--- /dev/null+++ b/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx@@ -0,0 +1,203 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),+ useAuthStore: vi.fn(),+ isLoggedIn: { value: true },+ routerReplace: vi.fn(),+ routerBack: vi.fn(),+ currentRoute: {+ value: {+ query: {} as Record<string, string>,+ fullPath: "/oauth2/consent?x=1",+ },+ },+ fetchImpl: vi.fn(),+}));+mocks.useAuthStore.mockImplementation(() => ({+ get isLoggedIn() {+ return mocks.isLoggedIn.value;+ },+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useAuthStore: mocks.useAuthStore,+}));++vi.mock("@/router", () => ({+ router: {+ replace: mocks.routerReplace,+ back: mocks.routerBack,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/router/auth", () => ({+ AUTH_SIGNIN_MODULE: "auth.signin",+}));++vi.mock("@/react/components/BytebaseLogo", () => ({+ BytebaseLogo: () => null,+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, string>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key,+ }),+}));++let OAuth2ConsentPage: typeof import("./OAuth2ConsentPage").OAuth2ConsentPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.isLoggedIn.value = true;+ mocks.currentRoute.value.query = {};+ mocks.currentRoute.value.fullPath = "/oauth2/consent";+ globalThis.fetch = mocks.fetchImpl as typeof fetch;+ mocks.fetchImpl.mockReset();+ ({ OAuth2ConsentPage } = await import("./OAuth2ConsentPage"));+});++describe("OAuth2ConsentPage", () => {+ test("redirects to signin when user is not logged in", async () => {+ mocks.isLoggedIn.value = false;+ mocks.currentRoute.value.fullPath = "/oauth2/consent?client_id=abc";+ const { render, unmount } = renderIntoContainer(<OAuth2ConsentPage />);+ render();+ await flushPromises();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: "auth.signin",+ query: { redirect: "/oauth2/consent?client_id=abc" },+ });+ unmount();+ });++ test("renders error when required params are missing", async () => {+ mocks.currentRoute.value.query = { client_id: "abc" };+ const { container, render, unmount } = renderIntoContainer(+ <OAuth2ConsentPage />+ );+ render();+ await flushPromises();+ expect(container.textContent).toContain(+ "Missing required OAuth2 parameters"+ );+ unmount();+ });++ test("fetches client info and renders consent form", async () => {+ mocks.currentRoute.value.query = {+ client_id: "c1",+ redirect_uri: "https://app/callback",+ state: "s",+ code_challenge: "ch",+ code_challenge_method: "S256",+ };+ mocks.fetchImpl.mockResolvedValue({+ ok: true,+ json: async () => ({ client_name: "Acme" }),+ });+ const { container, render, unmount } = renderIntoContainer(+ <OAuth2ConsentPage />+ );+ render();+ await flushPromises();+ expect(mocks.fetchImpl).toHaveBeenCalledWith("/api/oauth2/clients/c1");+ expect(container.textContent).toContain("Acme");+ expect(container.querySelector('form[method="POST"]')).not.toBeNull();+ const hiddenClientId = container.querySelector<HTMLInputElement>(+ 'input[name="client_id"]'+ );+ expect(hiddenClientId?.value).toBe("c1");+ unmount();+ });++ test("renders error when client lookup fails", async () => {+ mocks.currentRoute.value.query = {+ client_id: "c1",+ redirect_uri: "https://app/callback",+ state: "s",+ code_challenge: "ch",+ code_challenge_method: "S256",+ };+ mocks.fetchImpl.mockResolvedValue({+ ok: false,+ json: async () => ({ error_description: "client unknown" }),+ });+ const { container, render, unmount } = renderIntoContainer(+ <OAuth2ConsentPage />+ );+ render();+ await flushPromises();+ expect(container.textContent).toContain("client unknown");+ unmount();+ });++ test("deny creates a programmatic form and submits it", async () => {+ mocks.currentRoute.value.query = {+ client_id: "c1",+ redirect_uri: "https://app/callback",+ state: "s",+ code_challenge: "ch",+ code_challenge_method: "S256",+ };+ mocks.fetchImpl.mockResolvedValue({+ ok: true,+ json: async () => ({ client_name: "Acme" }),+ });+ const { container, render, unmount } = renderIntoContainer(+ <OAuth2ConsentPage />+ );+ render();+ await flushPromises();+ const denyBtn = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((b) => b.textContent === "common.deny");+ expect(denyBtn).toBeDefined();+ const submitSpy = vi+ .spyOn(HTMLFormElement.prototype, "submit")+ .mockImplementation(() => {});+ act(() => {+ denyBtn?.click();+ });+ expect(submitSpy).toHaveBeenCalledTimes(1);+ submitSpy.mockRestore();+ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx b/frontend/src/react/pages/auth/OAuth2ConsentPage.tsxnew file mode 100644index 0000000000..4565e09e3a--- /dev/null+++ b/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx@@ -0,0 +1,174 @@+import { Check, Loader2 } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { BytebaseLogo } from "@/react/components/BytebaseLogo";+import { Button } from "@/react/components/ui/button";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { AUTH_SIGNIN_MODULE } from "@/router/auth";+import { useAuthStore } from "@/store";++const AUTHORIZE_URL = "/api/oauth2/authorize";++export function OAuth2ConsentPage() {+ const { t } = useTranslation();+ const [loading, setLoading] = useState(true);+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState("");+ const [clientName, setClientName] = useState("");++ const isLoggedIn = useVueState(() => useAuthStore().isLoggedIn);++ const query = router.currentRoute.value.query;+ const clientId = (query.client_id as string) || "";+ const redirectUri = (query.redirect_uri as string) || "";+ const oauthState = (query.state as string) || "";+ const codeChallenge = (query.code_challenge as string) || "";+ const codeChallengeMethod = (query.code_challenge_method as string) || "";++ const initRef = useRef(false);+ useEffect(() => {+ if (initRef.current) return;+ initRef.current = true;+ if (!isLoggedIn) {+ const returnUrl = router.currentRoute.value.fullPath;+ router.replace({+ name: AUTH_SIGNIN_MODULE,+ query: { redirect: returnUrl },+ });+ return;+ }++ if (!clientId || !redirectUri || !codeChallenge || !codeChallengeMethod) {+ setError("Missing required OAuth2 parameters");+ setLoading(false);+ return;+ }++ (async () => {+ try {+ const response = await fetch(+ `/api/oauth2/clients/${encodeURIComponent(clientId)}`+ );+ if (!response.ok) {+ const data = await response.json();+ setError(data.error_description || "Client not found");+ setLoading(false);+ return;+ }+ const data = await response.json();+ setClientName(data.client_name || clientId);+ } catch {+ setError("Failed to load client information");+ }+ setLoading(false);+ })();+ }, []);++ const goBack = () => {+ router.back();+ };++ const deny = () => {+ setSubmitting(true);+ const form = document.createElement("form");+ form.method = "POST";+ form.action = AUTHORIZE_URL;+ const fields: [string, string][] = [+ ["client_id", clientId],+ ["redirect_uri", redirectUri],+ ["state", oauthState],+ ["code_challenge", codeChallenge],+ ["code_challenge_method", codeChallengeMethod],+ ["action", "deny"],+ ];+ for (const [name, value] of fields) {+ const input = document.createElement("input");+ input.type = "hidden";+ input.name = name;+ input.value = value;+ form.appendChild(input);+ }+ document.body.appendChild(form);+ form.submit();+ };++ return (+ <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">+ <BytebaseLogo className="mx-auto mb-8" />+ <div className="rounded-sm border border-control-border bg-white p-6">+ {loading ? (+ <div className="flex justify-center py-8">+ <Loader2 className="size-6 animate-spin" />+ </div>+ ) : error ? (+ <div className="text-center py-4">+ <p className="text-error mb-4">{error}</p>+ <Button variant="outline" onClick={goBack}>+ {t("common.go-back")}+ </Button>+ </div>+ ) : (+ <div className="space-y-6">+ <div className="text-center">+ <h1 className="text-xl font-semibold text-main mb-2">+ {t("oauth2.consent.title")}+ </h1>+ <p className="text-control">+ {t("oauth2.consent.description", { clientName })}+ </p>+ </div>+ <div className="bg-control-bg rounded-sm p-4">+ <p className="text-sm text-control-light mb-2">+ {t("oauth2.consent.permissions")}+ </p>+ <ul className="text-sm text-main space-y-1">+ <li className="flex items-center gap-2">+ <Check className="w-4 h-4 text-success" />+ {t("oauth2.consent.permission-access")}+ </li>+ </ul>+ </div>+ <form method="POST" action={AUTHORIZE_URL}>+ <input type="hidden" name="client_id" value={clientId} />+ <input type="hidden" name="redirect_uri" value={redirectUri} />+ <input type="hidden" name="state" value={oauthState} />+ <input+ type="hidden"+ name="code_challenge"+ value={codeChallenge}+ />+ <input+ type="hidden"+ name="code_challenge_method"+ value={codeChallengeMethod}+ />+ <div className="flex gap-x-2">+ <Button+ type="button"+ variant="outline"+ size="lg"+ className="flex-1"+ disabled={submitting}+ onClick={deny}+ >+ {t("common.deny")}+ </Button>+ <Button+ type="submit"+ size="lg"+ className="flex-1"+ disabled={submitting}+ name="action"+ value="allow"+ >+ {t("common.allow")}+ </Button>+ </div>+ </form>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsxnew file mode 100644index 0000000000..29fa3e6d09--- /dev/null+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx@@ -0,0 +1,257 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),+ login: vi.fn<(payload: unknown) => Promise<void>>(async () => {}),+ useAuthStore: vi.fn(),+ routerPush: vi.fn(),+ currentRoute: {+ value: { query: {} as Record<string, string> },+ },+ retrieveOAuthState: vi.fn(),+ clearOAuthState: vi.fn(),+ resolveWorkspaceName: vi.fn(() => undefined),+}));+mocks.useAuthStore.mockImplementation(() => ({ login: mocks.login }));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useAuthStore: mocks.useAuthStore,+}));++vi.mock("@/router", () => ({+ router: {+ push: mocks.routerPush,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/router/auth", () => ({+ AUTH_SIGNIN_MODULE: "auth.signin",+}));++vi.mock("@/utils/sso", () => ({+ retrieveOAuthState: mocks.retrieveOAuthState,+ clearOAuthState: mocks.clearOAuthState,+}));++vi.mock("@/utils", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/utils")>();+ return {+ ...actual,+ resolveWorkspaceName: mocks.resolveWorkspaceName,+ };+});++vi.mock("@bufbuild/protobuf", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@bufbuild/protobuf")>();+ return {+ ...actual,+ create: (_schema: unknown, data: Record<string, unknown>) => data,+ };+});++vi.mock("@/types/proto-es/v1/auth_service_pb", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/types/proto-es/v1/auth_service_pb")+ >();+ return {+ ...actual,+ LoginRequestSchema: {},+ };+});++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++let OAuthCallbackPage: typeof import("./OAuthCallbackPage").OAuthCallbackPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++const originalOpener = (window as unknown as { opener: unknown }).opener;++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.currentRoute.value.query = {};+ mocks.login.mockResolvedValue(undefined);+ mocks.retrieveOAuthState.mockReset();+ mocks.clearOAuthState.mockReset();+ ({ OAuthCallbackPage } = await import("./OAuthCallbackPage"));+});++afterEach(() => {+ (window as unknown as { opener: unknown }).opener = originalOpener;+});++describe("OAuthCallbackPage", () => {+ test("renders error + back-to-signin link when state token is missing", async () => {+ mocks.currentRoute.value.query = {};+ const { container, render, unmount } = renderIntoContainer(+ <OAuthCallbackPage />+ );+ render();+ await flushPromises();+ expect(container.textContent).toContain(+ "auth.oauth-callback.invalid-state"+ );+ const backBtn = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((b) => b.textContent === "auth.back-to-signin");+ expect(backBtn).toBeDefined();+ unmount();+ });++ test("renders error when stored state not found", async () => {+ mocks.currentRoute.value.query = { state: "xyz" };+ mocks.retrieveOAuthState.mockReturnValue(null);+ const { container, render, unmount } = renderIntoContainer(+ <OAuthCallbackPage />+ );+ render();+ await flushPromises();+ expect(container.textContent).toContain(+ "auth.oauth-callback.session-expired"+ );+ unmount();+ });++ test("renders security-validation error and clears state when token mismatches", async () => {+ mocks.currentRoute.value.query = { state: "xyz" };+ mocks.retrieveOAuthState.mockReturnValue({+ token: "OTHER",+ event: "bb.oauth.signin.gh",+ idpType: IdentityProviderType.OAUTH2,+ timestamp: Date.now(),+ });+ const { container, render, unmount } = renderIntoContainer(+ <OAuthCallbackPage />+ );+ render();+ await flushPromises();+ expect(container.textContent).toContain(+ "auth.oauth-callback.security-failed"+ );+ expect(mocks.clearOAuthState).toHaveBeenCalledWith("xyz");+ unmount();+ });++ test("redirect mode: valid signin event calls authStore.login with oauth2Context", async () => {+ mocks.currentRoute.value.query = { state: "xyz", code: "abc" };+ mocks.retrieveOAuthState.mockReturnValue({+ token: "xyz",+ event: "bb.oauth.signin.gh",+ idpType: IdentityProviderType.OAUTH2,+ popup: false,+ redirect: "/home",+ timestamp: Date.now(),+ });+ const { render, unmount } = renderIntoContainer(<OAuthCallbackPage />);+ render();+ await flushPromises();+ expect(mocks.login).toHaveBeenCalledTimes(1);+ const arg = mocks.login.mock.calls[0]?.[0] as {+ request: {+ idpName: string;+ idpContext: {+ context: { case: string; value: { code: string } };+ };+ };+ redirect: boolean;+ redirectUrl: string;+ };+ expect(arg.request.idpName).toBe("gh");+ expect(arg.request.idpContext.context.case).toBe("oauth2Context");+ expect(arg.request.idpContext.context.value.code).toBe("abc");+ expect(arg.redirect).toBe(true);+ expect(arg.redirectUrl).toBe("/home");+ unmount();+ });++ test("redirect mode: OIDC event uses oidcContext", async () => {+ mocks.currentRoute.value.query = { state: "xyz", code: "abc" };+ mocks.retrieveOAuthState.mockReturnValue({+ token: "xyz",+ event: "bb.oauth.signin.okta",+ idpType: IdentityProviderType.OIDC,+ popup: false,+ redirect: "/",+ timestamp: Date.now(),+ });+ const { render, unmount } = renderIntoContainer(<OAuthCallbackPage />);+ render();+ await flushPromises();+ const arg = mocks.login.mock.calls[0]?.[0] as {+ request: {+ idpName: string;+ idpContext: { context: { case: string } };+ };+ };+ expect(arg.request.idpName).toBe("okta");+ expect(arg.request.idpContext.context.case).toBe("oidcContext");+ unmount();+ });++ test("popup mode: dispatches CustomEvent on window.opener with payload", async () => {+ mocks.currentRoute.value.query = { state: "xyz", code: "abc" };+ mocks.retrieveOAuthState.mockReturnValue({+ token: "xyz",+ event: "bb.oauth.signin.gh",+ idpType: IdentityProviderType.OAUTH2,+ popup: true,+ redirect: "/home",+ timestamp: Date.now(),+ });+ const dispatchEvent = vi.fn();+ (window as unknown as { opener: unknown }).opener = {+ closed: false,+ dispatchEvent,+ };+ const { render, unmount } = renderIntoContainer(<OAuthCallbackPage />);+ render();+ await flushPromises();+ expect(dispatchEvent).toHaveBeenCalledTimes(1);+ const arg = dispatchEvent.mock.calls[0]?.[0] as CustomEvent<{+ code: string;+ }>;+ expect(arg).toBeInstanceOf(CustomEvent);+ expect(arg.type).toBe("bb.oauth.signin.gh");+ expect(arg.detail.code).toBe("abc");+ // authStore.login must NOT be called in popup mode+ expect(mocks.login).not.toHaveBeenCalled();+ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.tsxnew file mode 100644index 0000000000..8be5aba722--- /dev/null+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.tsx@@ -0,0 +1,179 @@+import { create } from "@bufbuild/protobuf";+import { Loader2 } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { router } from "@/router";+import { AUTH_SIGNIN_MODULE } from "@/router/auth";+import { useAuthStore } from "@/store";+import type { OAuthState, OAuthWindowEventPayload } from "@/types/oauth";+import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";+import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";+import { resolveWorkspaceName } from "@/utils";+import { clearOAuthState, retrieveOAuthState } from "@/utils/sso";++export function OAuthCallbackPage() {+ const { t } = useTranslation();+ const [message, setMessage] = useState("");+ const [hasError, setHasError] = useState(false);+ const [oAuthState, setOAuthState] = useState<OAuthState | undefined>(+ undefined+ );+ const [showCloseButton, setShowCloseButton] = useState(false);+ const payloadRef = useRef<OAuthWindowEventPayload>({ error: "", code: "" });+ // StrictMode double-invokes effects; the OAuth state token is single-use+ // (consumed via `clearOAuthState`). Without this guard the second invocation+ // would fail to retrieve the already-cleared token and flash a+ // "session expired" error before the login completes.+ const initRef = useRef(false);++ useEffect(() => {+ if (initRef.current) return;+ initRef.current = true;+ const query = router.currentRoute.value.query;+ const stateToken = query.state as string | undefined;++ if (+ !stateToken ||+ typeof stateToken !== "string" ||+ stateToken.length === 0+ ) {+ setHasError(true);+ setMessage(t("auth.oauth-callback.invalid-state"));+ triggerAuthCallback(undefined, true);+ return;+ }++ const storedState = retrieveOAuthState(stateToken);+ if (!storedState) {+ setHasError(true);+ setMessage(t("auth.oauth-callback.session-expired"));+ triggerAuthCallback(undefined, true);+ return;+ }++ if (storedState.token !== stateToken) {+ setHasError(true);+ setMessage(t("auth.oauth-callback.security-failed"));+ clearOAuthState(stateToken);+ triggerAuthCallback(undefined, true);+ return;+ }++ setOAuthState(storedState);+ setHasError(false);+ setMessage(t("auth.oauth-callback.success-redirecting"));+ payloadRef.current.code = (query.code as string) || "";+ clearOAuthState(storedState.token);+ triggerAuthCallback(storedState, false);+ }, []);++ const triggerAuthCallback = async (+ state: OAuthState | undefined,+ isError: boolean+ ) => {+ if (state?.popup) {+ try {+ if (!window.opener || window.opener.closed) {+ setHasError(true);+ setMessage(t("auth.oauth-callback.opener-unavailable"));+ setShowCloseButton(true);+ return;+ }++ const eventName = isError ? "bb.oauth.unknown" : state.event;++ window.opener.dispatchEvent(+ new CustomEvent(eventName, { detail: payloadRef.current })+ );++ try {+ window.close();++ setTimeout(() => {+ if (!window.closed) {+ setShowCloseButton(true);+ if (!isError) {+ setMessage(t("auth.oauth-callback.success-close"));+ }+ }+ }, 500);+ } catch {+ setShowCloseButton(true);+ if (!isError) {+ setMessage(t("auth.oauth-callback.please-close"));+ }+ }+ } catch (error) {+ console.error("Failed to communicate with opener window:", error);+ setHasError(true);+ setMessage(t("auth.oauth-callback.opener-failed"));+ setShowCloseButton(true);+ }+ return;+ }++ if (isError || !state) {+ return;+ }++ const eventName = state.event;+ if (eventName.startsWith("bb.oauth.signin")) {+ const isOidc = state.idpType === IdentityProviderType.OIDC;+ const idpName = eventName.split(".").pop();+ if (!idpName) {+ return;+ }++ await useAuthStore().login({+ request: create(LoginRequestSchema, {+ idpName,+ idpContext: {+ context: {+ case: isOidc ? "oidcContext" : "oauth2Context",+ value: {+ code: payloadRef.current.code,+ },+ },+ },+ workspace: resolveWorkspaceName(),+ }),+ redirect: true,+ redirectUrl: state.redirect,+ });+ }+ };++ const backToSignin = () => {+ router.push({ name: AUTH_SIGNIN_MODULE });+ };++ return (+ <div className="p-4">+ {hasError ? (+ <div className="mt-2">+ <div>{message}</div>+ {oAuthState?.popup ? (+ <Button onClick={() => window.close()}>{t("common.close")}</Button>+ ) : (+ <button type="button" className="btn-normal" onClick={backToSignin}>+ {t("auth.back-to-signin")}+ </button>+ )}+ </div>+ ) : (+ <div className="mt-2">+ <div className="flex items-center gap-x-2">+ <Loader2 className="size-4 animate-spin" />+ <span>{message || t("auth.oauth-callback.processing")}</span>+ </div>+ {oAuthState?.popup && showCloseButton && (+ <Button className="mt-4" onClick={() => window.close()}>+ {t("auth.close-window")}+ </Button>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx b/frontend/src/react/pages/auth/PasswordForgotPage.test.tsxnew file mode 100644index 0000000000..6fdc5e2814--- /dev/null+++ b/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx@@ -0,0 +1,220 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => {+ const restriction: {+ passwordResetEnabled: boolean;+ disallowPasswordSignin: boolean;+ } = {+ passwordResetEnabled: true,+ disallowPasswordSignin: false,+ };+ return {+ restriction,+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) =>+ getter()+ ),+ useActuatorV1Store: vi.fn(() => ({+ serverInfo: { restriction },+ })),+ pushNotification: vi.fn(),+ routerPush: vi.fn(),+ routerReplace: vi.fn(),+ currentRoute: { value: { query: {} as Record<string, string> } },+ requestPasswordReset: vi.fn(),+ resolveWorkspaceName: vi.fn(() => undefined),+ };+});++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useActuatorV1Store: mocks.useActuatorV1Store,+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/router", () => ({+ router: {+ push: mocks.routerPush,+ replace: mocks.routerReplace,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/router/auth", () => ({+ AUTH_PASSWORD_RESET_MODULE: "auth.password.reset",+ AUTH_SIGNIN_MODULE: "auth.signin",+}));++vi.mock("@/connect", () => ({+ authServiceClientConnect: {+ requestPasswordReset: mocks.requestPasswordReset,+ },+}));++vi.mock("@/utils", async () => {+ const actual = await vi.importActual<typeof import("@/utils")>("@/utils");+ return {+ ...actual,+ resolveWorkspaceName: mocks.resolveWorkspaceName,+ };+});++vi.mock("@/assets/logo-full.svg", () => ({+ default: "/assets/logo-full.svg",+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++let PasswordForgotPage: typeof import("./PasswordForgotPage").PasswordForgotPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++const setInputValue = (input: HTMLInputElement, value: string) => {+ act(() => {+ const descriptor = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ );+ descriptor?.set?.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.restriction.passwordResetEnabled = true;+ mocks.restriction.disallowPasswordSignin = false;+ mocks.currentRoute.value.query = {};+ ({ PasswordForgotPage } = await import("./PasswordForgotPage"));+});++describe("PasswordForgotPage", () => {+ test("renders self-host warning when passwordResetEnabled is false", () => {+ mocks.restriction.passwordResetEnabled = false;+ const { container, render, unmount } = renderIntoContainer(+ <PasswordForgotPage />+ );+ render();+ expect(container.textContent).toContain("auth.password-forget.selfhost");+ expect(container.querySelector("#forgot-email")).toBeNull();+ unmount();+ });++ test("renders email input and disabled send button when passwordResetEnabled is true", () => {+ const { container, render, unmount } = renderIntoContainer(+ <PasswordForgotPage />+ );+ render();+ const input = container.querySelector<HTMLInputElement>("#forgot-email");+ expect(input).not.toBeNull();+ const button = container.querySelector<HTMLButtonElement>("button");+ expect(button?.textContent).toBe("auth.password-forget.send-reset-code");+ expect(button?.disabled).toBe(true);+ unmount();+ });++ test("enables submit button for a valid email", () => {+ const { container, render, unmount } = renderIntoContainer(+ <PasswordForgotPage />+ );+ render();+ const input = container.querySelector<HTMLInputElement>("#forgot-email");+ expect(input).not.toBeNull();+ setInputValue(input!, "[email protected]");+ const button = container.querySelector<HTMLButtonElement>("button");+ expect(button?.disabled).toBe(false);+ unmount();+ });++ test("submit calls requestPasswordReset then navigates to password-reset", async () => {+ mocks.requestPasswordReset.mockResolvedValue({});+ const { container, render, unmount } = renderIntoContainer(+ <PasswordForgotPage />+ );+ render();+ const input = container.querySelector<HTMLInputElement>("#forgot-email")!;+ setInputValue(input, "[email protected]");+ const button = container.querySelector<HTMLButtonElement>("button")!;+ act(() => {+ button.click();+ });+ await flushPromises();+ expect(mocks.requestPasswordReset).toHaveBeenCalledWith({+ email: "[email protected]",+ workspace: undefined,+ });+ expect(mocks.routerPush).toHaveBeenCalledWith({+ name: "auth.password.reset",+ query: { email: "[email protected]" },+ });+ unmount();+ });++ test("shows notification when requestPasswordReset rejects", async () => {+ mocks.requestPasswordReset.mockRejectedValue(new Error("boom"));+ const { container, render, unmount } = renderIntoContainer(+ <PasswordForgotPage />+ );+ render();+ const input = container.querySelector<HTMLInputElement>("#forgot-email")!;+ setInputValue(input, "[email protected]");+ const button = container.querySelector<HTMLButtonElement>("button")!;+ act(() => {+ button.click();+ });+ await flushPromises();+ expect(mocks.pushNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ style: "CRITICAL",+ title: "auth.password-forget.failed-to-send-code",+ })+ );+ expect(mocks.routerPush).not.toHaveBeenCalled();+ unmount();+ });++ test("redirects to signin when disallowPasswordSignin is true", () => {+ mocks.restriction.disallowPasswordSignin = true;+ const { render, unmount } = renderIntoContainer(<PasswordForgotPage />);+ render();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: "auth.signin",+ query: {},+ });+ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/PasswordForgotPage.tsx b/frontend/src/react/pages/auth/PasswordForgotPage.tsxnew file mode 100644index 0000000000..f2a4b9adcd--- /dev/null+++ b/frontend/src/react/pages/auth/PasswordForgotPage.tsx@@ -0,0 +1,142 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import logoFull from "@/assets/logo-full.svg";+import { authServiceClientConnect } from "@/connect";+import { Alert, AlertTitle } from "@/react/components/ui/alert";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { AUTH_PASSWORD_RESET_MODULE, AUTH_SIGNIN_MODULE } from "@/router/auth";+import { pushNotification, useActuatorV1Store } from "@/store";+import { isValidEmail, resolveWorkspaceName } from "@/utils";++export function PasswordForgotPage() {+ const { t } = useTranslation();+ const [email, setEmail] = useState("");+ const [isLoading, setIsLoading] = useState(false);++ const passwordResetEnabled = useVueState(+ () =>+ useActuatorV1Store().serverInfo?.restriction?.passwordResetEnabled ??+ false+ );+ const disallowPasswordSignin = useVueState(+ () =>+ useActuatorV1Store().serverInfo?.restriction?.disallowPasswordSignin ??+ false+ );++ useEffect(() => {+ if (disallowPasswordSignin) {+ router.replace({+ name: AUTH_SIGNIN_MODULE,+ query: router.currentRoute.value.query,+ });+ }+ }, [disallowPasswordSignin]);++ const canSubmit = isValidEmail(email) && !isLoading;++ const onSubmit = async () => {+ if (!canSubmit) return;+ setIsLoading(true);+ try {+ await authServiceClientConnect.requestPasswordReset({+ email,+ workspace: resolveWorkspaceName(),+ });+ router.push({+ name: AUTH_PASSWORD_RESET_MODULE,+ query: { ...router.currentRoute.value.query, email },+ });+ } catch {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("auth.password-forget.failed-to-send-code"),+ });+ } finally {+ setIsLoading(false);+ }+ };++ const goToSignin = () => {+ router.push({+ name: AUTH_SIGNIN_MODULE,+ query: router.currentRoute.value.query,+ });+ };++ return (+ <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">+ <div>+ <img src={logoFull} alt="Bytebase" className="h-12 w-auto" />+ <h2 className="mt-6 text-3xl leading-9 font-extrabold text-main">+ {t("auth.password-forget.title")}+ </h2>+ </div>++ <div className="mt-8">+ <div className="mt-6 flex flex-col gap-y-4">+ {!passwordResetEnabled ? (+ <Alert variant="warning">+ <AlertTitle>{t("auth.password-forget.selfhost")}</AlertTitle>+ </Alert>+ ) : (+ <>+ <div>+ <label+ htmlFor="forgot-email"+ className="block text-sm font-medium leading-5 text-control"+ >+ {t("common.email")}+ </label>+ <div className="mt-1">+ <Input+ id="forgot-email"+ type="email"+ autoComplete="email"+ placeholder="[email protected]"+ required+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ onKeyUp={(e) => {+ if (e.key === "Enter") onSubmit();+ }}+ />+ </div>+ </div>+ <Button+ size="lg"+ className="w-full"+ disabled={!canSubmit}+ onClick={onSubmit}+ >+ {t("auth.password-forget.send-reset-code")}+ </Button>+ </>+ )}+ </div>+ </div>++ <div className="mt-6 relative">+ <div aria-hidden="true" className="absolute inset-0 flex items-center">+ <div className="w-full border-t border-control-border" />+ </div>+ <div className="relative flex justify-center text-sm">+ <a+ href="#"+ className="accent-link bg-white px-2"+ onClick={(e) => {+ e.preventDefault();+ goToSignin();+ }}+ >+ {t("auth.password-forget.return-to-sign-in")}+ </a>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/pages/auth/PasswordResetPage.test.tsx b/frontend/src/react/pages/auth/PasswordResetPage.test.tsxnew file mode 100644index 0000000000..4da3c202b2--- /dev/null+++ b/frontend/src/react/pages/auth/PasswordResetPage.test.tsx@@ -0,0 +1,286 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),+ useActuatorV1Store: vi.fn(() => ({+ serverInfo: {+ restriction: {+ passwordRestriction: undefined,+ disallowPasswordSignin: false,+ },+ },+ })),+ useAuthStore: vi.fn(() => ({+ requireResetPassword: false,+ setRequireResetPassword: vi.fn(),+ login: vi.fn(async () => {}),+ })),+ useCurrentUserV1: vi.fn(() => ({ value: { name: "users/1", email: "u@e" } })),+ useUserStore: vi.fn(() => ({ updateUser: vi.fn() })),+ pushNotification: vi.fn(),+ routerReplace: vi.fn(),+ routerPush: vi.fn(),+ currentRoute: {+ value: { query: {} as Record<string, string> },+ },+ resetPassword: vi.fn(),+ requestPasswordReset: vi.fn(),+ resolveWorkspaceName: vi.fn(() => undefined),+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useActuatorV1Store: mocks.useActuatorV1Store,+ useAuthStore: mocks.useAuthStore,+ useCurrentUserV1: mocks.useCurrentUserV1,+ useUserStore: mocks.useUserStore,+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/router", () => ({+ router: {+ replace: mocks.routerReplace,+ push: mocks.routerPush,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/router/auth", () => ({+ AUTH_SIGNIN_MODULE: "auth.signin",+}));++vi.mock("@/connect", () => ({+ authServiceClientConnect: {+ resetPassword: mocks.resetPassword,+ requestPasswordReset: mocks.requestPasswordReset,+ },+}));++vi.mock("@/utils", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/utils")>();+ return {+ ...actual,+ resolveWorkspaceName: mocks.resolveWorkspaceName,+ };+});++vi.mock("@bufbuild/protobuf", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@bufbuild/protobuf")>();+ return {+ ...actual,+ create: (_schema: unknown, data: Record<string, unknown>) => data,+ };+});++vi.mock("@/types/proto-es/v1/auth_service_pb", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/types/proto-es/v1/auth_service_pb")+ >();+ return {+ ...actual,+ LoginRequestSchema: {},+ ResetPasswordRequestSchema: {},+ };+});++vi.mock("@/types/proto-es/v1/user_service_pb", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/types/proto-es/v1/user_service_pb")+ >();+ return {+ ...actual,+ UpdateUserRequestSchema: {},+ };+});++vi.mock("@/assets/logo-full.svg", () => ({+ default: "/assets/logo-full.svg",+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, unknown>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key,+ }),+}));++let PasswordResetPage: typeof import("./PasswordResetPage").PasswordResetPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++const setInputValue = (input: HTMLInputElement, value: string) => {+ act(() => {+ const descriptor = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value"+ );+ descriptor?.set?.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.currentRoute.value.query = {};+ mocks.useActuatorV1Store.mockReturnValue({+ serverInfo: {+ restriction: {+ passwordRestriction: undefined,+ disallowPasswordSignin: false,+ },+ },+ });+ mocks.useAuthStore.mockReturnValue({+ requireResetPassword: true,+ setRequireResetPassword: vi.fn(),+ login: vi.fn(async () => {}),+ });+ ({ PasswordResetPage } = await import("./PasswordResetPage"));+});++describe("PasswordResetPage", () => {+ test("forced-reset mode: redirects when requireResetPassword is false", () => {+ mocks.useAuthStore.mockReturnValue({+ requireResetPassword: false,+ setRequireResetPassword: vi.fn(),+ login: vi.fn(),+ });+ const { render, unmount } = renderIntoContainer(<PasswordResetPage />);+ render();+ expect(mocks.routerReplace).toHaveBeenCalled();+ unmount();+ });++ test("code mode: redirects to signin when password signin is disallowed", () => {+ mocks.currentRoute.value.query = { email: "[email protected]" };+ mocks.useActuatorV1Store.mockReturnValue({+ serverInfo: {+ restriction: {+ passwordRestriction: undefined,+ disallowPasswordSignin: true,+ },+ },+ });+ const { render, unmount } = renderIntoContainer(<PasswordResetPage />);+ render();+ expect(mocks.routerReplace).toHaveBeenCalledWith({+ name: "auth.signin",+ query: { email: "[email protected]" },+ });+ unmount();+ });++ test("code mode: renders email + verification code + password fields", () => {+ mocks.currentRoute.value.query = { email: "[email protected]" };+ const { container, render, unmount } = renderIntoContainer(+ <PasswordResetPage />+ );+ render();+ const emailInput = container.querySelector<HTMLInputElement>(+ 'input[type="email"]'+ );+ expect(emailInput?.value).toBe("[email protected]");+ expect(emailInput?.disabled).toBe(true);+ const otpInputs = container.querySelectorAll('input[inputmode="numeric"]');+ expect(otpInputs.length).toBe(6);+ const passwordInputs = container.querySelectorAll<HTMLInputElement>(+ 'input[type="password"]'+ );+ expect(passwordInputs.length).toBe(2);+ unmount();+ });++ test("confirm button is disabled until valid password + matching confirm", () => {+ mocks.currentRoute.value.query = {};+ const { container, render, unmount } = renderIntoContainer(+ <PasswordResetPage />+ );+ render();+ const confirmBtn = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((b) => b.textContent === "common.confirm");+ expect(confirmBtn?.disabled).toBe(true);+ const passwordInputs = container.querySelectorAll<HTMLInputElement>(+ 'input[type="password"]'+ );+ setInputValue(passwordInputs[0], "Passw0rd!");+ setInputValue(passwordInputs[1], "Passw0rd!");+ expect(confirmBtn?.disabled).toBe(false);+ unmount();+ });++ test("code mode: confirm calls resetPassword and logs in on success", async () => {+ mocks.currentRoute.value.query = { email: "[email protected]" };+ mocks.resetPassword.mockResolvedValue({});+ const login = vi.fn(async () => {});+ mocks.useAuthStore.mockReturnValue({+ requireResetPassword: true,+ setRequireResetPassword: vi.fn(),+ login,+ });+ const { container, render, unmount } = renderIntoContainer(+ <PasswordResetPage />+ );+ render();+ // Fill OTP+ const otpInputs = Array.from(+ container.querySelectorAll<HTMLInputElement>('input[inputmode="numeric"]')+ );+ "111111".split("").forEach((d, i) => setInputValue(otpInputs[i], d));+ // Fill passwords+ const passwordInputs = container.querySelectorAll<HTMLInputElement>(+ 'input[type="password"]'+ );+ setInputValue(passwordInputs[0], "Passw0rd!");+ setInputValue(passwordInputs[1], "Passw0rd!");+ const confirmBtn = Array.from(+ container.querySelectorAll<HTMLButtonElement>("button")+ ).find((b) => b.textContent === "common.confirm")!;+ act(() => {+ confirmBtn.click();+ });+ await flushPromises();+ expect(mocks.resetPassword).toHaveBeenCalledWith(+ expect.objectContaining({+ email: "[email protected]",+ code: "111111",+ newPassword: "Passw0rd!",+ })+ );+ expect(login).toHaveBeenCalled();+ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/PasswordResetPage.tsx b/frontend/src/react/pages/auth/PasswordResetPage.tsxnew file mode 100644index 0000000000..0ef635adda--- /dev/null+++ b/frontend/src/react/pages/auth/PasswordResetPage.tsx@@ -0,0 +1,273 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import logoFull from "@/assets/logo-full.svg";+import { authServiceClientConnect } from "@/connect";+import { UserPasswordFields } from "@/react/components/auth/UserPasswordFields";+import { computePasswordValidation } from "@/react/components/auth/userPasswordValidation";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { OtpInput } from "@/react/components/ui/otp-input";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { AUTH_SIGNIN_MODULE } from "@/router/auth";+import {+ pushNotification,+ useActuatorV1Store,+ useAuthStore,+ useCurrentUserV1,+ useUserStore,+} from "@/store";+import {+ LoginRequestSchema,+ ResetPasswordRequestSchema,+} from "@/types/proto-es/v1/auth_service_pb";+import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";+import { resolveWorkspaceName } from "@/utils";++export function PasswordResetPage() {+ const { t } = useTranslation();+ const [email, setEmail] = useState("");+ const [codeParts, setCodeParts] = useState<string[]>([]);+ const [password, setPassword] = useState("");+ const [passwordConfirm, setPasswordConfirm] = useState("");+ const [resendCountdown, setResendCountdown] = useState(60);+ const countdownTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);++ const query = router.currentRoute.value.query;+ const codeMode = !!query.email;++ const passwordRestriction = useVueState(+ () => useActuatorV1Store().serverInfo?.restriction?.passwordRestriction+ );+ const disallowPasswordSignin = useVueState(+ () =>+ useActuatorV1Store().serverInfo?.restriction?.disallowPasswordSignin ??+ false+ );+ const requireResetPassword = useVueState(+ () => useAuthStore().requireResetPassword+ );+ const currentUser = useVueState(() => useCurrentUserV1().value);++ const redirectQuery = () => {+ const q = new URLSearchParams(window.location.search);+ return q.get("redirect") || "/";+ };++ const startCountdown = () => {+ setResendCountdown(60);+ if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);+ countdownTimerRef.current = setInterval(() => {+ setResendCountdown((prev) => {+ if (prev <= 1) {+ if (countdownTimerRef.current) {+ clearInterval(countdownTimerRef.current);+ countdownTimerRef.current = null;+ }+ return 0;+ }+ return prev - 1;+ });+ }, 1000);+ };++ useEffect(() => {+ if (codeMode) {+ if (disallowPasswordSignin) {+ router.replace({ name: AUTH_SIGNIN_MODULE, query });+ return;+ }+ setEmail(query.email as string);+ startCountdown();+ return () => {+ if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);+ };+ }+ if (!requireResetPassword) {+ router.replace(redirectQuery());+ }+ return () => {+ if (countdownTimerRef.current) clearInterval(countdownTimerRef.current);+ };+ }, []);++ const validation = computePasswordValidation(+ password,+ passwordConfirm,+ passwordRestriction+ );++ const allowConfirm = (() => {+ if (!password) return false;+ if (codeMode && (!email || codeParts.join("").length !== 6)) return false;+ return !validation.hint && !validation.mismatch;+ })();++ const resendCode = async () => {+ if (resendCountdown > 0 || !email) return;+ try {+ await authServiceClientConnect.requestPasswordReset({+ email,+ workspace: resolveWorkspaceName(),+ });+ startCountdown();+ } catch {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("auth.password-forget.failed-to-send-code"),+ });+ }+ };++ const onConfirm = async () => {+ if (codeMode) {+ try {+ await authServiceClientConnect.resetPassword(+ create(ResetPasswordRequestSchema, {+ email,+ code: codeParts.join(""),+ newPassword: password,+ })+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ await useAuthStore().login({+ request: create(LoginRequestSchema, {+ email,+ password,+ workspace: resolveWorkspaceName(),+ }),+ });+ } catch {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("auth.password-reset.invalid-or-expired-code"),+ });+ }+ return;+ }++ // Forced-reset mode+ if (!currentUser) return;+ const patch = { ...currentUser, password };+ await useUserStore().updateUser(+ create(UpdateUserRequestSchema, {+ user: patch,+ updateMask: create(FieldMaskSchema, { paths: ["password"] }),+ })+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.updated"),+ });+ useAuthStore().setRequireResetPassword(false);+ router.replace(redirectQuery());+ };++ return (+ <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">+ <img src={logoFull} alt="Bytebase" className="h-12 w-auto" />+ <h2 className="mt-6 text-3xl leading-9 font-extrabold text-main">+ {t("auth.password-reset.title")}+ </h2>+ <p className="textinfo mt-2">{t("auth.password-reset.content")}</p>++ <div className="mt-8 flex flex-col gap-y-6">+ {codeMode && (+ <>+ <div>+ <label className="block text-sm font-medium leading-5 text-control">+ {t("common.email")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <Input+ className="mt-1"+ type="email"+ autoComplete="email"+ value={email}+ disabled+ required+ onChange={(e) => setEmail(e.target.value)}+ />+ </div>+ <div>+ <label className="block text-sm font-medium leading-5 text-control">+ {t("auth.password-reset.code-label")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="mt-1">+ <OtpInput+ value={codeParts}+ onChange={setCodeParts}+ length={6}+ />+ </div>+ <div className="mt-2 flex items-center justify-end">+ <button+ type="button"+ className="text-sm text-accent disabled:text-control-light disabled:cursor-not-allowed"+ disabled={resendCountdown > 0}+ onClick={resendCode}+ >+ {resendCountdown > 0+ ? t("auth.sign-in.resend-in", {+ seconds: resendCountdown,+ })+ : t("auth.sign-in.resend-code")}+ </button>+ </div>+ </div>+ </>+ )}++ <UserPasswordFields+ password={password}+ passwordConfirm={passwordConfirm}+ onPasswordChange={setPassword}+ onPasswordConfirmChange={setPasswordConfirm}+ passwordRestriction={passwordRestriction}+ />++ <Button+ size="lg"+ className="w-full"+ disabled={!allowConfirm}+ onClick={onConfirm}+ >+ {t("common.confirm")}+ </Button>+ </div>++ {codeMode && (+ <div className="mt-6 relative">+ <div+ aria-hidden="true"+ className="absolute inset-0 flex items-center"+ >+ <div className="w-full border-t border-control-border" />+ </div>+ <div className="relative flex justify-center text-sm">+ <a+ href="#"+ className="accent-link bg-white px-2"+ onClick={(e) => {+ e.preventDefault();+ router.push({ name: AUTH_SIGNIN_MODULE, query });+ }}+ >+ {t("auth.password-forget.return-to-sign-in")}+ </a>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/auth/SetupPage.test.tsx b/frontend/src/react/pages/auth/SetupPage.test.tsxnew file mode 100644index 0000000000..c314c56a35--- /dev/null+++ b/frontend/src/react/pages/auth/SetupPage.test.tsx@@ -0,0 +1,190 @@+import { Code, ConnectError } from "@connectrpc/connect";+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ routerIsReady: vi.fn(async () => {}),+ routerPush: vi.fn(),+ fetchRoleList: vi.fn(async () => {}),+ fetchIamPolicy: vi.fn(async () => {}),+ getOrFetchProjectByName: vi.fn(async () => {+ throw new ConnectError("not found", Code.NotFound);+ }),+ createProject: vi.fn(),+ setupSample: vi.fn(),+ updateWorkspaceProfile: vi.fn(),+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),+}));++vi.mock("@/router", () => ({+ router: {+ isReady: mocks.routerIsReady,+ push: mocks.routerPush,+ },+}));++vi.mock("@/router/sqlEditor", () => ({+ SQL_EDITOR_HOME_MODULE: "sql-editor.home",+}));++vi.mock("@/store", () => ({+ useActuatorV1Store: () => ({+ enableOnboarding: true,+ setupSample: mocks.setupSample,+ }),+ useAppFeature: () => ({ value: 0 }),+ useProjectV1Store: () => ({+ getOrFetchProjectByName: mocks.getOrFetchProjectByName,+ createProject: mocks.createProject,+ }),+ useRoleStore: () => ({+ fetchRoleList: mocks.fetchRoleList,+ }),+ useSettingV1Store: () => ({+ updateWorkspaceProfile: mocks.updateWorkspaceProfile,+ }),+ useWorkspaceV1Store: () => ({+ fetchIamPolicy: mocks.fetchIamPolicy,+ }),+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/react/components/auth/AuthFooter", () => ({+ AuthFooter: () => null,+}));++vi.mock("@/react/components/ComponentPermissionGuard", () => ({+ ComponentPermissionGuard: ({ children }: { children: React.ReactNode }) =>+ children,+}));++vi.mock("@/react/components/ResourceIdField", async () => {+ const React = await import("react");+ return {+ ResourceIdField: ({+ validate,+ onValidationChange,+ }: {+ validate?: (+ value: string+ ) => Promise<{ type: string; message: string }[]>;+ onValidationChange?: (valid: boolean) => void;+ }) => {+ React.useEffect(() => {+ validate?.("new-project").then((messages) => {+ onValidationChange?.(messages.length === 0);+ });+ }, [validate, onValidationChange]);+ return React.createElement("div", {+ "data-testid": "resource-id-field",+ });+ },+ };+});++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, unknown>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key,+ }),+}));++vi.mock("@/utils/connect", () => ({+ getErrorCode: (error: unknown) =>+ error instanceof ConnectError ? error.code : Code.Unknown,+ extractGrpcErrorMessage: (error: unknown) =>+ error instanceof ConnectError ? error.message : String(error),+}));++let SetupPage: typeof import("./SetupPage").SetupPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ });++beforeEach(async () => {+ vi.clearAllMocks();+ ({ SetupPage } = await import("./SetupPage"));+});++describe("SetupPage", () => {+ test("allows advancing with a new project resource id", async () => {+ const { container, render, unmount } = renderIntoContainer(<SetupPage />);+ render();+ await flushPromises();++ const nextButton = () =>+ Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(+ (button) => button.textContent === "→"+ );++ expect(nextButton()).toBeTruthy();+ act(() => {+ nextButton()?.click();+ });+ await flushPromises();++ expect(mocks.getOrFetchProjectByName).toHaveBeenCalledWith(+ "projects/new-project",+ true+ );+ expect(nextButton()?.disabled).toBe(false);++ unmount();+ });++ test("blocks advancing when project lookup fails for reasons other than NotFound", async () => {+ mocks.getOrFetchProjectByName.mockRejectedValueOnce(+ new ConnectError("backend unavailable", Code.Unavailable)+ );++ const { container, render, unmount } = renderIntoContainer(<SetupPage />);+ render();+ await flushPromises();++ const nextButton = () =>+ Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(+ (button) => button.textContent === "→"+ );++ expect(nextButton()).toBeTruthy();+ act(() => {+ nextButton()?.click();+ });+ await flushPromises();++ expect(nextButton()).toBeTruthy();+ expect(nextButton()?.disabled).toBe(true);++ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/SetupPage.tsx b/frontend/src/react/pages/auth/SetupPage.tsxnew file mode 100644index 0000000000..e4a466771e--- /dev/null+++ b/frontend/src/react/pages/auth/SetupPage.tsx@@ -0,0 +1,366 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import { Code } from "@connectrpc/connect";+import { Loader2 } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { AuthFooter } from "@/react/components/auth/AuthFooter";+import { ComponentPermissionGuard } from "@/react/components/ComponentPermissionGuard";+import {+ ResourceIdField,+ type ResourceIdFieldRef,+} from "@/react/components/ResourceIdField";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { RadioGroup, RadioGroupItem } from "@/react/components/ui/radio-group";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";+import {+ useActuatorV1Store,+ useAppFeature,+ useProjectV1Store,+ useRoleStore,+ useSettingV1Store,+ useWorkspaceV1Store,+} from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";+import { unknownProject } from "@/types/v1/project";+import { extractGrpcErrorMessage, getErrorCode } from "@/utils/connect";++type Purpose = "edit-schema" | "query-data";+type Workflow = "simple" | "team";+type DataChoice = "self-setup" | "builtin-sample";++const SETUP_PERMISSIONS = [+ "bb.settings.get",+ "bb.settings.setWorkspaceProfile",+ "bb.projects.create",+ "bb.roles.list",+ "bb.workspaces.getIamPolicy",+] as const;++const homePath = (mode?: DatabaseChangeMode) => {+ if (mode === DatabaseChangeMode.EDITOR) {+ return { name: SQL_EDITOR_HOME_MODULE };+ }+ return "/";+};++export function SetupPage() {+ const [ready, setReady] = useState(false);++ useEffect(() => {+ (async () => {+ await router.isReady();+ try {+ await Promise.all([+ useRoleStore().fetchRoleList(),+ useWorkspaceV1Store().fetchIamPolicy(),+ ]);+ } catch (error) {+ // Roles/IAM pre-fetch failed — proceed to render the wizard anyway.+ // The wizard's own RPC calls surface their errors; blocking setup+ // on a prefetch failure leaves the page stuck on a spinner.+ console.error("Setup prefetch failed:", error);+ }+ setReady(true);+ })();+ }, []);++ return (+ <>+ <ComponentPermissionGuard permissions={[...SETUP_PERMISSIONS]}>+ {ready ? (+ <SetupWizard />+ ) : (+ <div className="w-full h-full flex items-center justify-center">+ <Loader2 className="size-6 animate-spin" />+ </div>+ )}+ </ComponentPermissionGuard>+ <AuthFooter />+ </>+ );+}++function SetupWizard() {+ const { t } = useTranslation();+ const [currentStep, setCurrentStep] = useState(0);+ const [purpose, setPurpose] = useState<Purpose>("edit-schema");+ const [workflow, setWorkflow] = useState<Workflow>("team");+ const [data, setData] = useState<DataChoice>("self-setup");+ const [mode, setMode] = useState<DatabaseChangeMode>(+ DatabaseChangeMode.PIPELINE+ );+ const [projectTitle, setProjectTitle] = useState("New Project");+ const [resourceId, setResourceId] = useState("");+ const [loading, setLoading] = useState(false);++ const resourceFieldRef = useRef<ResourceIdFieldRef>(null);+ const [resourceValid, setResourceValid] = useState(false);++ const enableOnboarding = useVueState(+ () => useActuatorV1Store().enableOnboarding+ );+ const databaseChangeMode = useVueState(+ () => useAppFeature("bb.feature.database-change-mode").value+ );++ useEffect(() => {+ if (!enableOnboarding) {+ router.push(homePath(databaseChangeMode));+ }+ }, [enableOnboarding, databaseChangeMode]);++ const steps = [+ t("setup.basic-info"),+ t("setup.self"),+ t("settings.general.workspace.default-landing-page.self"),+ ];++ const canAdvance = (() => {+ if (currentStep === 1 && data === "self-setup") {+ return !!projectTitle && resourceValid;+ }+ return !loading;+ })();++ const changeStepIndex = (next: number) => {+ if (next === steps.length - 1) {+ if (purpose === "query-data" && workflow === "simple") {+ setMode(DatabaseChangeMode.EDITOR);+ } else {+ setMode(DatabaseChangeMode.PIPELINE);+ }+ }+ setCurrentStep(next);+ };++ const projectV1Store = useProjectV1Store();++ const skip = () => router.push("/");++ const finish = async () => {+ if (loading) return;+ setLoading(true);+ try {+ if (data === "self-setup") {+ const project = { ...unknownProject(), title: projectTitle };+ await projectV1Store.createProject(project, resourceId);+ } else {+ await useActuatorV1Store().setupSample();+ }+ await useSettingV1Store().updateWorkspaceProfile({+ payload: { databaseChangeMode: mode },+ updateMask: create(FieldMaskSchema, {+ paths: ["value.workspace_profile.database_change_mode"],+ }),+ });+ router.push(homePath(mode));+ } finally {+ setLoading(false);+ }+ };++ const validateProjectResourceID = useCallback(+ async (id: string) => {+ try {+ await projectV1Store.getOrFetchProjectByName(+ `${projectNamePrefix}${id}`,+ true /* silent */+ );+ return [+ {+ type: "error" as const,+ message: t("resource-id.validation.duplicated", {+ resource: "project",+ }),+ },+ ];+ } catch (error) {+ if (getErrorCode(error) === Code.NotFound) {+ return [];+ }+ return [+ {+ type: "error" as const,+ message: extractGrpcErrorMessage(error),+ },+ ];+ }+ },+ [projectV1Store, t]+ );++ return (+ <div className="w-full mx-auto max-w-2xl py-6 px-4 flex flex-col gap-4">+ <div className="sticky top-0 bg-white z-10 pb-4 border-b border-control-border">+ <ol className="flex items-center gap-x-4 text-sm">+ {steps.map((label, i) => (+ <li+ key={label}+ className={+ i === currentStep+ ? "text-accent font-medium"+ : "text-control-light"+ }+ >+ {i + 1}. {label}+ </li>+ ))}+ </ol>+ </div>++ {currentStep === 0 && (+ <div className="w-full flex flex-col gap-6 py-4">+ <div className="flex flex-col gap-y-2">+ <p>{t("setup.purposes.self")}</p>+ <RadioGroup+ value={purpose}+ onValueChange={(v) => setPurpose(v as Purpose)}+ className="flex-col items-start gap-y-2"+ >+ <RadioGroupItem value="edit-schema">+ {t("setup.purposes.alter-schema")}+ </RadioGroupItem>+ <RadioGroupItem value="query-data">+ {t("setup.purposes.query-data")}+ </RadioGroupItem>+ </RadioGroup>+ </div>+ <div className="flex flex-col gap-y-2">+ <p>{t("setup.workflow.self")}</p>+ <RadioGroup+ value={workflow}+ onValueChange={(v) => setWorkflow(v as Workflow)}+ className="flex-col items-start gap-y-2"+ >+ <RadioGroupItem value="team">+ {t("setup.workflow.team")}+ </RadioGroupItem>+ <RadioGroupItem value="simple">+ {t("setup.workflow.simple")}+ </RadioGroupItem>+ </RadioGroup>+ </div>+ </div>+ )}++ {currentStep === 1 && (+ <div className="w-full flex flex-col gap-2 py-4">+ <RadioGroup+ value={data}+ onValueChange={(v) => setData(v as DataChoice)}+ className="flex-col items-start gap-y-6"+ >+ <div>+ <RadioGroupItem value="self-setup">+ <div className="font-medium">{t("setup.data.self-setup")}</div>+ </RadioGroupItem>+ {data === "self-setup" && (+ <div className="mt-2 ml-6 flex flex-col gap-y-1">+ <Input+ value={projectTitle}+ required+ placeholder={t("project.create-modal.project-name")}+ onChange={(e) => setProjectTitle(e.target.value)}+ />+ <ResourceIdField+ ref={resourceFieldRef}+ value={resourceId}+ resourceType="project"+ resourceName={projectTitle}+ resourceTitle={projectTitle}+ validate={validateProjectResourceID}+ onChange={setResourceId}+ onValidationChange={setResourceValid}+ />+ </div>+ )}+ </div>+ <div>+ <RadioGroupItem value="builtin-sample">+ <div className="flex flex-col gap-1">+ <div className="font-medium">{t("setup.data.built-in")}</div>+ <div>{t("setup.data.built-in-desc")}</div>+ </div>+ </RadioGroupItem>+ </div>+ </RadioGroup>+ </div>+ )}++ {currentStep === 2 && (+ <div className="py-4 flex flex-col gap-6">+ <div className="font-medium">+ {t("settings.general.workspace.default-landing-page.self")}+ </div>+ <RadioGroup+ value={String(mode)}+ onValueChange={(v) => setMode(Number(v) as DatabaseChangeMode)}+ className="flex-col items-start gap-y-6"+ >+ <RadioGroupItem value={String(DatabaseChangeMode.PIPELINE)}>+ <div className="flex flex-col gap-1">+ <div className="textinfo">+ {t(+ "settings.general.workspace.default-landing-page.workspace.self"+ )}+ </div>+ <div className="textinfolabel">+ {t(+ "settings.general.workspace.default-landing-page.workspace.description"+ )}+ </div>+ </div>+ </RadioGroupItem>+ <RadioGroupItem value={String(DatabaseChangeMode.EDITOR)}>+ <div className="flex flex-col gap-1">+ <div className="textinfo">+ {t(+ "settings.general.workspace.default-landing-page.sql-editor.self"+ )}+ </div>+ <div className="textinfolabel">+ {t(+ "settings.general.workspace.default-landing-page.sql-editor.description"+ )}+ </div>+ </div>+ </RadioGroupItem>+ </RadioGroup>+ </div>+ )}++ <div className="flex items-center justify-between pt-4 border-t border-control-border">+ <Button variant="ghost" onClick={skip}>+ {t("setup.skip-setup")}+ </Button>+ <div className="flex items-center gap-x-2">+ {currentStep > 0 && (+ <Button+ variant="outline"+ onClick={() => changeStepIndex(currentStep - 1)}+ >+ ←+ </Button>+ )}+ {currentStep < steps.length - 1 ? (+ <Button+ onClick={() => changeStepIndex(currentStep + 1)}+ disabled={!canAdvance}+ >+ →+ </Button>+ ) : (+ <Button onClick={finish} disabled={loading}>+ {t("common.confirm")}+ </Button>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/pages/auth/SigninAdminPage.tsx b/frontend/src/react/pages/auth/SigninAdminPage.tsxnew file mode 100644index 0000000000..d4891b24b6--- /dev/null+++ b/frontend/src/react/pages/auth/SigninAdminPage.tsx@@ -0,0 +1,42 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { AuthFooter } from "@/react/components/auth/AuthFooter";+import { PasswordSigninForm } from "@/react/components/auth/PasswordSigninForm";+import { BytebaseLogo } from "@/react/components/BytebaseLogo";+import { useAuthStore } from "@/store";+import type { LoginRequest } from "@/types/proto-es/v1/auth_service_pb";++export function SigninAdminPage() {+ const { t } = useTranslation();+ const [isLoading, setIsLoading] = useState(false);++ const trySignin = async (request: LoginRequest) => {+ if (isLoading) return;+ setIsLoading(true);+ try {+ await useAuthStore().login({ request, redirect: true });+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <>+ <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">+ <BytebaseLogo className="mx-auto mb-8" />++ <div className="rounded-sm border border-control-border bg-white p-6">+ <p className="text-xl pl-1 font-medium mb-4">+ {t("common.sign-in-as-admin")}+ </p>+ <PasswordSigninForm+ loading={isLoading}+ showForgotPassword={false}+ onSignin={trySignin}+ />+ </div>+ </div>+ <AuthFooter />+ </>+ );+}diff --git a/frontend/src/react/pages/auth/SigninPage.test.tsx b/frontend/src/react/pages/auth/SigninPage.test.tsxnew file mode 100644index 0000000000..a7f3de908c--- /dev/null+++ b/frontend/src/react/pages/auth/SigninPage.test.tsx@@ -0,0 +1,155 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),+ routerPush: vi.fn(),+ currentRoute: {+ value: { query: {} as Record<string, string | undefined> },+ },+ pushNotification: vi.fn(),+ openWindowForSSO: vi.fn(),+ actuatorStore: null as unknown,+ identityProviderStore: null as unknown,+ authStore: null as unknown,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/router", () => ({+ router: {+ push: mocks.routerPush,+ currentRoute: mocks.currentRoute,+ },+}));++vi.mock("@/router/auth", () => ({+ AUTH_SIGNUP_MODULE: "auth.signup",+}));++vi.mock("@/store", () => ({+ pushNotification: mocks.pushNotification,+ useActuatorV1Store: () => mocks.actuatorStore,+ useAuthStore: () => mocks.authStore,+ useIdentityProviderStore: () => mocks.identityProviderStore,+}));++vi.mock("@/utils", () => ({+ openWindowForSSO: mocks.openWindowForSSO,+ resolveWorkspaceName: () => undefined,+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, vars?: Record<string, unknown>) =>+ vars ? `${key}:${JSON.stringify(vars)}` : key,+ }),+}));++vi.mock("@/react/components/BytebaseLogo", () => ({+ BytebaseLogo: () => null,+}));++vi.mock("@/react/components/auth/AuthFooter", () => ({+ AuthFooter: () => null,+}));++let SigninPage: typeof import("./SigninPage").SigninPage;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++const flushPromises = () =>+ act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.currentRoute.value.query = {};+ mocks.actuatorStore = {+ serverInfo: {+ restriction: {+ disallowPasswordSignin: true,+ allowEmailCodeSignin: false,+ disallowSignup: false,+ },+ },+ isDemo: false,+ isSaaSMode: false,+ activeUserCount: 1,+ fetchServerInfo: vi.fn(async () => ({})),+ };+ mocks.identityProviderStore = {+ identityProviderList: [+ {+ name: "idps/corp-ldap",+ title: "Corp LDAP",+ type: IdentityProviderType.LDAP,+ },+ ],+ fetchIdentityProviderList: vi.fn(async () => [+ {+ name: "idps/corp-ldap",+ title: "Corp LDAP",+ type: IdentityProviderType.LDAP,+ },+ ]),+ };+ mocks.authStore = {+ login: vi.fn(async () => {}),+ };+ ({ SigninPage } = await import("./SigninPage"));+});++describe("SigninPage", () => {+ test("renders a username text field for LDAP tabs", async () => {+ const { container, render, unmount } = renderIntoContainer(<SigninPage />);+ render();+ await flushPromises();++ const usernameInput = container.querySelector<HTMLInputElement>(+ 'input#username[type="text"]'+ );+ expect(usernameInput).toBeTruthy();+ expect(usernameInput?.placeholder).toBe("jim");+ expect(usernameInput?.getAttribute("autocomplete")).toBe("username");++ const passwordInput = container.querySelector<HTMLInputElement>(+ 'input#password[type="password"]'+ );+ expect(passwordInput).toBeTruthy();+ expect(passwordInput?.getAttribute("autocomplete")).toBe(+ "current-password"+ );++ const emailInput = container.querySelector('input#email[type="email"]');+ expect(emailInput).toBeNull();++ unmount();+ });+});diff --git a/frontend/src/react/pages/auth/SigninPage.tsx b/frontend/src/react/pages/auth/SigninPage.tsxnew file mode 100644index 0000000000..3e2591c7a8--- /dev/null+++ b/frontend/src/react/pages/auth/SigninPage.tsx@@ -0,0 +1,297 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { AuthFooter } from "@/react/components/auth/AuthFooter";+import { DemoSigninForm } from "@/react/components/auth/DemoSigninForm";+import { EmailCodeSigninForm } from "@/react/components/auth/EmailCodeSigninForm";+import { PasswordSigninForm } from "@/react/components/auth/PasswordSigninForm";+import { BytebaseLogo } from "@/react/components/BytebaseLogo";+import { Alert, AlertTitle } from "@/react/components/ui/alert";+import { Button } from "@/react/components/ui/button";+import {+ Tabs,+ TabsList,+ TabsPanel,+ TabsTrigger,+} from "@/react/components/ui/tabs";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { AUTH_SIGNUP_MODULE } from "@/router/auth";+import {+ pushNotification,+ useActuatorV1Store,+ useAuthStore,+ useIdentityProviderStore,+} from "@/store";+import { idpNamePrefix } from "@/store/modules/v1/common";+import type { LoginRequest } from "@/types/proto-es/v1/auth_service_pb";+import type { IdentityProvider } from "@/types/proto-es/v1/idp_service_pb";+import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";+import { openWindowForSSO, resolveWorkspaceName } from "@/utils";++export type SigninPageProps = {+ readonly redirect?: boolean;+ readonly redirectUrl?: string;+ readonly allowSignup?: boolean;+ readonly hideFooter?: boolean;+ readonly footerOverride?: React.ReactNode;+};++export function SigninPage(props: SigninPageProps) {+ const {+ redirect = true,+ redirectUrl,+ allowSignup: allowSignupProp = true,+ hideFooter = false,+ footerOverride,+ } = props;+ const { t } = useTranslation();+ const [isLoading, setIsLoading] = useState(false);+ const [initialized, setInitialized] = useState(false);++ const serverInfo = useVueState(() => useActuatorV1Store().serverInfo);+ const isDemo = useVueState(() => useActuatorV1Store().isDemo);+ const isSaaSMode = useVueState(() => useActuatorV1Store().isSaaSMode);+ const activeUserCount = useVueState(+ () => useActuatorV1Store().activeUserCount+ );+ const identityProviders = useVueState(+ () => useIdentityProviderStore().identityProviderList+ );++ const query = router.currentRoute.value.query;+ const invitedEmail = (query.email as string | undefined) ?? "";++ const disallowSignup =+ !allowSignupProp || !!serverInfo?.restriction?.disallowSignup;++ const separatedIdps = identityProviders.filter(+ (idp) => idp.type !== IdentityProviderType.LDAP+ );+ const groupedIdps = identityProviders.filter(+ (idp) => idp.type === IdentityProviderType.LDAP+ );++ const showSignInForm =+ !serverInfo?.restriction?.disallowPasswordSignin ||+ groupedIdps.length > 0 ||+ serverInfo?.restriction?.allowEmailCodeSignin;++ const defaultTab = (() => {+ if (serverInfo?.restriction?.allowEmailCodeSignin) return "email-code";+ if (!serverInfo?.restriction?.disallowPasswordSignin) return "standard";+ if (groupedIdps.length > 0) return groupedIdps[0].name;+ return "standard";+ })();++ // Redirect to signup when an admin setup is needed.+ useEffect(() => {+ if (!initialized) return;+ if (activeUserCount === 0 && !disallowSignup && !isSaaSMode) {+ router.push({ name: AUTH_SIGNUP_MODULE, replace: true });+ }+ }, [initialized, activeUserCount, disallowSignup, isSaaSMode]);++ const trySigninWithIdp = async (idp: IdentityProvider) => {+ try {+ await openWindowForSSO(idp, false, query.redirect as string);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Request error occurred",+ description: (error as Error).message,+ });+ }+ };++ const trySignin = async (request: LoginRequest) => {+ if (isLoading) return;+ setIsLoading(true);+ try {+ await useAuthStore().login({+ request,+ redirect,+ redirectUrl,+ });+ } finally {+ setIsLoading(false);+ }+ };++ // Initial load: fetch server info + IDPs + handle `idp` query param.+ // Ref guard is critical — the `?idp=<name>` path triggers an SSO redirect+ // via `trySigninWithIdp`, which must not fire twice under StrictMode.+ const initRef = useRef(false);+ useEffect(() => {+ if (initRef.current) return;+ initRef.current = true;+ (async () => {+ const workspaceName = resolveWorkspaceName();+ const idpStore = useIdentityProviderStore();+ const actuatorStore = useActuatorV1Store();+ try {+ const [idpList] = await Promise.all([+ idpStore.fetchIdentityProviderList(workspaceName),+ actuatorStore.fetchServerInfo(workspaceName),+ ]);+ if (idpList.length === 0 && workspaceName) {+ await idpStore.fetchIdentityProviderList();+ }+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Request error occurred",+ description: (error as Error).message,+ });+ }+ const idpQuery = query.idp;+ if (idpQuery) {+ const name = `${idpNamePrefix}${idpQuery}`;+ const idp = idpStore.identityProviderList.find(+ (i: IdentityProvider) => i.name === name+ );+ if (idp) {+ // On success this navigates away; on failure `trySigninWithIdp`+ // pushes a notification and we still need to show the form so the+ // user can recover (e.g., pick a different IdP or retry).+ await trySigninWithIdp(idp);+ }+ }+ setInitialized(true);+ })();+ }, []);++ if (!initialized) {+ return (+ <div className="inset-0 absolute flex flex-row justify-center items-center">+ <div className="h-6 w-6 border-2 border-control-border border-t-accent rounded-full animate-spin" />+ </div>+ );+ }++ return (+ <>+ <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">+ <BytebaseLogo className="mx-auto mb-8" />++ {invitedEmail && (+ <Alert variant="info" className="mb-4 mt-4">+ <AlertTitle>+ {t("auth.sign-in.invited-email", { email: invitedEmail })}+ </AlertTitle>+ </Alert>+ )}++ {showSignInForm && (+ <div className="rounded-sm border border-control-border bg-white p-4">+ <Tabs defaultValue={defaultTab}>+ <TabsList>+ {!serverInfo?.restriction?.disallowPasswordSignin && (+ <TabsTrigger value="standard">Standard</TabsTrigger>+ )}+ {serverInfo?.restriction?.allowEmailCodeSignin && (+ <TabsTrigger value="email-code">+ {t("auth.sign-in.email-code-tab")}+ </TabsTrigger>+ )}+ {groupedIdps.map((idp) => (+ <TabsTrigger key={idp.name} value={idp.name}>+ {idp.title}+ </TabsTrigger>+ ))}+ </TabsList>+ {!serverInfo?.restriction?.disallowPasswordSignin && (+ <TabsPanel value="standard" className="pt-3">+ {isDemo ? (+ <DemoSigninForm loading={isLoading} onSignin={trySignin} />+ ) : (+ <>+ <PasswordSigninForm+ loading={isLoading}+ onSignin={trySignin}+ />+ {!disallowSignup && (+ <div className="mt-3 flex justify-center items-center text-sm text-control gap-x-2">+ <span>{t("auth.sign-in.new-user")}</span>+ <a+ href="#"+ className="accent-link"+ onClick={(e) => {+ e.preventDefault();+ router.push({+ name: AUTH_SIGNUP_MODULE,+ query,+ });+ }}+ >+ {t("common.sign-up")}+ </a>+ </div>+ )}+ </>+ )}+ </TabsPanel>+ )}+ {serverInfo?.restriction?.allowEmailCodeSignin && (+ <TabsPanel value="email-code" className="pt-3">+ <EmailCodeSigninForm+ loading={isLoading}+ onSignin={trySignin}+ />+ </TabsPanel>+ )}+ {groupedIdps.map((idp) => (+ <TabsPanel key={idp.name} value={idp.name} className="pt-3">+ <PasswordSigninForm+ loading={isLoading}+ showForgotPassword={false}+ credentialLabel={t("common.username")}+ credentialPlaceholder="jim"+ credentialInputType="text"+ credentialAutocomplete="username"+ onSignin={(req) => trySignin({ ...req, idpName: idp.name })}+ />+ </TabsPanel>+ ))}+ </Tabs>+ </div>+ )}++ {separatedIdps.length > 0 && (+ <div className="mb-3 px-1">+ {showSignInForm && (+ <div className="relative my-4">+ <div+ aria-hidden="true"+ className="absolute inset-0 flex items-center"+ >+ <div className="w-full border-t border-control-border" />+ </div>+ <div className="relative flex justify-center text-sm">+ <span className="px-2 bg-white text-control">+ {t("common.or")}+ </span>+ </div>+ </div>+ )}+ {separatedIdps.map((idp) => (+ <div key={idp.name} className="w-full mb-2">+ <Button+ variant="outline"+ size="lg"+ className="w-full"+ onClick={() => trySigninWithIdp(idp)}+ >+ {t("auth.sign-in.sign-in-with-idp", { idp: idp.title })}+ </Button>+ </div>+ ))}+ </div>+ )}+ </div>++ {footerOverride ?? (hideFooter ? null : <AuthFooter />)}+ </>+ );+}diff --git a/frontend/src/react/pages/auth/SignupPage.tsx b/frontend/src/react/pages/auth/SignupPage.tsxnew file mode 100644index 0000000000..8d5ee32803--- /dev/null+++ b/frontend/src/react/pages/auth/SignupPage.tsx@@ -0,0 +1,247 @@+import { useEffect, useState } from "react";+import { Trans, useTranslation } from "react-i18next";+import { AuthFooter } from "@/react/components/auth/AuthFooter";+import { UserPasswordFields } from "@/react/components/auth/UserPasswordFields";+import { computePasswordValidation } from "@/react/components/auth/userPasswordValidation";+import { BytebaseLogo } from "@/react/components/BytebaseLogo";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import { AUTH_SIGNIN_MODULE } from "@/router/auth";+import { useActuatorV1Store, useAuthStore } from "@/store";+import { isValidEmail } from "@/utils";++export function SignupPage() {+ const { t } = useTranslation();+ const [email, setEmail] = useState("");+ const [password, setPassword] = useState("");+ const [passwordConfirm, setPasswordConfirm] = useState("");+ const [name, setName] = useState("");+ const [nameManuallyEdited, setNameManuallyEdited] = useState(false);+ const [isLoading, setIsLoading] = useState(false);++ const activeUserCount = useVueState(+ () => useActuatorV1Store().activeUserCount+ );+ const serverInfo = useVueState(() => useActuatorV1Store().serverInfo);+ const needAdminSetup = activeUserCount === 0;++ const [acceptTermsAndPolicy, setAcceptTermsAndPolicy] = useState(+ !needAdminSetup+ );++ const query = router.currentRoute.value.query;++ useEffect(() => {+ if (!needAdminSetup && serverInfo?.restriction?.disallowSignup) {+ router.replace({ name: AUTH_SIGNIN_MODULE, query });+ }+ if (needAdminSetup) {+ setAcceptTermsAndPolicy(false);+ }+ }, []);++ const passwordRestriction = serverInfo?.restriction?.passwordRestriction;+ const validation = computePasswordValidation(+ password,+ passwordConfirm,+ passwordRestriction+ );++ const allowSignup =+ isValidEmail(email) &&+ password.length > 0 &&+ name.length > 0 &&+ !validation.hint &&+ !validation.mismatch &&+ acceptTermsAndPolicy &&+ !serverInfo?.restriction?.disallowSignup;++ const onEmailChange = (value: string) => {+ const normalized = value.trim().toLowerCase();+ setEmail(normalized);+ if (!nameManuallyEdited) {+ const parts = normalized.split("@");+ if (parts.length > 0 && parts[0].length > 0) {+ const candidate = parts[0].replace("_", ".");+ const segments = candidate.split(".");+ if (segments.length >= 2) {+ setName(+ [+ segments[0].charAt(0).toUpperCase() + segments[0].slice(1),+ segments[1].charAt(0).toUpperCase() + segments[1].slice(1),+ ].join(" ")+ );+ } else {+ setName(candidate.charAt(0).toUpperCase() + candidate.slice(1));+ }+ }+ }+ };++ const onNameChange = (value: string) => {+ setName(value);+ setNameManuallyEdited(value.trim().length > 0);+ };++ const trySignup = async (e: React.FormEvent) => {+ e.preventDefault();+ if (isLoading) return;+ setIsLoading(true);+ try {+ await useAuthStore().signup({ email, password, name });+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <>+ <div className="h-full flex flex-col justify-center mx-auto w-full max-w-sm">+ <div>+ <BytebaseLogo className="mx-auto mb-8" />+ <h2 className="text-2xl leading-9 font-medium text-main mt-4">+ {needAdminSetup ? (+ <p className="text-accent font-semibold text-center">+ <Trans+ i18nKey="auth.sign-up.admin-title"+ components={{+ account: <span className="text-accent font-semibold" />,+ }}+ />+ </p>+ ) : (+ <span>{t("auth.sign-up.title")}</span>+ )}+ </h2>+ </div>++ <div className="mt-8">+ <form className="flex flex-col gap-y-6 mt-6" onSubmit={trySignup}>+ <div>+ <label+ htmlFor="email"+ className="block text-sm font-medium leading-5 text-control"+ >+ {t("common.email")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="mt-1 rounded-md shadow-xs">+ <Input+ id="email"+ type="email"+ required+ placeholder="[email protected]"+ value={email}+ onChange={(e) => onEmailChange(e.target.value)}+ />+ </div>+ </div>++ <UserPasswordFields+ password={password}+ passwordConfirm={passwordConfirm}+ onPasswordChange={setPassword}+ onPasswordConfirmChange={setPasswordConfirm}+ passwordRestriction={passwordRestriction}+ />++ <div>+ <label+ htmlFor="name"+ className="block text-sm font-medium leading-5 text-control"+ >+ {t("common.username")}+ <span className="text-error ml-0.5">*</span>+ </label>+ <div className="mt-1 rounded-md shadow-xs">+ <Input+ id="name"+ required+ placeholder="Jim Gray"+ value={name}+ onChange={(e) => onNameChange(e.target.value)}+ />+ </div>+ </div>++ {needAdminSetup && (+ <div className="w-full flex flex-row justify-start items-start gap-x-2">+ <input+ id="accept-terms"+ type="checkbox"+ checked={acceptTermsAndPolicy}+ onChange={(e) => setAcceptTermsAndPolicy(e.target.checked)}+ />+ <label+ htmlFor="accept-terms"+ className="select-none text-sm text-control"+ >+ <Trans+ i18nKey="auth.sign-up.accept-terms-and-policy"+ components={{+ terms: (+ <a+ href="https://www.bytebase.com/terms?source=console"+ className="text-accent"+ />+ ),+ policy: (+ <a+ href="https://www.bytebase.com/privacy?source=console"+ className="text-accent"+ />+ ),+ }}+ />+ </label>+ </div>+ )}++ <div className="w-full">+ <Button+ type="submit"+ size="lg"+ className="w-full"+ disabled={!allowSignup || isLoading}+ >+ {needAdminSetup+ ? t("auth.sign-up.create-admin-account")+ : t("common.sign-up")}+ </Button>+ </div>+ </form>+ </div>++ {!needAdminSetup && (+ <div className="mt-6 relative">+ <div+ aria-hidden="true"+ className="absolute inset-0 flex items-center"+ >+ <div className="w-full border-t border-control-border" />+ </div>+ <div className="relative flex justify-center text-sm">+ <span className="pl-2 bg-white text-control">+ {t("auth.sign-up.existing-user")}+ </span>+ <a+ href="#"+ className="accent-link px-2 bg-white"+ onClick={(e) => {+ e.preventDefault();+ router.push({ name: AUTH_SIGNIN_MODULE, query });+ }}+ >+ {t("common.sign-in")}+ </a>+ </div>+ </div>+ )}+ </div>++ <AuthFooter />+ </>+ );+}diff --git a/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx b/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsxnew file mode 100644index 0000000000..f0342b916a--- /dev/null+++ b/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx@@ -0,0 +1,20 @@+import { useTranslation } from "react-i18next";+import { Alert, AlertDescription } from "@/react/components/ui/alert";+import { TwoFactorSetupPage } from "@/react/pages/settings/two-factor/TwoFactorSetupPage";+import { useAuthStore } from "@/store";++export function TwoFactorRequiredPage() {+ const { t } = useTranslation();+ return (+ <div className="w-full">+ <Alert variant="warning">+ <AlertDescription>+ {t("two-factor.messages.2fa-required")}+ </AlertDescription>+ </Alert>+ <div className="w-full p-2 sm:p-8 sm:px-16">+ <TwoFactorSetupPage cancelAction={() => useAuthStore().logout()} />+ </div>+ </div>+ );+}diff --git a/frontend/src/router/auth.ts b/frontend/src/router/auth.tsindex b58c310b13..b1a7355c32 100644--- a/frontend/src/router/auth.ts+++ b/frontend/src/router/auth.ts@@ -13,6 +13,10 @@ export const AUTH_OIDC_CALLBACK_MODULE = "auth.oidc.callback";export const AUTH_2FA_SETUP_MODULE = "auth.2fa.setup";export const OAUTH2_CONSENT_MODULE = "oauth2.consent";+// Every auth/consent route renders a React page mounted by ReactPageMount.vue.+// The `page` prop names the React component registered in @/react/mount.ts.+const reactPage = () => import("@/react/ReactPageMount.vue");+const authRoutes: RouteRecordRaw[] = [{path: "/oauth2/consent",@@ -22,7 +26,8 @@ const authRoutes: RouteRecordRaw[] = [path: "",name: OAUTH2_CONSENT_MODULE,meta: { title: () => t("oauth2.consent.title") },- component: () => import("@/views/OAuth2Consent.vue"),+ component: reactPage,+ props: { page: "OAuth2ConsentPage" },},],},@@ -36,56 +41,65 @@ const authRoutes: RouteRecordRaw[] = [alias: "signin",name: AUTH_SIGNIN_MODULE,meta: { title: () => t("common.sign-in") },- component: () => import("@/views/auth/Signin.vue"),+ component: reactPage,+ props: { page: "SigninPage" },},{// We need the admin as the backdoor for the workspace admin.path: "admin",name: AUTH_SIGNIN_ADMIN_MODULE,meta: { title: () => t("common.sign-in-as-admin") },- component: () => import("@/views/auth/SigninAdmin.vue"),+ component: reactPage,+ props: { page: "SigninAdminPage" },},{path: "signup",name: AUTH_SIGNUP_MODULE,meta: { title: () => t("common.sign-up") },- component: () => import("@/views/auth/Signup.vue"),+ component: reactPage,+ props: { page: "SignupPage" },},{path: "password-forgot",name: AUTH_PASSWORD_FORGOT_MODULE,meta: { title: () => `${t("auth.password-forgot")}` },- component: () => import("@/views/auth/PasswordForgot.vue"),+ component: reactPage,+ props: { page: "PasswordForgotPage" },},{path: "password-reset",name: AUTH_PASSWORD_RESET_MODULE,meta: { title: () => `${t("auth.password-reset.title")}` },- component: () => import("@/views/auth/PasswordReset.vue"),+ component: reactPage,+ props: { page: "PasswordResetPage" },},{path: "mfa",name: AUTH_MFA_MODULE,meta: { title: () => t("multi-factor.self") },- component: () => import("@/views/auth/MultiFactor.vue"),+ component: reactPage,+ props: { page: "MultiFactorPage" },},],},{path: "/oauth/callback",name: AUTH_OAUTH_CALLBACK_MODULE,- component: () => import("@/views/OAuthCallback.vue"),+ component: reactPage,+ props: { page: "OAuthCallbackPage" },},{path: "/oidc/callback",name: AUTH_OIDC_CALLBACK_MODULE,- component: () => import("@/views/OAuthCallback.vue"),+ component: reactPage,+ props: { page: "OAuthCallbackPage" },},{path: "/2fa/setup",name: AUTH_2FA_SETUP_MODULE,meta: { title: () => t("two-factor.self") },- component: () => import("@/views/TwoFactorRequired.vue"),+ component: reactPage,+ props: { page: "TwoFactorRequiredPage" },},];diff --git a/frontend/src/router/setup.ts b/frontend/src/router/setup.tsindex ceb02760f9..b62125d7b1 100644--- a/frontend/src/router/setup.ts+++ b/frontend/src/router/setup.ts@@ -22,7 +22,8 @@ const setupRoutes: RouteRecordRaw[] = ["bb.workspaces.getIamPolicy",],},- component: () => import("@/views/Setup/Setup.vue"),+ component: () => import("@/react/ReactPageMount.vue"),+ props: { page: "SetupPage" },},],},diff --git a/frontend/src/store/modules/sqlEditor/uiState.test.ts b/frontend/src/store/modules/sqlEditor/uiState.test.tsindex 8de6a09992..8df42c72e8 100644--- a/frontend/src/store/modules/sqlEditor/uiState.test.ts+++ b/frontend/src/store/modules/sqlEditor/uiState.test.ts@@ -1,15 +1,44 @@import { createPinia, setActivePinia } from "pinia";-import { beforeEach, describe, expect, test } from "vitest";+import { afterEach, beforeEach, describe, expect, test } from "vitest";import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";let useSQLEditorUIStore: typeof import("./uiState").useSQLEditorUIStore;+const originalLocalStorage = globalThis.localStorage;+const storage = new Map<string, string>();+const localStorageMock = {+ getItem: (key: string) => storage.get(key) ?? null,+ setItem: (key: string, value: string) => {+ storage.set(key, value);+ },+ removeItem: (key: string) => {+ storage.delete(key);+ },+ clear: () => {+ storage.clear();+ },+ key: (index: number) => Array.from(storage.keys())[index] ?? null,+ get length() {+ return storage.size;+ },+};beforeEach(async () => {- localStorage.clear();+ storage.clear();+ Object.defineProperty(globalThis, "localStorage", {+ value: localStorageMock,+ configurable: true,+ });setActivePinia(createPinia());({ useSQLEditorUIStore } = await import("./uiState"));});+afterEach(() => {+ Object.defineProperty(globalThis, "localStorage", {+ value: originalLocalStorage,+ configurable: true,+ });+});+describe("useSQLEditorUIStore", () => {test("initial state has documented defaults", () => {const store = useSQLEditorUIStore();diff --git a/frontend/src/views/OAuth2Consent.vue b/frontend/src/views/OAuth2Consent.vuedeleted file mode 100644index 019a266dfa..0000000000--- a/frontend/src/views/OAuth2Consent.vue+++ /dev/null@@ -1,192 +0,0 @@-<template>- <div class="mx-auto w-full max-w-sm">- <BytebaseLogo class="mx-auto mb-8" />-- <NCard v-if="state.loading">- <div class="flex justify-center py-8">- <BBSpin />- </div>- </NCard>-- <NCard v-else-if="state.error">- <div class="text-center py-4">- <p class="text-red-600 mb-4">{{ state.error }}</p>- <NButton @click="goBack">- {{ $t("common.go-back") }}- </NButton>- </div>- </NCard>-- <NCard v-else>- <div class="space-y-6">- <div class="text-center">- <h1 class="text-xl font-semibold text-gray-900 mb-2">- {{ $t("oauth2.consent.title") }}- </h1>- <p class="text-gray-600">- {{- $t("oauth2.consent.description", {- clientName: state.clientName,- })- }}- </p>- </div>-- <div class="bg-gray-50 rounded-lg p-4">- <p class="text-sm text-gray-500 mb-2">- {{ $t("oauth2.consent.permissions") }}- </p>- <ul class="text-sm text-gray-700 space-y-1">- <li class="flex items-center gap-2">- <CheckIcon class="w-4 h-4 text-green-500" />- {{ $t("oauth2.consent.permission-access") }}- </li>- </ul>- </div>-- <form method="POST" :action="authorizeUrl">- <input type="hidden" name="client_id" :value="clientId" />- <input type="hidden" name="redirect_uri" :value="redirectUri" />- <input type="hidden" name="state" :value="oauthState" />- <input type="hidden" name="code_challenge" :value="codeChallenge" />- <input- type="hidden"- name="code_challenge_method"- :value="codeChallengeMethod"- />-- <div class="flex gap-x-2">- <NButton- class="flex-1"- size="large"- :disabled="state.submitting"- @click="deny"- >- {{ $t("common.deny") }}- </NButton>- <NButton- type="primary"- class="flex-1"- size="large"- :loading="state.submitting"- attr-type="submit"- name="action"- value="allow"- >- {{ $t("common.allow") }}- </NButton>- </div>- </form>- </div>- </NCard>- </div>-</template>--<script lang="ts" setup>-import { CheckIcon } from "lucide-vue-next";-import { NButton, NCard } from "naive-ui";-import { onMounted, reactive } from "vue";-import { useRoute, useRouter } from "vue-router";-import { BBSpin } from "@/bbkit";-import BytebaseLogo from "@/components/BytebaseLogo.vue";-import { AUTH_SIGNIN_MODULE } from "@/router/auth";-import { useAuthStore } from "@/store";--interface LocalState {- loading: boolean;- submitting: boolean;- error: string;- clientName: string;-}--const route = useRoute();-const router = useRouter();-const authStore = useAuthStore();--const state = reactive<LocalState>({- loading: true,- submitting: false,- error: "",- clientName: "",-});--// Extract query parameters-const clientId = (route.query.client_id as string) || "";-const redirectUri = (route.query.redirect_uri as string) || "";-const oauthState = (route.query.state as string) || "";-const codeChallenge = (route.query.code_challenge as string) || "";-const codeChallengeMethod = (route.query.code_challenge_method as string) || "";--const authorizeUrl = "/api/oauth2/authorize";--onMounted(async () => {- // Check if user is logged in- if (!authStore.isLoggedIn) {- // Redirect to login with return URL- const returnUrl = route.fullPath;- router.replace({- name: AUTH_SIGNIN_MODULE,- query: { redirect: returnUrl },- });- return;- }-- // Validate required parameters- if (!clientId || !redirectUri || !codeChallenge || !codeChallengeMethod) {- state.error = "Missing required OAuth2 parameters";- state.loading = false;- return;- }-- // Fetch client info- try {- const response = await fetch(- `/api/oauth2/clients/${encodeURIComponent(clientId)}`- );- if (!response.ok) {- const data = await response.json();- state.error = data.error_description || "Client not found";- state.loading = false;- return;- }- const data = await response.json();- state.clientName = data.client_name || clientId;- } catch {- state.error = "Failed to load client information";- }-- state.loading = false;-});--const deny = () => {- state.submitting = true;- // Submit form with deny action- const form = document.createElement("form");- form.method = "POST";- form.action = authorizeUrl;-- const fields = [- { name: "client_id", value: clientId },- { name: "redirect_uri", value: redirectUri },- { name: "state", value: oauthState },- { name: "code_challenge", value: codeChallenge },- { name: "code_challenge_method", value: codeChallengeMethod },- { name: "action", value: "deny" },- ];-- for (const field of fields) {- const input = document.createElement("input");- input.type = "hidden";- input.name = field.name;- input.value = field.value;- form.appendChild(input);- }-- document.body.appendChild(form);- form.submit();-};--const goBack = () => {- router.back();-};-</script>diff --git a/frontend/src/views/OAuthCallback.vue b/frontend/src/views/OAuthCallback.vuedeleted file mode 100644index 32e3a11ede..0000000000--- a/frontend/src/views/OAuthCallback.vue+++ /dev/null@@ -1,205 +0,0 @@-<template>- <div class="p-4">- <div v-if="state.hasError" class="mt-2">- <div>{{ state.message }}</div>- <NButton v-if="state.oAuthState?.popup" @click="window.close()">- {{ $t("common.close") }}- </NButton>- <router-link v-else :to="{ name: AUTH_SIGNIN_MODULE }" class="btn-normal">- {{ $t("auth.back-to-signin") }}- </router-link>- </div>- <div v-else class="mt-2">- <div class="flex items-center gap-x-2">- <NSpin size="small" />- <span>{{ state.message || "Processing authentication..." }}</span>- </div>- <NButton- v-if="state.oAuthState?.popup && state.showCloseButton"- class="mt-4"- @click="window.close()"- >- {{ $t("auth.close-window") }}- </NButton>- </div>- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { NButton, NSpin } from "naive-ui";-import { onMounted, reactive } from "vue";-import { useRoute } from "vue-router";-import { AUTH_SIGNIN_MODULE } from "@/router/auth";-import { useAuthStore } from "@/store";-import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";-import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";-import { resolveWorkspaceName } from "@/utils";-import { clearOAuthState, retrieveOAuthState } from "@/utils/sso";-import type { OAuthState, OAuthWindowEventPayload } from "../types";--interface LocalState {- message: string;- hasError: boolean;- oAuthState: OAuthState | undefined;- payload: OAuthWindowEventPayload;- showCloseButton: boolean;-}--const route = useRoute();-const authStore = useAuthStore();--const state = reactive<LocalState>({- message: "",- hasError: false,- oAuthState: undefined,- payload: {- error: "",- code: "",- },- showCloseButton: false,-});--onMounted(() => {- // State parameter is now an opaque token (RFC 6749 compliant)- const stateToken = route.query.state as string;-- // Validate state token exists- if (- !stateToken ||- typeof stateToken !== "string" ||- stateToken.length === 0- ) {- state.hasError = true;- state.message =- "Authentication failed: Invalid callback state. Please try again.";- state.oAuthState = undefined;- triggerAuthCallback();- return;- }-- // Retrieve and validate stored state from localStorage using opaque token- const storedState = retrieveOAuthState(stateToken);-- if (!storedState) {- state.hasError = true;- state.message =- "Authentication failed: Session expired or invalid. Please try again.";- state.oAuthState = undefined;- triggerAuthCallback();- return;- }-- // Validate token matches (constant-time comparison via retrieval)- if (storedState.token !== stateToken) {- state.hasError = true;- state.message =- "Authentication failed: Security validation failed. Please try again.";- state.oAuthState = undefined;- clearOAuthState(stateToken);- triggerAuthCallback();- return;- }-- // State validation successful- state.oAuthState = storedState;- state.hasError = false;- state.message = "Successfully authorized. Redirecting back to Bytebase...";- state.payload.code = (route.query.code as string) || "";-- // Clear state from localStorage (single-use token)- clearOAuthState(storedState.token);-- triggerAuthCallback();-});--const triggerAuthCallback = async () => {- const { oAuthState, hasError } = state;-- // Handle popup flow with robust error handling- if (oAuthState?.popup) {- try {- // Check if opener window is available and not closed- if (!window.opener || window.opener.closed) {- state.hasError = true;- state.message =- "Authentication completed, but the parent window is no longer available. Please close this window and try again.";- state.showCloseButton = true;- return;- }-- const eventName = hasError ? "bb.oauth.unknown" : oAuthState.event;-- // Dispatch event to parent window- window.opener.dispatchEvent(- new CustomEvent(eventName, {- detail: state.payload,- })- );-- // Try to close the popup window- try {- window.close();-- // If window.close() doesn't work immediately (some browsers delay it),- // show a close button after a short delay- setTimeout(() => {- if (!window.closed) {- state.showCloseButton = true;- state.message = hasError- ? state.message- : "Authentication completed. You can close this window.";- }- }, 500);- } catch {- // Browser blocked window.close()- state.showCloseButton = true;- state.message = hasError- ? state.message- : "Authentication completed. Please close this window.";- }- } catch (error) {- console.error("Failed to communicate with opener window:", error);- state.hasError = true;- state.message =- "Authentication completed, but failed to communicate with the parent window. Please close this window and try again.";- state.showCloseButton = true;- }- return;- }-- // Handle redirect flow (non-popup)- if (hasError || !oAuthState) {- // For redirect flow, errors are already displayed in the template- return;- }-- const eventName = oAuthState.event;- if (eventName.startsWith("bb.oauth.signin")) {- // Determine context type based on the stored IdP type- // OIDC providers use oidcContext, OAuth2 providers use oauth2Context- const isOidc = oAuthState.idpType === IdentityProviderType.OIDC;- const idpName = eventName.split(".").pop();- if (!idpName) {- return;- }-- await authStore.login({- request: create(LoginRequestSchema, {- idpName,- idpContext: {- context: {- case: isOidc ? "oidcContext" : "oauth2Context",- value: {- code: state.payload.code,- },- },- },- workspace: resolveWorkspaceName(),- }),- redirect: true,- redirectUrl: oAuthState.redirect,- });- }-};-</script>diff --git a/frontend/src/views/Setup/AdminSetup.vue b/frontend/src/views/Setup/AdminSetup.vuedeleted file mode 100644index 49a11b6eb6..0000000000--- a/frontend/src/views/Setup/AdminSetup.vue+++ /dev/null@@ -1,228 +0,0 @@-<template>- <StepTab- :sticky="true"- :current-index="state.currentStep"- :step-list="STEP_LIST"- :allow-next="allowNext"- :cancel-title="$t('setup.skip-setup')"- :finish-title="$t('common.confirm')"- @cancel="() => onCancel('/')"- @update:current-index="changeStepIndex"- @finish="tryFinishSetup"- >- <template #0>- <div class="w-full flex flex-col gap-6 py-4">- <div class="flex flex-col gap-y-2">- <p>{{ $t("setup.purposes.self") }}</p>- <NRadioGroup v-model:value="state.purpose">- <NSpace vertical>- <NRadio :value="'edit-schema'">- {{ $t("setup.purposes.alter-schema") }}- </NRadio>- <NRadio :value="'query-data'">- {{ $t("setup.purposes.query-data") }}- </NRadio>- </NSpace>- </NRadioGroup>- </div>- <div class="flex flex-col gap-y-2">- <p>{{ $t("setup.workflow.self") }}</p>- <NRadioGroup v-model:value="state.workflow">- <NSpace vertical>- <NRadio :value="'team'">- {{ $t("setup.workflow.team") }}- </NRadio>- <NRadio :value="'simple'">- {{ $t("setup.workflow.simple") }}- </NRadio>- </NSpace>- </NRadioGroup>- </div>- </div>- </template>- <template #1>- <div class="w-full flex flex-col gap-2 py-4">- <NRadioGroup v-model:value="state.data">- <NSpace vertical size="large">- <NRadio :value="'self-setup'">- <div>- <p class="font-medium">{{ $t("setup.data.self-setup") }}</p>- <div>- <BBTextField- v-model:value="state.project.title"- class="mt-2 mb-1 w-full"- :required="true"- :placeholder="$t('project.create-modal.project-name')"- />- <ResourceIdField- ref="resourceIdField"- editing-class="mt-2"- resource-type="project"- :value="state.resourceId"- :resource-title="state.project.title"- :fetch-resource="- (id) =>- projectV1Store.getOrFetchProjectByName(- `${projectNamePrefix}${id}`,- true /* silent */- )- "- @update:value="state.resourceId = $event"- />- </div>- </div>- </NRadio>- <NRadio :value="'builtin-sample'">- <div>- <p class="font-medium">- {{ $t("setup.data.built-in") }}- </p>- <div>- {{ $t("setup.data.built-in-desc") }}- </div>- </div>- </NRadio>- </NSpace>- </NRadioGroup>- </div>- </template>- <template #2>- <div class="py-4">- <WorkspaceMode v-model:mode="state.mode" />- </div>- </template>- </StepTab>-</template>--<script lang="tsx" setup>-import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { NRadio, NRadioGroup, NSpace } from "naive-ui";-import { computed, onMounted, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { type RouteLocationRaw, useRouter } from "vue-router";-import { BBTextField } from "@/bbkit";-import { StepTab } from "@/components/v2";-import ResourceIdField from "@/components/v2/Form/ResourceIdField.vue";-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";-import {- useActuatorV1Store,- useAppFeature,- useProjectV1Store,- useSettingV1Store,-} from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";-import { unknownProject } from "@/types";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";-import WorkspaceMode from "./WorkspaceMode.vue";--interface LocalState {- currentStep: number;- purpose: "edit-schema" | "query-data";- data: "self-setup" | "builtin-sample";- workflow: "simple" | "team";- mode: DatabaseChangeMode;- project: Project;- resourceId: string;- loading: boolean;-}--const { t } = useI18n();-const router = useRouter();-const projectV1Store = useProjectV1Store();-const actuatorV1Store = useActuatorV1Store();-const settingStore = useSettingV1Store();--const state = reactive<LocalState>({- currentStep: 0,- purpose: "edit-schema",- workflow: "team",- data: "self-setup",- mode: DatabaseChangeMode.PIPELINE,- project: {- ...unknownProject(),- title: "New Project",- },- resourceId: "",- loading: false,-});-const resourceIdField = ref<InstanceType<typeof ResourceIdField>>();--const STEP_LIST = [- { title: t("setup.basic-info") },- { title: t("setup.self") },- { title: t("settings.general.workspace.default-landing-page.self") },-];--const allowNext = computed(() => {- if (state.currentStep === 1) {- if (state.data === "self-setup") {- return (- !!state.project.title && (resourceIdField.value?.isValidated ?? false)- );- }- } else if (state.currentStep === STEP_LIST.length - 1) {- return !state.loading;- }- return true;-});--const changeStepIndex = (nextIndex: number) => {- if (nextIndex === STEP_LIST.length - 1) {- if (state.purpose === "query-data" && state.workflow === "simple") {- state.mode = DatabaseChangeMode.EDITOR;- } else {- state.mode = DatabaseChangeMode.PIPELINE;- }- }-- state.currentStep = nextIndex;-};--const onCancel = (to: RouteLocationRaw) => {- router.push(to);-};--const getHomePageByMode = (mode?: DatabaseChangeMode) => {- if (mode === DatabaseChangeMode.EDITOR) {- return {- name: SQL_EDITOR_HOME_MODULE,- };- }- return "/";-};--const tryFinishSetup = async () => {- if (state.loading) {- return;- }- state.loading = true;-- try {- if (state.data === "self-setup") {- await projectV1Store.createProject(state.project, state.resourceId);- } else {- await actuatorV1Store.setupSample();- }- await settingStore.updateWorkspaceProfile({- payload: {- databaseChangeMode: state.mode,- },- updateMask: create(FieldMaskSchema, {- paths: ["value.workspace_profile.database_change_mode"],- }),- });- onCancel(getHomePageByMode(state.mode));- } finally {- state.loading = false;- }-};--onMounted(async () => {- if (!actuatorV1Store.enableOnboarding) {- const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");- return onCancel(getHomePageByMode(databaseChangeMode.value));- }-});-</script>diff --git a/frontend/src/views/Setup/Setup.vue b/frontend/src/views/Setup/Setup.vuedeleted file mode 100644index 232b3b54f7..0000000000--- a/frontend/src/views/Setup/Setup.vue+++ /dev/null@@ -1,31 +0,0 @@-<template>- <RoutePermissionGuard :routes="setupRoutes">- <AdminSetup v-if="ready" />- <MaskSpinner v-else class="bg-white!" />- <AuthFooter />- </RoutePermissionGuard>-</template>--<script lang="ts" setup>-import { onMounted, ref } from "vue";-import { useRouter } from "vue-router";-import MaskSpinner from "@/components/misc/MaskSpinner.vue";-import RoutePermissionGuard from "@/components/Permission/RoutePermissionGuard.vue";-import setupRoutes from "@/router/setup";-import { useRoleStore, useWorkspaceV1Store } from "@/store";-import AuthFooter from "@/views/auth/AuthFooter.vue";-import AdminSetup from "./AdminSetup.vue";--const router = useRouter();-const ready = ref<boolean>(false);--onMounted(async () => {- await router.isReady();- // Prepare roles and workspace IAM policy.- await Promise.all([- useRoleStore().fetchRoleList(),- useWorkspaceV1Store().fetchIamPolicy(),- ]);- ready.value = true;-});-</script>diff --git a/frontend/src/views/Setup/WorkspaceMode.vue b/frontend/src/views/Setup/WorkspaceMode.vuedeleted file mode 100644index 77d8aa3a60..0000000000--- a/frontend/src/views/Setup/WorkspaceMode.vue+++ /dev/null@@ -1,75 +0,0 @@-<template>- <div>- <div class="mb-4 font-medium">- {{ $t("settings.general.workspace.default-landing-page.self") }}- </div>- <div class="w-full flex flex-col gap-8">- <PermissionGuardWrapper- v-slot="slotProps"- :permissions="[- 'bb.settings.setWorkspaceProfile'- ]"- >- <NRadioGroup- :disabled="slotProps.disabled"- :value="mode"- :size="'large'"- @update:value="$emit('update:mode', $event)"- >- <NSpace vertical size="large">- <NRadio :value="DatabaseChangeMode.PIPELINE">- <div class="flex flex-col gap-1">- <div class="textinfo">- {{- $t(- "settings.general.workspace.default-landing-page.workspace.self"- )- }}- </div>- <div class="textinfolabel">- {{- $t(- "settings.general.workspace.default-landing-page.workspace.description"- )- }}- </div>- </div>- </NRadio>- <NRadio :value="DatabaseChangeMode.EDITOR">- <div class="flex flex-col gap-1">- <div class="textinfo">- {{- $t(- "settings.general.workspace.default-landing-page.sql-editor.self"- )- }}- </div>- <div class="textinfolabel">- {{- $t(- "settings.general.workspace.default-landing-page.sql-editor.description"- )- }}- </div>- </div>- </NRadio>- </NSpace>- </NRadioGroup>- </PermissionGuardWrapper>- </div>- </div>-</template>--<script lang="ts" setup>-import { NRadio, NRadioGroup, NSpace } from "naive-ui";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";--defineProps<{- mode: DatabaseChangeMode;-}>();--defineEmits<{- (event: "update:mode", mode: DatabaseChangeMode): void;-}>();-</script>diff --git a/frontend/src/views/TwoFactorRequired.vue b/frontend/src/views/TwoFactorRequired.vuedeleted file mode 100644index f9359680f5..0000000000--- a/frontend/src/views/TwoFactorRequired.vue+++ /dev/null@@ -1,34 +0,0 @@-<template>- <div class="w-full">- <BBAttention type="warning">- {{ $t("two-factor.messages.2fa-required") }}- </BBAttention>- <div class="w-full p-2 sm:p-8 sm:px-16">- <div ref="container" />- </div>- </div>-</template>--<script lang="ts" setup>-import { onMounted, onUnmounted, ref } from "vue";-import { BBAttention } from "@/bbkit";-import { useAuthStore } from "@/store";--const authStore = useAuthStore();-const container = ref<HTMLElement>();-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any--onMounted(async () => {- if (!container.value) return;- const { mountReactPage } = await import("@/react/mount");- root = await mountReactPage(container.value, "TwoFactorSetupPage", {- cancelAction: () => authStore.logout(),- });-});--onUnmounted(() => {- root?.unmount();- root = null;-});-</script>diff --git a/frontend/src/views/auth/AuthFooter.vue b/frontend/src/views/auth/AuthFooter.vuedeleted file mode 100644index 3f5356c55e..0000000000--- a/frontend/src/views/auth/AuthFooter.vue+++ /dev/null@@ -1,66 +0,0 @@-<template>- <div class="absolute left-0 bottom-0 mb-8 text-center w-full">- <p class="block text-sm text-gray-400 flex justify-center gap-x-2">- <a- v-for="item in languageList"- :key="item.label"- href="#"- class="hover:text-gray-600"- :class="{ 'text-gray-800': item.label === selectedLanguage }"- @click.prevent="changeLanguage(item)"- >- {{ item.label }}- </a>- </p>- <p class="text-sm text-gray-400 mt-1">- © {{ year }} Bytebase. All rights reserved.- </p>- </div>-</template>--<script lang="ts" setup>-import { ref } from "vue";-import { useLanguage } from "../../composables/useLanguage";--const { locale, setLocale } = useLanguage();--const languageList = [- {- label: "English",- value: "en-US",- },- {- label: "简体中文",- value: "zh-CN",- },- {- label: "Español",- value: "es-ES",- },- {- label: "日本語",- value: "ja-JP",- },- {- label: "Tiếng việt",- value: "vi-VN",- },-];-const localeLabel =- locale.value === "zh-CN" || locale.value === "zh"- ? "简体中文"- : locale.value === "es-ES" || locale.value === "es"- ? "Español"- : locale.value === "ja-JP" || locale.value === "ja"- ? "日本語"- : locale.value === "vi-VN" || locale.value === "vi"- ? "Tiếng việt"- : "English";-const selectedLanguage = ref(localeLabel);-const year = new Date().getFullYear();--const changeLanguage = (item: { label: string; value: string }) => {- setLocale(item.value);- selectedLanguage.value = item.label;-};-</script>diff --git a/frontend/src/views/auth/InactiveRemindModal.vue b/frontend/src/views/auth/InactiveRemindModal.vuedeleted file mode 100644index aa34cabd27..0000000000--- a/frontend/src/views/auth/InactiveRemindModal.vue+++ /dev/null@@ -1,104 +0,0 @@-<template>- <BBModal- :show="shouldShow"- :trap-focus="true"- :show-close="false"- :mask-closable="false"- :header-class="'hidden!'"- >- <div class="flex items-center w-auto md:min-w-96 max-w-full h-auto md:py-4">- <div class="flex flex-col justify-center items-start flex-1 gap-y-4">- <div>- <p class="font-medium text-lg">- {{ $t("auth.inactive-modal.title") }}- </p>- <span class="textinfo">- {{- $t("auth.inactive-modal.description", {- minutes: showModalThresholdInMins,- })- }}- </span>- </div>- <div class="w-full flex items-center justify-end gap-x-2">- <NButton quaternary @click="logout">- {{ $t("common.logout") }}- </NButton>- <NButton type="primary" @click="staySignedIn">- {{ $t("auth.inactive-modal.stay-signed-in") }}- </NButton>- </div>- </div>- </div>- </BBModal>-</template>--<script lang="tsx" setup>-import { NButton } from "naive-ui";-import { computed, onUnmounted, ref, watch } from "vue";-import { BBModal } from "@/bbkit";-import { useCurrentTimestamp } from "@/composables/useCurrentTimestamp";-import { useLastActivity } from "@/composables/useLastActivity";-import { useAuthStore, useSettingV1Store } from "@/store";--const authStore = useAuthStore();-const settingV1Store = useSettingV1Store();-const timer = ref<NodeJS.Timeout | undefined>();--// Show the modal 3min before the inactiveTimeout threshold.-const showModalThresholdInMins = 3;--const logout = () => {- authStore.logout();-};--const inactiveTimeoutInSeconds = computed(() =>- Number(settingV1Store.workspaceProfile.inactiveSessionTimeout?.seconds ?? 0)-);--const { lastActivityTs } = useLastActivity();--const staySignedIn = () => (lastActivityTs.value = Date.now());--const { currentTsInMS } = useCurrentTimestamp();--const shouldShow = computed(() => {- if (inactiveTimeoutInSeconds.value <= 0) {- return false;- }-- const inactiveInSeconds = (currentTsInMS.value - lastActivityTs.value) / 1000;- // Show the modal 3min before the inactiveTimeout threshold.- return (- inactiveInSeconds >- inactiveTimeoutInSeconds.value - showModalThresholdInMins * 60- );-});--const resetTimeout = () => {- if (timer.value) {- clearTimeout(timer.value);- timer.value = undefined;- }-};--watch(- () => shouldShow.value,- (show) => {- resetTimeout();-- if (show) {- timer.value = setTimeout(- () => {- logout();- },- showModalThresholdInMins * 60 * 1000- );- }- }-);--onUnmounted(() => {- resetTimeout();-});-</script>diff --git a/frontend/src/views/auth/MultiFactor.vue b/frontend/src/views/auth/MultiFactor.vuedeleted file mode 100644index 23a5e896b6..0000000000--- a/frontend/src/views/auth/MultiFactor.vue+++ /dev/null@@ -1,129 +0,0 @@-<template>- <div- class="mx-auto max-w-2xl h-full py-6 flex flex-col justify-center items-center"- >- <NCard class="w-80 p-8 py-6 shadow-sm">- <img- class="h-12 w-auto mx-auto mb-8"- src="@/assets/logo-full.svg"- alt="Bytebase"- />- <form- class="w-full mt-4 h-auto flex flex-col justify-start items-center"- @submit.prevent="challenge"- >- <template v-if="state.selectedMFAType === 'OTP'">- <SmartphoneIcon- class="w-8 h-auto opacity-60"- />- <p class="my-2 mb-4">{{ $t("multi-factor.auth-code") }}</p>- <NInputOtp- v-model:value="state.otpCodes"- @finish="onOtpCodeFinish"- />- </template>- <template v-else-if="state.selectedMFAType === 'RECOVERY_CODE'">- <heroicons-outline:key class="w-8 h-auto opacity-60" />- <p class="my-2 mb-4">{{ $t("multi-factor.recovery-code") }}</p>- <BBTextField- v-model:value="state.recoveryCode"- placeholder="XXXXXXXXXX"- class="w-full"- />- </template>- <div class="w-full mt-4">- <NButton class="w-full!" attr-type="submit" type="primary">- {{ $t("common.verify") }}- </NButton>- </div>- <p class="textinfolabel mt-2">- {{ challengeDescription }}- </p>- </form>- <hr class="my-3" />- <div class="text-sm mb-2">- <p class="">{{ $t("multi-factor.other-methods.self") }}:</p>- <ul class="list-disc list-inside pl-2 pt-1">- <li v-if="state.selectedMFAType !== 'OTP'">- <button class="accent-link" @click="state.selectedMFAType = 'OTP'">- {{ $t("multi-factor.other-methods.use-auth-app.self") }}- </button>- </li>- <li v-if="state.selectedMFAType !== 'RECOVERY_CODE'">- <button- class="accent-link"- @click="state.selectedMFAType = 'RECOVERY_CODE'"- >- {{ $t("multi-factor.other-methods.use-recovery-code.self") }}- </button>- </li>- </ul>- </div>- </NCard>- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { SmartphoneIcon } from "lucide-vue-next";-import { NButton, NCard, NInputOtp } from "naive-ui";-import { computed, reactive } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute } from "vue-router";-import { BBTextField } from "@/bbkit";-import { useAuthStore } from "@/store";-import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";-import { resolveWorkspaceName } from "@/utils";--type MFAType = "OTP" | "RECOVERY_CODE";--interface LocalState {- selectedMFAType: MFAType;- otpCodes: string[];- recoveryCode: string;-}--const { t } = useI18n();-const route = useRoute();-const authStore = useAuthStore();-const state = reactive<LocalState>({- selectedMFAType: "OTP",- otpCodes: [],- recoveryCode: "",-});--const mfaTempToken = computed(() => {- return route.query.mfaTempToken as string;-});--const challengeDescription = computed(() => {- if (state.selectedMFAType === "OTP") {- return t("multi-factor.other-methods.use-auth-app.description");- } else if (state.selectedMFAType === "RECOVERY_CODE") {- return t("multi-factor.other-methods.use-recovery-code.description");- } else {- return "";- }-});--const onOtpCodeFinish = async (value: string[]) => {- state.otpCodes = value;- await challenge();-};--const challenge = async () => {- const request = create(LoginRequestSchema, {- mfaTempToken: mfaTempToken.value,- workspace: resolveWorkspaceName(),- });- if (state.selectedMFAType === "OTP") {- request.otpCode = state.otpCodes.join("");- } else if (state.selectedMFAType === "RECOVERY_CODE") {- request.recoveryCode = state.recoveryCode;- }- await authStore.login({- request,- redirect: true,- });-};-</script>diff --git a/frontend/src/views/auth/PasswordForgot.vue b/frontend/src/views/auth/PasswordForgot.vuedeleted file mode 100644index 92aa6e24a2..0000000000--- a/frontend/src/views/auth/PasswordForgot.vue+++ /dev/null@@ -1,120 +0,0 @@-<template>- <div class="mx-auto w-full max-w-sm">- <div>- <img class="h-12 w-auto" src="@/assets/logo-full.svg" alt="Bytebase" />- <h2 class="mt-6 text-3xl leading-9 font-extrabold text-main">- {{ $t("auth.password-forget.title") }}- </h2>- </div>-- <div class="mt-8">- <div class="mt-6 flex flex-col gap-y-4">- <BBAttention- v-if="!passwordResetEnabled"- type="warning"- :title="$t('auth.password-forget.selfhost')"- />- <template v-else>- <div>- <label- for="forgot-email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("common.email") }}- </label>- <div class="mt-1">- <BBTextField- v-model:value="email"- required- :input-props="{- id: 'forgot-email',- autocomplete: 'email',- type: 'email',- }"- placeholder="[email protected]"- @keyup.enter="onSubmit"- />- </div>- </div>- <NButton- type="primary"- size="large"- style="width: 100%"- :disabled="!isValidEmail(email) || isLoading"- :loading="isLoading"- @click="onSubmit"- >- {{ $t("auth.password-forget.send-reset-code") }}- </NButton>- </template>- </div>- </div>-- <div class="mt-6 relative">- <div class="absolute inset-0 flex items-center" aria-hidden="true">- <div class="w-full border-t border-control-border"></div>- </div>- <div class="relative flex justify-center text-sm">- <router-link- :to="{ name: AUTH_SIGNIN_MODULE, query: $route.query }"- class="accent-link bg-white px-2"- >- {{ $t("auth.password-forget.return-to-sign-in") }}- </router-link>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import { computed, onMounted, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute, useRouter } from "vue-router";-import { BBAttention, BBTextField } from "@/bbkit";-import { authServiceClientConnect } from "@/connect";-import { AUTH_PASSWORD_RESET_MODULE, AUTH_SIGNIN_MODULE } from "@/router/auth";-import { pushNotification, useActuatorV1Store } from "@/store";-import { isValidEmail, resolveWorkspaceName } from "@/utils";--const actuatorStore = useActuatorV1Store();-const router = useRouter();-const route = useRoute();-const { t } = useI18n();--const passwordResetEnabled = computed(- () => actuatorStore.serverInfo?.restriction?.passwordResetEnabled ?? false-);--onMounted(() => {- if (actuatorStore.serverInfo?.restriction?.disallowPasswordSignin) {- router.replace({ name: AUTH_SIGNIN_MODULE, query: route.query });- }-});--const email = ref("");-const isLoading = ref(false);--const onSubmit = async () => {- if (!isValidEmail(email.value) || isLoading.value) return;- isLoading.value = true;- try {- await authServiceClientConnect.requestPasswordReset({- email: email.value,- workspace: resolveWorkspaceName(),- });- router.push({- name: AUTH_PASSWORD_RESET_MODULE,- query: { ...route.query, email: email.value },- });- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("auth.password-forget.failed-to-send-code"),- });- } finally {- isLoading.value = false;- }-};-</script>diff --git a/frontend/src/views/auth/PasswordReset.vue b/frontend/src/views/auth/PasswordReset.vuedeleted file mode 100644index 46b6b2a26c..0000000000--- a/frontend/src/views/auth/PasswordReset.vue+++ /dev/null@@ -1,270 +0,0 @@-<template>- <div class="mx-auto w-full max-w-sm">- <img class="h-12 w-auto" src="@/assets/logo-full.svg" alt="Bytebase" />- <h2 class="mt-6 text-3xl leading-9 font-extrabold text-main">- {{ $t("auth.password-reset.title") }}- </h2>- <p class="textinfo mt-2">- {{ $t("auth.password-reset.content") }}- </p>-- <div class="mt-8 flex flex-col gap-y-6">- <!-- Code-based mode: email + code fields -->- <template v-if="codeMode">- <div>- <label class="block text-sm font-medium leading-5 text-control">- {{ $t("common.email") }}- <RequiredStar />- </label>- <BBTextField- v-model:value="state.email"- required- :input-props="{- autocomplete: 'email',- type: 'email',- }"- class="mt-1"- disabled- />- </div>- <div>- <label class="block text-sm font-medium leading-5 text-control">- {{ $t("auth.password-reset.code-label") }}- <RequiredStar />- </label>- <NInputOtp- v-model:value="state.codeParts"- :length="6"- class="mt-1 w-full email-code-otp"- />- <div class="mt-2 flex items-center justify-end">- <NButton- text- :disabled="resendCountdown > 0"- @click="resendCode"- >- {{- resendCountdown > 0- ? $t("auth.sign-in.resend-in", { seconds: resendCountdown })- : $t("auth.sign-in.resend-code")- }}- </NButton>- </div>- </div>- </template>-- <UserPassword- ref="userPasswordRef"- v-model:password="state.password"- v-model:password-confirm="state.passwordConfirm"- :show-learn-more="false"- :password-restriction="passwordRestrictionSetting"- />-- <NButton- type="primary"- size="large"- style="width: 100%"- :disabled="!allowConfirm"- @click="onConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>-- <div v-if="codeMode" class="mt-6 relative">- <div class="absolute inset-0 flex items-center" aria-hidden="true">- <div class="w-full border-t border-control-border"></div>- </div>- <div class="relative flex justify-center text-sm">- <router-link- :to="{ name: AUTH_SIGNIN_MODULE, query: $route.query }"- class="accent-link bg-white px-2"- >- {{ $t("auth.password-forget.return-to-sign-in") }}- </router-link>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { create, create as createProto } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { NButton, NInputOtp } from "naive-ui";-import { computed, onMounted, onUnmounted, reactive, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute, useRouter } from "vue-router";-import { BBTextField } from "@/bbkit";-import RequiredStar from "@/components/RequiredStar.vue";-import UserPassword from "@/components/User/Settings/UserPassword.vue";-import { authServiceClientConnect } from "@/connect";-import { AUTH_SIGNIN_MODULE } from "@/router/auth";-import {- pushNotification,- useActuatorV1Store,- useAuthStore,- useCurrentUserV1,- useUserStore,-} from "@/store";-import {- LoginRequestSchema,- ResetPasswordRequestSchema,-} from "@/types/proto-es/v1/auth_service_pb";-import type { User } from "@/types/proto-es/v1/user_service_pb";-import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";-import { resolveWorkspaceName } from "@/utils";--interface LocalState {- email: string;- codeParts: string[];- password: string;- passwordConfirm: string;-}--const { t } = useI18n();-const route = useRoute();-const router = useRouter();-const me = useCurrentUserV1();-const userStore = useUserStore();-const authStore = useAuthStore();-const userPasswordRef = ref<InstanceType<typeof UserPassword>>();--const state = reactive<LocalState>({- email: "",- codeParts: [],- password: "",- passwordConfirm: "",-});--const codeMode = computed(() => !!route.query.email);--// Resend cooldown — starts at 60s (code was just sent from PasswordForgot).-const resendCountdown = ref(60);-let countdownTimer: ReturnType<typeof setInterval> | null = null;--const startCountdown = () => {- resendCountdown.value = 60;- if (countdownTimer) clearInterval(countdownTimer);- countdownTimer = setInterval(() => {- resendCountdown.value -= 1;- if (resendCountdown.value <= 0 && countdownTimer) {- clearInterval(countdownTimer);- countdownTimer = null;- }- }, 1000);-};--const resendCode = async () => {- if (resendCountdown.value > 0 || !state.email) return;- try {- await authServiceClientConnect.requestPasswordReset({- email: state.email,- workspace: resolveWorkspaceName(),- });- startCountdown();- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("auth.password-forget.failed-to-send-code"),- });- }-};--onUnmounted(() => {- if (countdownTimer) clearInterval(countdownTimer);-});--const passwordRestrictionSetting = computed(- () => useActuatorV1Store().serverInfo?.restriction?.passwordRestriction-);--const redirectQuery = computed(() => {- const query = new URLSearchParams(window.location.search);- return query.get("redirect") || "/";-});--onMounted(() => {- if (codeMode.value) {- // If password signin is disabled, resetting a password is pointless.- if (useActuatorV1Store().serverInfo?.restriction?.disallowPasswordSignin) {- router.replace({ name: AUTH_SIGNIN_MODULE, query: route.query });- return;- }- state.email = route.query.email as string;- startCountdown();- return;- }- // Forced-reset mode: if user doesn't need to reset, redirect away.- if (!authStore.requireResetPassword) {- router.replace(redirectQuery.value);- }-});--const allowConfirm = computed(() => {- if (!state.password) return false;- if (codeMode.value && (!state.email || state.codeParts.join("").length !== 6))- return false;- return (- !userPasswordRef.value?.passwordHint &&- !userPasswordRef.value?.passwordMismatch- );-});--const onConfirm = async () => {- if (codeMode.value) {- try {- await authServiceClientConnect.resetPassword(- create(ResetPasswordRequestSchema, {- email: state.email,- code: state.codeParts.join(""),- newPassword: state.password,- })- );- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- // Auto-login with the new password so the user doesn't have to re-enter it.- await authStore.login({- request: create(LoginRequestSchema, {- email: state.email,- password: state.password,- workspace: resolveWorkspaceName(),- }),- });- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("auth.password-reset.invalid-or-expired-code"),- });- }- return;- }-- // Legacy forced-reset mode.- const patch: User = { ...me.value, password: state.password };- await userStore.updateUser(- createProto(UpdateUserRequestSchema, {- user: patch,- updateMask: createProto(FieldMaskSchema, { paths: ["password"] }),- })- );- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- authStore.setRequireResetPassword(false);- router.replace(redirectQuery.value);-};-</script>--<style scoped>-.email-code-otp :deep(.n-input) {- flex: 1;-}-</style>diff --git a/frontend/src/views/auth/Signin.vue b/frontend/src/views/auth/Signin.vuedeleted file mode 100644index 6d1df23770..0000000000--- a/frontend/src/views/auth/Signin.vue+++ /dev/null@@ -1,397 +0,0 @@-<template>- <template v-if="initialized">- <div class="mx-auto w-full max-w-sm">- <BytebaseLogo class="mx-auto mb-8" />-- <BBAttention- v-if="invitedEmail"- class="mb-4"- type="info"- :title="$t('auth.sign-in.invited-email', { email: invitedEmail })"- />-- <div v-if="showSignInForm">- <NCard>- <NTabs- class="card-tabs"- :default-value="defaultTabValue"- size="small"- animated- pane-style="padding: 12px 0 0 0"- >- <NTabPane- v-if="!serverInfo?.restriction?.disallowPasswordSignin"- name="standard"- tab="Standard"- >- <DemoSigninForm- v-if="isDemo"- :loading="state.isLoading"- @signin="trySignin"- />- <template v-else>- <PasswordSigninForm- :loading="state.isLoading"- @signin="trySignin"- />-- <div class="mt-3">- <div- class="flex justify-center items-center text-sm text-control"- >- <template v-if="!disallowSignup">- <span>- {{ $t("auth.sign-in.new-user") }}- </span>- <router-link- :to="{ name: AUTH_SIGNUP_MODULE, query: route.query }"- class="accent-link px-2"- >- {{ $t("common.sign-up") }}- </router-link>- </template>- </div>- </div>- </template>- </NTabPane>-- <NTabPane- v-if="serverInfo?.restriction?.allowEmailCodeSignin"- name="email-code"- :tab="$t('auth.sign-in.email-code-tab')"- >- <EmailCodeSigninForm- :loading="state.isLoading"- @signin="trySignin"- />- </NTabPane>-- <template- v-for="identityProvider in groupedIdentityProviderList"- :key="identityProvider.name"- >- <NTabPane- v-if="identityProvider.type === IdentityProviderType.LDAP"- :name="identityProvider.name"- :tab="identityProvider.title"- >- <form- class="flex flex-col gap-y-6"- @submit.prevent="trySigninWithIdp(identityProvider.name)"- >- <div>- <label- for="email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("common.username") }}- <RequiredStar />- </label>- <div class="mt-1 rounded-md shadow-xs">- <BBTextField- v-model:value="state.email"- required- placeholder="jim"- :input-props="{ id: 'username', autocomplete: 'on' }"- />- </div>- </div>-- <div>- <label- for="password"- class="flex justify-between text-sm font-medium leading-5 text-control"- >- <div>- {{ $t("common.password") }}- <RequiredStar />- </div>- </label>- <div- class="relative flex flex-row items-center mt-1 rounded-md shadow-xs"- >- <BBTextField- v-model:value="state.password"- :type="state.showPassword ? 'text' : 'password'"- :input-props="{ id: 'password', autocomplete: 'on' }"- required- />- <div- class="hover:cursor-pointer absolute right-3"- @click="- () => {- state.showPassword = !state.showPassword;- }- "- >- <EyeIcon v-if="state.showPassword" class="w-4 h-4" />- <EyeOffIcon v-else class="w-4 h-4" />- </div>- </div>- </div>-- <div class="w-full">- <NButton- attr-type="submit"- type="primary"- size="large"- :disabled="!allowIdPSignin"- :loading="state.isLoading"- style="width: 100%"- >- {{ $t("common.sign-in") }}- </NButton>- </div>- </form>- </NTabPane>- </template>- </NTabs>- </NCard>- </div>-- <div v-if="separatedIdentityProviderList.length > 0" class="mb-3 px-1">- <div v-if="showSignInForm" class="relative my-4">- <div class="absolute inset-0 flex items-center" aria-hidden="true">- <div class="w-full border-t border-control-border"></div>- </div>- <div class="relative flex justify-center text-sm">- <span class="px-2 bg-white text-control">{{- $t("common.or")- }}</span>- </div>- </div>- <template- v-for="identityProvider in separatedIdentityProviderList"- :key="identityProvider.name"- >- <div class="w-full mb-2">- <NButton- style="width: 100%"- size="large"- @click.prevent="trySigninWithIdentityProvider(identityProvider)"- >- {{- $t("auth.sign-in.sign-in-with-idp", {- idp: identityProvider.title,- })- }}- </NButton>- </div>- </template>- </div>- </div>- <slot name="footer">- <AuthFooter />- </slot>- </template>- <template v-else>- <div class="inset-0 absolute flex flex-row justify-center items-center">- <BBSpin />- </div>- </template>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import type { ConnectError } from "@connectrpc/connect";-import { EyeIcon, EyeOffIcon } from "lucide-vue-next";-import { NButton, NCard, NTabPane, NTabs } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, onMounted, reactive, ref, watchEffect } from "vue";-import { useRoute, useRouter } from "vue-router";-import { BBAttention, BBSpin, BBTextField } from "@/bbkit";-import BytebaseLogo from "@/components/BytebaseLogo.vue";-import DemoSigninForm from "@/components/DemoSigninForm.vue";-import EmailCodeSigninForm from "@/components/EmailCodeSigninForm.vue";-import PasswordSigninForm from "@/components/PasswordSigninForm.vue";-import RequiredStar from "@/components/RequiredStar.vue";-import { AUTH_SIGNUP_MODULE } from "@/router/auth";-import {- pushNotification,- useActuatorV1Store,- useAuthStore,- useIdentityProviderStore,-} from "@/store";-import { idpNamePrefix } from "@/store/modules/v1/common";-import {- type LoginRequest,- LoginRequestSchema,-} from "@/types/proto-es/v1/auth_service_pb";-import type { IdentityProvider } from "@/types/proto-es/v1/idp_service_pb";-import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";-import { openWindowForSSO, resolveWorkspaceName } from "@/utils";-import AuthFooter from "./AuthFooter.vue";--const props = withDefaults(- defineProps<{- redirect?: boolean;- redirectUrl?: string;- allowSignup?: boolean;- }>(),- {- redirect: true,- allowSignup: true,- }-);--interface LocalState {- email: string;- password: string;- showPassword: boolean;- isLoading: boolean;-}--const router = useRouter();-const route = useRoute();-const actuatorStore = useActuatorV1Store();-const authStore = useAuthStore();-const identityProviderStore = useIdentityProviderStore();--const state = reactive<LocalState>({- email: (route.query.email as string) || "",- password: "",- showPassword: false,- isLoading: false,-});-const initialized = ref(false);-const { isDemo } = storeToRefs(actuatorStore);-const { serverInfo, isSaaSMode } = storeToRefs(actuatorStore);--const invitedEmail = computed(- () => (route.query.email as string | undefined) || ""-);--const disallowSignup = computed(- () => !props.allowSignup || serverInfo.value?.restriction?.disallowSignup-);--const separatedIdentityProviderList = computed(() =>- identityProviderStore.identityProviderList.filter(- (idp) => idp.type !== IdentityProviderType.LDAP- )-);-const groupedIdentityProviderList = computed(() =>- identityProviderStore.identityProviderList.filter(- (idp) => idp.type === IdentityProviderType.LDAP- )-);--const showSignInForm = computed(() => {- return (- !serverInfo.value?.restriction?.disallowPasswordSignin ||- groupedIdentityProviderList.value.length > 0 ||- serverInfo.value?.restriction?.allowEmailCodeSignin- );-});--const defaultTabValue = computed(() => {- if (serverInfo.value?.restriction?.allowEmailCodeSignin) {- return "email-code";- }- if (!serverInfo.value?.restriction?.disallowPasswordSignin) {- return "standard";- }- if (groupedIdentityProviderList.value.length > 0) {- return groupedIdentityProviderList.value[0].name;- }- return "standard";-});--watchEffect(() => {- // Navigate to signup if needs admin setup.- // Unable to achieve it in router.beforeEach because actuator/info is fetched async and returns- // after router has already made the decision on first page load.- if (- actuatorStore.activeUserCount === 0 &&- !disallowSignup.value &&- !isSaaSMode.value- ) {- router.push({ name: AUTH_SIGNUP_MODULE, replace: true });- }-});--onMounted(async () => {- // If a workspace is specified in the query, fetch workspace-scoped actuator and IDPs.- const workspaceName = resolveWorkspaceName();-- try {- const [idpList, _] = await Promise.all([- identityProviderStore.fetchIdentityProviderList(workspaceName),- actuatorStore.fetchServerInfo(workspaceName),- ]);- if (idpList.length === 0 && workspaceName) {- // fallback to global IDPs- await identityProviderStore.fetchIdentityProviderList();- }- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `Request error occurred`,- description: (error as ConnectError).message,- });- }- // Check if there is an identity provider in the query string and try to sign in with it.- if (route.query["idp"]) {- const idpName = `${idpNamePrefix}${route.query["idp"] as string}`;- const identityProvider = identityProviderStore.identityProviderList.find(- (idp) => idp.name === idpName- );- if (identityProvider) {- await trySigninWithIdentityProvider(identityProvider);- // If we successfully signed in with the identity provider, return early.- return;- }- }- initialized.value = true;-});--const allowIdPSignin = computed(() => {- return state.email && state.password;-});--// Mainly for LDAP signin.-const trySigninWithIdp = (idpName: string) => {- trySignin(- create(LoginRequestSchema, {- email: state.email,- password: state.password,- idpName: idpName,- workspace: resolveWorkspaceName(),- })- );-};--const trySignin = async (request: LoginRequest) => {- if (state.isLoading) return;- state.isLoading = true;- try {- await authStore.login({- request,- redirect: props.redirect,- redirectUrl: props.redirectUrl,- });- } finally {- state.isLoading = false;- }-};--const trySigninWithIdentityProvider = async (- identityProvider: IdentityProvider-) => {- try {- await openWindowForSSO(- identityProvider,- false /* !popup */,- route.query.redirect as string- );- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `Request error occurred`,- description: (error as ConnectError).message,- });- }-};-</script>diff --git a/frontend/src/views/auth/SigninAdmin.vue b/frontend/src/views/auth/SigninAdmin.vuedeleted file mode 100644index 72fdaeb3ef..0000000000--- a/frontend/src/views/auth/SigninAdmin.vue+++ /dev/null@@ -1,45 +0,0 @@-<template>- <div class="mx-auto w-full max-w-sm">- <BytebaseLogo class="mx-auto" />-- <div class="mt-8">- <NCard>- <p class="text-xl pl-1 font-medium mb-4">- {{ $t("common.sign-in-as-admin") }}- </p>- <PasswordSigninForm- :show-forgot-password="false"- :loading="isLoading"- @signin="trySignin"- />- </NCard>- </div>- </div>- <AuthFooter />-</template>--<script lang="ts" setup>-import { NCard } from "naive-ui";-import { ref } from "vue";-import BytebaseLogo from "@/components/BytebaseLogo.vue";-import PasswordSigninForm from "@/components/PasswordSigninForm.vue";-import { useAuthStore } from "@/store";-import { type LoginRequest } from "@/types/proto-es/v1/auth_service_pb";-import AuthFooter from "./AuthFooter.vue";--const isLoading = ref(false);-const authStore = useAuthStore();--const trySignin = async (request: LoginRequest) => {- if (isLoading.value) return;- isLoading.value = true;- try {- await authStore.login({- request,- redirect: true,- });- } finally {- isLoading.value = false;- }-};-</script>\ No newline at end of filediff --git a/frontend/src/views/auth/SigninModal.vue b/frontend/src/views/auth/SigninModal.vuedeleted file mode 100644index 9f5040a524..0000000000--- a/frontend/src/views/auth/SigninModal.vue+++ /dev/null@@ -1,43 +0,0 @@-<template>- <BBModal- :show="true"- :trap-focus="true"- :show-close="false"- :mask-closable="false"- :header-class="'hidden!'"- >- <div class="flex items-center w-auto md:min-w-96 max-w-full h-auto md:py-4">- <div class="flex flex-col justify-center items-center flex-1 gap-y-2">- <Signin- :redirect="false"- :redirect-url="currentPath"- :allow-signup="false"- >- <template #footer>- <NButton quaternary size="small" @click="logout">- {{ $t("common.logout") }}- </NButton>- </template>- </Signin>- </div>- </div>- </BBModal>-</template>--<script lang="tsx" setup>-import { NButton } from "naive-ui";-import { computed } from "vue";-import { useRoute } from "vue-router";-import { BBModal } from "@/bbkit";-import { useAuthStore } from "@/store";-import Signin from "@/views/auth/Signin.vue";--const authStore = useAuthStore();-const route = useRoute();--const logout = () => {- authStore.logout();-};--const currentPath = computed(() => route.fullPath);-</script>diff --git a/frontend/src/views/auth/Signup.vue b/frontend/src/views/auth/Signup.vuedeleted file mode 100644index 3f2b2d7cb5..0000000000--- a/frontend/src/views/auth/Signup.vue+++ /dev/null@@ -1,251 +0,0 @@-<template>- <div class="mx-auto w-full max-w-sm">- <div>- <BytebaseLogo class="mx-auto mb-8" />-- <h2 class="text-2xl leading-9 font-medium text-main">- <template v-if="needAdminSetup">- <i18n-t- keypath="auth.sign-up.admin-title"- tag="p"- class="text-accent font-semnibold text-center"- >- <template #account>- <span class="text-accent font-semnibold">{{- $t("auth.sign-up.admin-account")- }}</span>- </template>- </i18n-t>- </template>- <template v-else> {{ $t("auth.sign-up.title") }}</template>- </h2>- </div>-- <div class="mt-8">- <div class="mt-6">- <form class="flex flex-col gap-y-6" @submit.prevent="trySignup">- <div>- <label- for="email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("common.email") }}- <RequiredStar />- </label>- <div class="mt-1 rounded-md shadow-xs">- <BBTextField- v-model:value="state.email"- required- placeholder="[email protected]"- :input-props="{ id: 'email' }"- @input="onTextEmail"- />- </div>- </div>-- <UserPassword- ref="userPasswordRef"- v-model:password="state.password"- v-model:password-confirm="state.passwordConfirm"- :show-learn-more="false"- :password-restriction="serverInfo?.restriction?.passwordRestriction"- />-- <div>- <label- for="email"- class="block text-sm font-medium leading-5 text-control"- >- {{ $t("common.username") }}- <RequiredStar />- </label>- <div class="mt-1 rounded-md shadow-xs">- <BBTextField- id="name"- v-model:value="state.name"- required- placeholder="Jim Gray"- @input="onTextName"- />- </div>- </div>-- <div- v-if="needAdminSetup"- class="w-full flex flex-row justify-start items-start"- >- <NCheckbox v-model:checked="state.acceptTermsAndPolicy">- <i18n-t- tag="span"- keypath="auth.sign-up.accept-terms-and-policy"- class="select-none"- >- <template #terms>- <a- href="https://www.bytebase.com/terms?source=console"- class="text-accent"- >{{ $t("auth.sign-up.terms-of-service") }}</a- >- </template>- <template #policy>- <a- href="https://www.bytebase.com/privacy?source=console"- class="text-accent"- >{{ $t("auth.sign-up.privacy-policy") }}</a- >- </template>- </i18n-t>- </NCheckbox>- </div>-- <div class="w-full">- <NButton- attr-type="submit"- type="primary"- size="large"- :disabled="!allowSignup"- :loading="state.isLoading"- style="width: 100%"- >- {{- needAdminSetup- ? $t("auth.sign-up.create-admin-account")- : $t("common.sign-up")- }}- </NButton>- </div>- </form>- </div>- </div>-- <div v-if="!needAdminSetup" class="mt-6 relative">- <div class="absolute inset-0 flex items-center" aria-hidden="true">- <div class="w-full border-t border-control-border"></div>- </div>- <div class="relative flex justify-center text-sm">- <span class="pl-2 bg-white text-control">- {{ $t("auth.sign-up.existing-user") }}- </span>- <router-link- :to="{ name: AUTH_SIGNIN_MODULE, query: $route.query }"- class="accent-link px-2 bg-white"- >- {{ $t("common.sign-in") }}- </router-link>- </div>- </div>- </div>-- <AuthFooter />-</template>--<script lang="ts" setup>-import { NButton, NCheckbox } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, onMounted, reactive, ref } from "vue";-import { useRoute, useRouter } from "vue-router";-import { BBTextField } from "@/bbkit";-import BytebaseLogo from "@/components/BytebaseLogo.vue";-import RequiredStar from "@/components/RequiredStar.vue";-import UserPassword from "@/components/User/Settings/UserPassword.vue";-import { AUTH_SIGNIN_MODULE } from "@/router/auth";-import { useActuatorV1Store, useAuthStore } from "@/store";-import type { User } from "@/types/proto-es/v1/user_service_pb";-import { isValidEmail } from "@/utils";-import AuthFooter from "./AuthFooter.vue";--interface LocalState {- email: string;- password: string;- passwordConfirm: string;- name: string;- nameManuallyEdited: boolean;- acceptTermsAndPolicy: boolean;- isLoading: boolean;-}--const router = useRouter();-const route = useRoute();-const actuatorStore = useActuatorV1Store();-const userPasswordRef = ref<InstanceType<typeof UserPassword>>();--const state = reactive<LocalState>({- email: "",- password: "",- passwordConfirm: "",- name: "",- nameManuallyEdited: false,- acceptTermsAndPolicy: true,- isLoading: false,-});--const { activeUserCount, serverInfo } = storeToRefs(actuatorStore);--const needAdminSetup = computed(() => activeUserCount.value === 0);--const allowSignup = computed(() => {- return (- isValidEmail(state.email) &&- state.password &&- state.name &&- !userPasswordRef.value?.passwordHint &&- !userPasswordRef.value?.passwordMismatch &&- state.acceptTermsAndPolicy &&- !serverInfo.value?.restriction?.disallowSignup- );-});--onMounted(() => {- // Signup is closed — redirect to signin. Admin-setup (first user) is always allowed.- if (!needAdminSetup.value && serverInfo.value?.restriction?.disallowSignup) {- router.replace({ name: AUTH_SIGNIN_MODULE, query: route.query });- return;- }- if (needAdminSetup.value) {- state.acceptTermsAndPolicy = false;- }-});--const onTextEmail = () => {- const email = state.email.trim().toLowerCase();- state.email = email;- if (!state.nameManuallyEdited) {- const emailParts = email.split("@");- if (emailParts.length > 0) {- if (emailParts[0].length > 0) {- const name = emailParts[0].replace("_", ".");- const nameParts = name.split(".");- if (nameParts.length >= 2) {- state.name = [- nameParts[0].charAt(0).toUpperCase() + nameParts[0].slice(1),- nameParts[1].charAt(0).toUpperCase() + nameParts[1].slice(1),- ].join(" ");- } else {- state.name = name.charAt(0).toUpperCase() + name.slice(1);- }- }- }- }-};--const onTextName = () => {- const name = state.name.trim();- state.nameManuallyEdited = name.length > 0;-};--const trySignup = async () => {- if (state.isLoading) return;- state.isLoading = true;-- try {- const signupInfo: Partial<User> = {- email: state.email,- password: state.password,- name: state.name,- };- await useAuthStore().signup(signupInfo);- } finally {- state.isLoading = false;- }-};-</script>