@micha.bigler/ui-core-micha 4.12.0 → 4.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,114 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useEffect, useId, useRef, useState } from 'react';
3
+ import { useTranslation } from 'react-i18next';
4
+ import Alert from '@mui/material/Alert';
5
+ import Box from '@mui/material/Box';
6
+ import Button from '@mui/material/Button';
7
+ import ButtonBase from '@mui/material/ButtonBase';
8
+ import Paper from '@mui/material/Paper';
9
+ import Typography from '@mui/material/Typography';
10
+ import CheckIcon from '@mui/icons-material/Check';
11
+ // The step card: one column with the prototype's spacing. Its radius and border
12
+ // come from the theme's outlined Paper.
13
+ export const SETUP_WIZARD_CARD_SX = {
14
+ display: 'flex',
15
+ flexDirection: 'column',
16
+ gap: { xs: 2.5, sm: 3 },
17
+ px: { xs: 2, sm: 4 },
18
+ py: { xs: 2.5, sm: 4 },
19
+ };
20
+ /**
21
+ * Page/inline frame for a host-controlled setup flow (UCM-AUTH-14): one column of
22
+ * stable width with a labelled step list, the step title, an error region, the
23
+ * step content and one action row. Unlike the authenticated onboarding dialog
24
+ * (OnboardingWizard / WizardDialogShell) it decides nothing: the host owns the
25
+ * steps, which are completed or reachable, the current step, navigation, busy
26
+ * state, errors and every draft. The shell stores nothing and starts no work.
27
+ *
28
+ * Props:
29
+ * - `steps`: `[{ id, label }]` in order; `currentStepId`.
30
+ * - `completedStepIds`, `reachableStepIds`: a step can be selected when it is
31
+ * reachable or completed; `onSelectStep(id)`.
32
+ * - `title` (default: the current step's label), `description`.
33
+ * - `error`: text or node shown in an alert that receives focus.
34
+ * - `onBack`, `backLabel`; `primaryLabel` with either `onPrimary` (may return a
35
+ * promise; the primary action is ignored until it settles) or `primaryForm`
36
+ * (the id of a form in the content; the primary button submits it natively, and
37
+ * the content guards its own pending state).
38
+ * - `busy`: disables navigation and actions.
39
+ * Focus moves to the title when the step changes and to the error when it appears.
40
+ */
41
+ export function SetupWizardShell({ steps = [], currentStepId, completedStepIds = [], reachableStepIds = [], onSelectStep, title, description, error, onBack, backLabel, onPrimary, primaryForm, primaryLabel, busy = false, children, }) {
42
+ const { t } = useTranslation();
43
+ const titleId = useId();
44
+ const titleRef = useRef(null);
45
+ const errorRef = useRef(null);
46
+ const mountedRef = useRef(false);
47
+ const pendingRef = useRef(false);
48
+ const [pending, setPending] = useState(false);
49
+ const currentIndex = Math.max(0, steps.findIndex((step) => step.id === currentStepId));
50
+ const currentStep = steps[currentIndex];
51
+ const total = steps.length;
52
+ const locked = busy || pending;
53
+ // Move focus to the new step's title, but not on the first render: a page that
54
+ // opens on the shell keeps the browser's normal initial focus.
55
+ useEffect(() => {
56
+ var _a;
57
+ if (!mountedRef.current) {
58
+ mountedRef.current = true;
59
+ return;
60
+ }
61
+ (_a = titleRef.current) === null || _a === void 0 ? void 0 : _a.focus();
62
+ }, [currentStepId]);
63
+ useEffect(() => {
64
+ var _a;
65
+ if (error)
66
+ (_a = errorRef.current) === null || _a === void 0 ? void 0 : _a.focus();
67
+ }, [error]);
68
+ const handlePrimary = async () => {
69
+ if (locked || pendingRef.current || !onPrimary)
70
+ return;
71
+ pendingRef.current = true;
72
+ setPending(true);
73
+ try {
74
+ await onPrimary();
75
+ }
76
+ catch (_a) {
77
+ // The host reports failures through `error`.
78
+ }
79
+ finally {
80
+ pendingRef.current = false;
81
+ setPending(false);
82
+ }
83
+ };
84
+ const hasPrimary = Boolean(primaryLabel) && Boolean(onPrimary || primaryForm);
85
+ return (_jsxs(Box, { component: "section", "aria-labelledby": titleId, sx: { width: '100%', maxWidth: 600, mx: 'auto', pt: { xs: 3, sm: 4 }, pb: 5 }, children: [_jsxs(Box, { component: "header", sx: { mb: 3.5 }, children: [_jsxs(Box, { sx: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 2 }, children: [_jsx(Typography, { component: "p", variant: "subtitle2", children: t('Onboarding.SETUP') }), _jsx(Typography, { component: "p", variant: "body2", color: "text.secondary", "aria-live": "polite", children: t('Onboarding.STEP_COUNTER', { current: currentIndex + 1, total }) })] }), _jsx(Box, { component: "nav", "aria-label": t('Onboarding.SETUP'), children: _jsx(Box, { component: "ol", sx: { display: 'flex', listStyle: 'none', gap: { xs: 0, sm: 0.5 }, m: 0, mt: 2.25, p: 0 }, children: steps.map((step, index) => {
86
+ const isCurrent = index === currentIndex;
87
+ const isComplete = completedStepIds.includes(step.id) && !isCurrent;
88
+ const selectable = !isCurrent
89
+ && (reachableStepIds.includes(step.id) || completedStepIds.includes(step.id));
90
+ return (_jsx(Box, { component: "li", sx: { flex: 1, minWidth: 0 }, children: _jsxs(ButtonBase, { type: "button", onClick: () => onSelectStep === null || onSelectStep === void 0 ? void 0 : onSelectStep(step.id), disabled: !selectable || locked || !onSelectStep, "aria-current": isCurrent ? 'step' : undefined, "aria-label": isComplete ? `${step.label}, ${t('Onboarding.COMPLETED')}` : undefined, sx: {
91
+ display: 'flex',
92
+ flexDirection: 'column',
93
+ alignItems: 'center',
94
+ gap: 1,
95
+ width: '100%',
96
+ py: 1,
97
+ borderRadius: 1,
98
+ color: isCurrent ? 'primary.main' : 'text.secondary',
99
+ '&.Mui-focusVisible': { outline: '2px solid', outlineColor: 'primary.main' },
100
+ }, children: [_jsx(Box, { component: "span", "aria-hidden": "true", sx: {
101
+ display: 'grid',
102
+ placeItems: 'center',
103
+ width: 28,
104
+ height: 28,
105
+ borderRadius: '50%',
106
+ border: 1,
107
+ borderColor: isCurrent || isComplete ? 'primary.main' : 'divider',
108
+ bgcolor: isCurrent ? 'primary.main' : 'transparent',
109
+ color: isCurrent ? 'primary.contrastText' : 'inherit',
110
+ typography: 'caption',
111
+ }, children: isComplete ? _jsx(CheckIcon, { sx: { fontSize: 16, color: 'primary.main' } }) : index + 1 }), _jsx(Typography, { component: "span", variant: "caption", sx: { fontWeight: isCurrent ? 600 : undefined, maxWidth: '100%', overflowWrap: 'anywhere' }, children: step.label })] }) }, step.id));
112
+ }) }) })] }), _jsxs(Paper, { variant: "outlined", sx: SETUP_WIZARD_CARD_SX, children: [_jsxs(Box, { sx: { display: 'flex', flexDirection: 'column', gap: 1 }, children: [_jsx(Typography, { ref: titleRef, id: titleId, component: "h1", variant: "h5", tabIndex: -1, sx: { outline: 'none' }, children: title !== null && title !== void 0 ? title : currentStep === null || currentStep === void 0 ? void 0 : currentStep.label }), description && (_jsx(Typography, { variant: "body2", color: "text.secondary", sx: { overflowWrap: 'anywhere' }, children: description }))] }), error && (_jsx(Alert, { ref: errorRef, severity: "error", tabIndex: -1, children: error })), children, (onBack || hasPrimary) && (_jsxs(Box, { sx: { display: 'flex', flexDirection: 'column-reverse', gap: 1, mt: 1 }, children: [onBack && (_jsx(Button, { type: "button", variant: "text", onClick: onBack, disabled: locked, fullWidth: true, children: backLabel || t('Onboarding.BACK') })), hasPrimary && (_jsx(Button, { type: primaryForm ? 'submit' : 'button', form: primaryForm || undefined, variant: "contained", onClick: primaryForm ? undefined : handlePrimary, disabled: locked, fullWidth: true, children: primaryLabel }))] }))] })] }));
113
+ }
114
+ export default SetupWizardShell;
@@ -1,252 +1,9 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import React, { useState, useContext, useEffect } from 'react';
3
- import { useNavigate, useLocation } from 'react-router-dom';
4
- import { Box, Alert } from '@mui/material';
5
- import { useTranslation } from 'react-i18next';
6
- // Layout & Context
7
- import { NarrowPage } from '../layout/PageLayout';
8
- import { AuthContext } from '../auth/AuthContext';
9
- // API & Services (Clean Architecture)
10
- import { fetchRecoverySessionToken, loginWithPassword, loginWithRecoveryPassword, } from '../auth/authApi';
11
- import { loginWithPasskey, startSocialLogin } from '../utils/authService';
12
- // Components
13
- import { LoginForm } from '../components/LoginForm';
14
- import { MfaLoginComponent } from '../components/MfaLoginComponent';
15
- import { resolveErrorText } from '../utils/resolveErrorText';
16
- export const LOGIN_PAGE_ALERT_SX = { mb: 2 };
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import React from 'react';
3
+ // The login controller lives in LoginFlow so LoginPage and the embeddable
4
+ // LoginContent share one implementation (UCM-AUTH-14).
5
+ import { LoginFlow, LOGIN_PAGE_ALERT_SX } from '../components/LoginContent';
6
+ export { LOGIN_PAGE_ALERT_SX };
17
7
  export function LoginPage() {
18
- const navigate = useNavigate();
19
- const location = useLocation();
20
- const { user, loading, login, authMethods } = useContext(AuthContext);
21
- const { t, i18n } = useTranslation();
22
- // State
23
- const [step, setStep] = useState('credentials'); // 'credentials' | 'mfa'
24
- const [submitting, setSubmitting] = useState(false);
25
- const [errorKey, setErrorKey] = useState(null);
26
- const [mfaState, setMfaState] = useState(null); // { availableTypes: [...], identifier }
27
- // S164: token never travels through the URL/fragment anymore. It is held
28
- // in component state only, fetched from the server-side session handoff
29
- // endpoint when the redirect lands the SPA here with `#recovery=ok`.
30
- const [recoveryToken, setRecoveryToken] = useState(null);
31
- const [recoveryFetching, setRecoveryFetching] = useState(false);
32
- // URL Params parsing
33
- const params = new URLSearchParams(location.search);
34
- const hashParams = new URLSearchParams(String(location.hash || "").startsWith("#") ? String(location.hash).slice(1) : String(location.hash || ""));
35
- // After S164 the hash carries only a status sentinel: `ok`, `invalid`, or
36
- // `expired`. We also accept the same key from query params as a defensive
37
- // fallback for proxies that strip fragments.
38
- const recoveryStatus = String(hashParams.get('recovery') || params.get('recovery') || '').toLowerCase();
39
- // Backward-compatible fallback for legacy links using query parameters.
40
- const recoveryEmail = hashParams.get('email') || params.get('email') || '';
41
- const requestedNext = params.get('next');
42
- const getRedirectTarget = (currentUser, options = {}) => {
43
- var _a;
44
- if (options.forceSecurityRedirect) {
45
- return options.forceSecurityRedirect;
46
- }
47
- const requiresExtra = ((_a = currentUser === null || currentUser === void 0 ? void 0 : currentUser.security_state) === null || _a === void 0 ? void 0 : _a.requires_additional_security) === true;
48
- if (requiresExtra) {
49
- return '/account?tab=security&from=weak_login';
50
- }
51
- // Same-origin check via URL parser — `startsWith('/')` alone allows
52
- // bypasses like `/\evil.com`, which WHATWG-parses to `https://evil.com/`
53
- // for special schemes. Resolve against the current origin and only accept
54
- // results whose origin matches.
55
- // Require leading-slash absolute path on the raw input (rejects relative
56
- // inputs like `account/settings` and protocol-relative `//host` before
57
- // they reach the URL parser, which would normalise both into a same-
58
- // origin pathname starting with `/`).
59
- if (requestedNext &&
60
- typeof requestedNext === 'string' &&
61
- requestedNext.startsWith('/') &&
62
- !requestedNext.startsWith('//')) {
63
- try {
64
- const parsed = new URL(requestedNext, window.location.origin);
65
- // Catches WHATWG bypasses like `/\evil.com` that resolve to a
66
- // different origin even though the raw input started with `/`.
67
- if (parsed.origin === window.location.origin) {
68
- return parsed.pathname + parsed.search + parsed.hash;
69
- }
70
- }
71
- catch (_b) {
72
- // fall through to default redirect
73
- }
74
- }
75
- return '/';
76
- };
77
- useEffect(() => {
78
- const socialError = params.get('error') || params.get('social');
79
- if (socialError) {
80
- setErrorKey(t('Auth.SOCIAL_LOGIN_FAILED'));
81
- }
82
- }, [location.search]);
83
- // S164 handoff: on `#recovery=ok`, pull the plaintext token out of the
84
- // server-side session (one-shot). On `invalid`/`expired`, or on any
85
- // other non-empty value (legacy pre-S164 email links that carried the
86
- // token directly in the hash), surface an invalid-link error so the
87
- // user gets feedback instead of a silent login screen.
88
- useEffect(() => {
89
- var _a;
90
- if (!recoveryStatus) {
91
- return;
92
- }
93
- // Strip the `recovery=…` sentinel from BOTH hash and query string so a
94
- // bookmark or page refresh does not re-trigger this effect against an
95
- // already-popped session entry (which would render a confusing
96
- // "invalid" error to a user who is mid-login).
97
- //
98
- // We use `history.replaceState` rather than `navigate(..., {replace})`
99
- // intentionally: react-router's `navigate` would trigger an immediate
100
- // re-render with an updated `useLocation()`, which would cause this
101
- // effect's cleanup to set `cancelled=true` and discard the in-flight
102
- // recovery-token fetch result. `replaceState` only mutates the browser
103
- // URL bar; `useLocation()` stays at `recovery=ok` for this render, the
104
- // fetch resolves, and `recoveryToken` gets set normally. The trade-off
105
- // is that `useLocation().hash` is stale for the page lifetime — fine
106
- // because nothing else in this component reads it.
107
- if (typeof window !== 'undefined' && ((_a = window.history) === null || _a === void 0 ? void 0 : _a.replaceState)) {
108
- const cleanParams = new URLSearchParams(window.location.search);
109
- cleanParams.delete('recovery');
110
- const cleanSearch = cleanParams.toString();
111
- const cleanUrl = window.location.pathname + (cleanSearch ? `?${cleanSearch}` : '');
112
- window.history.replaceState(null, '', cleanUrl);
113
- }
114
- if (recoveryStatus === 'expired') {
115
- setErrorKey(t('Auth.RECOVERY_TOKEN_EXPIRED'));
116
- setRecoveryToken(null);
117
- return;
118
- }
119
- if (recoveryStatus !== 'ok') {
120
- // Catches `invalid` and any unknown value (including legacy email
121
- // links that carried the plaintext token before S164).
122
- setErrorKey(t('Auth.RECOVERY_TOKEN_INVALID'));
123
- setRecoveryToken(null);
124
- return;
125
- }
126
- let cancelled = false;
127
- setRecoveryFetching(true);
128
- fetchRecoverySessionToken()
129
- .then((token) => {
130
- if (cancelled)
131
- return;
132
- if (!token) {
133
- // Session entry missing or already consumed — treat as invalid.
134
- setErrorKey(t('Auth.RECOVERY_TOKEN_INVALID'));
135
- setRecoveryToken(null);
136
- return;
137
- }
138
- setRecoveryToken(token);
139
- })
140
- .catch((err) => {
141
- if (cancelled)
142
- return;
143
- setErrorKey(resolveErrorText(i18n, err, 'Auth.RECOVERY_TOKEN_INVALID'));
144
- setRecoveryToken(null);
145
- })
146
- .finally(() => {
147
- if (!cancelled) {
148
- setRecoveryFetching(false);
149
- }
150
- });
151
- return () => {
152
- cancelled = true;
153
- };
154
- }, [recoveryStatus]);
155
- useEffect(() => {
156
- if (loading || !user)
157
- return;
158
- navigate(getRedirectTarget(user), { replace: true });
159
- }, [loading, user, navigate, requestedNext]);
160
- // --- Helper: Central Success Logic ---
161
- const handleLoginSuccess = (user) => {
162
- login(user); // Update Context
163
- navigate(getRedirectTarget(user));
164
- };
165
- // --- Handlers ---
166
- const handleSubmitCredentials = async ({ identifier, password }) => {
167
- setErrorKey(null);
168
- setSubmitting(true);
169
- try {
170
- // A) Recovery Flow
171
- if (recoveryToken) {
172
- const result = await loginWithRecoveryPassword(identifier, password, recoveryToken);
173
- login(result.user);
174
- navigate(getRedirectTarget(result.user, {
175
- forceSecurityRedirect: '/account?tab=security&from=recovery',
176
- }));
177
- return;
178
- }
179
- // B) Standard Password Login
180
- const result = await loginWithPassword(identifier, password);
181
- if (result.needsMfa) {
182
- setMfaState({
183
- availableTypes: result.availableTypes || [],
184
- identifier,
185
- });
186
- setStep('mfa');
187
- }
188
- else {
189
- handleLoginSuccess(result.user);
190
- }
191
- }
192
- catch (err) {
193
- setErrorKey(resolveErrorText(i18n, err, 'Auth.LOGIN_FAILED'));
194
- }
195
- finally {
196
- setSubmitting(false);
197
- }
198
- };
199
- const handlePasskeyLoginInitial = async () => {
200
- setErrorKey(null);
201
- setSubmitting(true);
202
- try {
203
- // Service handles browser interaction + API calls
204
- const user = await loginWithPasskey();
205
- handleLoginSuccess(user);
206
- }
207
- catch (err) {
208
- // 'Auth.PASSKEY_CANCELLED' is generic, maybe ignore visually or show specific hint
209
- if (err.code !== 'Auth.PASSKEY_CANCELLED') {
210
- setErrorKey(resolveErrorText(i18n, err, 'Auth.PASSKEY_FAILED'));
211
- }
212
- }
213
- finally {
214
- setSubmitting(false);
215
- }
216
- };
217
- const handleMfaSuccess = ({ user, method }) => {
218
- // MFA component should return the user object after verifying code
219
- if (method === 'recovery_code') {
220
- login(user);
221
- navigate(getRedirectTarget(user, {
222
- forceSecurityRedirect: '/account?tab=security&from=recovery',
223
- }));
224
- }
225
- else {
226
- handleLoginSuccess(user);
227
- }
228
- };
229
- const handleMfaCancel = () => {
230
- setStep('credentials');
231
- setMfaState(null);
232
- setErrorKey(null);
233
- };
234
- const socialProviders = Array.isArray(authMethods === null || authMethods === void 0 ? void 0 : authMethods.social_providers)
235
- ? authMethods.social_providers
236
- : [];
237
- const passwordLoginEnabled = Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.password_login) || Boolean(recoveryToken);
238
- const socialLoginEnabled = Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.social_login) && socialProviders.length > 0;
239
- const passkeyLoginEnabled = Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.passkey_login);
240
- const signupModes = Array.isArray(authMethods === null || authMethods === void 0 ? void 0 : authMethods.signup_modes)
241
- ? authMethods.signup_modes.filter(Boolean)
242
- : [];
243
- const signupEnabled = signupModes.length > 0 || Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.signup);
244
- const passwordResetEnabled = Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.password_reset);
245
- const twoFactorRequired = Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.two_factor_required)
246
- || Number((authMethods === null || authMethods === void 0 ? void 0 : authMethods.required_auth_factor_count) || 1) >= 2;
247
- // --- Render ---
248
- return (_jsxs(NarrowPage, { title: t('Auth.PAGE_LOGIN_TITLE'), subtitle: t('Auth.PAGE_LOGIN_SUBTITLE'), children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.PAGE_LOGIN_TITLE')}` }), errorKey && (_jsx(Alert, { severity: "error", sx: LOGIN_PAGE_ALERT_SX, children: errorKey })), recoveryFetching && !errorKey && (_jsx(Alert, { severity: "info", sx: LOGIN_PAGE_ALERT_SX, children: t('Auth.RECOVERY_LINK_VALIDATING', 'Validating recovery link…') })), recoveryToken && !errorKey && (_jsx(Alert, { severity: "info", sx: LOGIN_PAGE_ALERT_SX, children: t('Auth.RECOVERY_LOGIN_WARNING', 'Recovery link validated. Please enter your password.') })), twoFactorRequired && !recoveryToken && !recoveryFetching && (_jsx(Alert, { severity: "info", sx: LOGIN_PAGE_ALERT_SX, children: t('Auth.TWO_FACTOR_REQUIRED_HINT', 'This app requires two authentication factors for full access.') })), step === 'credentials' && (_jsx(LoginForm, { onSubmit: passwordLoginEnabled ? handleSubmitCredentials : null, onForgotPassword: passwordResetEnabled ? () => navigate('/reset-request-password') : null, onSocialLogin: socialLoginEnabled ? (provider) => startSocialLogin(provider) : null, socialProviders: socialProviders, onPasskeyLogin: passkeyLoginEnabled ? handlePasskeyLoginInitial : null, onSignUp: signupEnabled ? () => navigate('/signup') : null,
249
- // Block submit while the handoff is in flight so the user does not
250
- // race the recovery-token fetch with a normal password POST.
251
- disabled: submitting || recoveryFetching, initialIdentifier: recoveryEmail })), step === 'mfa' && mfaState && (_jsx(Box, { children: _jsx(MfaLoginComponent, { availableTypes: mfaState.availableTypes, identifier: mfaState.identifier, onSuccess: handleMfaSuccess, onCancel: handleMfaCancel }) }))] }));
8
+ return _jsx(LoginFlow, { pageMode: true });
252
9
  }
@@ -1,123 +1,39 @@
1
- import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import React, { useContext, useEffect, useMemo, useRef, useState, } from 'react';
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useContext, useMemo, useState } from 'react';
3
3
  import { useNavigate, useLocation } from 'react-router-dom';
4
- import { Alert, Box, Button, Stack, TextField, Typography, } from '@mui/material';
4
+ import { Box, Button, Typography } from '@mui/material';
5
5
  import { useTranslation } from 'react-i18next';
6
6
  import { NarrowPage } from '../layout/PageLayout';
7
7
  import { AuthContext } from '../auth/AuthContext';
8
- import { submitRegistrationRequest } from '../auth/authApi';
9
- import { TurnstileWidget } from '../components/TurnstileWidget';
10
- import { resolveErrorText } from '../utils/resolveErrorText';
11
- export const SIGN_UP_PAGE_ALERT_SX = { mb: 2 };
12
- const TURNSTILE_SIGNUP_MODES = new Set([
13
- 'self_signup_open',
14
- 'self_signup_email_domain',
15
- ]);
16
- const MODE_LABELS = {
17
- self_signup_access_code: 'Auth.SIGNUP_ACCESS_CODE_TAB',
18
- self_signup_open: 'Auth.SIGNUP_OPEN_TAB',
19
- self_signup_email_domain: 'Auth.SIGNUP_EMAIL_DOMAIN_TAB',
20
- self_signup_qr: 'Auth.SIGNUP_QR_TAB',
21
- };
8
+ import { SIGN_UP_PAGE_ALERT_SX, SignUpContent, resolveSignupModes, } from '../components/SignUpContent';
9
+ export { SIGN_UP_PAGE_ALERT_SX };
22
10
  const MODE_SUBTITLES = {
23
11
  self_signup_access_code: 'Auth.PAGE_SIGNUP_SUBTITLE_ACCESS_CODE',
24
12
  self_signup_open: 'Auth.PAGE_SIGNUP_SUBTITLE_OPEN',
25
13
  self_signup_email_domain: 'Auth.PAGE_SIGNUP_SUBTITLE_EMAIL_DOMAIN',
26
14
  self_signup_qr: 'Auth.PAGE_SIGNUP_SUBTITLE_QR',
27
15
  };
16
+ // The form and its sign-up logic live in SignUpContent (UCM-AUTH-14); the page
17
+ // keeps the route framing, the `?rt` QR token source and the login link.
28
18
  export function SignUpPage() {
29
19
  const navigate = useNavigate();
30
20
  const location = useLocation();
31
- const { t, i18n } = useTranslation();
21
+ const { t } = useTranslation();
32
22
  const { authMethods } = useContext(AuthContext);
33
- const signupModes = useMemo(() => {
34
- const configured = Array.isArray(authMethods === null || authMethods === void 0 ? void 0 : authMethods.signup_modes)
35
- ? authMethods.signup_modes.filter(Boolean)
36
- : [];
37
- if (configured.length > 0) {
38
- return configured;
39
- }
40
- return (authMethods === null || authMethods === void 0 ? void 0 : authMethods.signup) ? ['self_signup_access_code'] : [];
41
- }, [authMethods]);
23
+ const signupModes = useMemo(() => resolveSignupModes(authMethods), [authMethods]);
42
24
  const query = new URLSearchParams(location.search);
43
25
  const tokenFromUrl = query.get('rt') || '';
44
- const initialMode = useMemo(() => {
45
- if (tokenFromUrl && signupModes.includes('self_signup_qr')) {
46
- return 'self_signup_qr';
47
- }
48
- return signupModes[0] || 'self_signup_access_code';
49
- }, [signupModes, tokenFromUrl]);
50
- const [mode, setMode] = useState(initialMode);
51
- const [email, setEmail] = useState('');
52
- const [accessCode, setAccessCode] = useState('');
53
- const [submitting, setSubmitting] = useState(false);
54
- const [successKey, setSuccessKey] = useState(null);
55
- const [errorKey, setErrorKey] = useState(null);
56
- const [turnstileToken, setTurnstileToken] = useState('');
57
- const turnstileWidgetRef = useRef(null);
58
- const turnstileRequired = Boolean(authMethods === null || authMethods === void 0 ? void 0 : authMethods.turnstile_site_key)
59
- && TURNSTILE_SIGNUP_MODES.has(mode);
26
+ const [mode, setMode] = useState(() => (tokenFromUrl && signupModes.includes('self_signup_qr')
27
+ ? 'self_signup_qr'
28
+ : signupModes[0] || 'self_signup_access_code'));
60
29
  const pageSubtitle = useMemo(() => {
61
30
  if (mode === 'self_signup_qr' && tokenFromUrl) {
62
31
  return t('Auth.PAGE_SIGNUP_SUBTITLE_QR_READY', 'Enter your email address to complete sign-up with the QR link you opened.');
63
32
  }
64
33
  return t(MODE_SUBTITLES[mode] || 'Auth.PAGE_SIGNUP_SUBTITLE', 'Choose a sign-up method and enter the required details.');
65
34
  }, [mode, t, tokenFromUrl]);
66
- useEffect(() => {
67
- setMode(initialMode);
68
- }, [initialMode]);
69
- useEffect(() => {
70
- setTurnstileToken('');
71
- }, [mode, authMethods === null || authMethods === void 0 ? void 0 : authMethods.turnstile_site_key]);
72
- const handleSubmit = async (event) => {
73
- var _a;
74
- event.preventDefault();
75
- setSuccessKey(null);
76
- setErrorKey(null);
77
- if (!email) {
78
- setErrorKey(t('Auth.EMAIL_REQUIRED'));
79
- return;
80
- }
81
- if (mode === 'self_signup_access_code' && !accessCode) {
82
- setErrorKey(t('Auth.SIGNUP_ACCESS_CODE_REQUIRED'));
83
- return;
84
- }
85
- if (mode === 'self_signup_qr' && !tokenFromUrl) {
86
- setErrorKey(t('Auth.SIGNUP_QR_INVALID'));
87
- return;
88
- }
89
- if (turnstileRequired && !turnstileToken)
90
- return;
91
- setSubmitting(true);
92
- try {
93
- const res = await submitRegistrationRequest({
94
- email,
95
- mode,
96
- accessCode,
97
- registrationContextToken: mode === 'self_signup_qr' ? tokenFromUrl : null,
98
- turnstileToken: turnstileRequired ? turnstileToken : undefined,
99
- });
100
- // The backend's own response code is already mode-agnostic and accurate
101
- // (Auth.INVITE_SENT). Falling back to the access-code-specific "if valid,
102
- // an invite was sent" wording here was wrong for open/email-domain/QR
103
- // signup, which have no code whose validity needs hiding.
104
- setSuccessKey((res === null || res === void 0 ? void 0 : res.code) || 'Auth.INVITE_SENT');
105
- }
106
- catch (err) {
107
- setErrorKey(resolveErrorText(i18n, err, 'Auth.INVITE_FAILED'));
108
- if (turnstileRequired) {
109
- setTurnstileToken('');
110
- (_a = turnstileWidgetRef.current) === null || _a === void 0 ? void 0 : _a.reset();
111
- }
112
- }
113
- finally {
114
- setSubmitting(false);
115
- }
116
- };
117
35
  const handleGoToLogin = () => {
118
36
  navigate('/login');
119
37
  };
120
- return (_jsxs(NarrowPage, { title: t('Auth.LOGIN_SIGNUP_BUTTON'), subtitle: pageSubtitle, children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.LOGIN_SIGNUP_BUTTON')}` }), signupModes.length === 0 ? (_jsx(Alert, { severity: "info", sx: SIGN_UP_PAGE_ALERT_SX, children: t('Auth.SELF_SIGNUP_DISABLED', 'Self sign-up is currently disabled.') })) : (_jsxs(_Fragment, { children: [successKey && (_jsx(Alert, { severity: "success", sx: SIGN_UP_PAGE_ALERT_SX, children: t(successKey, { email }) })), errorKey && (_jsx(Alert, { severity: "error", sx: SIGN_UP_PAGE_ALERT_SX, children: errorKey })), signupModes.length > 1 && (_jsx(Stack, { spacing: 1, sx: { mb: 2 }, children: _jsx(Stack, { spacing: 1, children: signupModes.map((entry) => (_jsx(Button, { variant: mode === entry ? 'contained' : 'outlined', onClick: () => setMode(entry), disabled: submitting, fullWidth: true, children: t(MODE_LABELS[entry] || entry, entry) }, entry))) }) })), _jsxs(Box, { component: "form", onSubmit: handleSubmit, sx: { display: 'flex', flexDirection: 'column', gap: 2 }, children: [_jsx(TextField, { label: t('Auth.EMAIL_LABEL'), type: "email", required: true, fullWidth: true, value: email, onChange: (e) => setEmail(e.target.value), disabled: submitting }), mode === 'self_signup_access_code' && (_jsx(TextField, { label: t('Auth.ACCESS_CODE_LABEL'), type: "text", required: true, fullWidth: true, value: accessCode, onChange: (e) => setAccessCode(e.target.value), disabled: submitting })), turnstileRequired && (_jsx(TurnstileWidget, { ref: turnstileWidgetRef, siteKey: authMethods.turnstile_site_key, onToken: setTurnstileToken })), _jsx(Button, { type: "submit", variant: "contained", disabled: submitting || (turnstileRequired && !turnstileToken), children: submitting
121
- ? t('Auth.SIGNUP_SUBMITTING')
122
- : t('Auth.SIGNUP_SUBMIT') })] })] })), _jsx(Box, { sx: { mt: 3 }, children: _jsxs(Typography, { variant: "body2", children: [t('Auth.SIGNUP_ALREADY_HAVE_ACCOUNT'), ' ', _jsx(Button, { onClick: handleGoToLogin, variant: "text", size: "small", children: t('Auth.SIGNUP_GO_TO_LOGIN') })] }) })] }));
38
+ return (_jsxs(NarrowPage, { title: t('Auth.LOGIN_SIGNUP_BUTTON'), subtitle: pageSubtitle, children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.LOGIN_SIGNUP_BUTTON')}` }), _jsx(SignUpContent, { registrationContextToken: tokenFromUrl, onModeChange: setMode }), _jsx(Box, { sx: { mt: 3 }, children: _jsxs(Typography, { variant: "body2", children: [t('Auth.SIGNUP_ALREADY_HAVE_ACCOUNT'), ' ', _jsx(Button, { onClick: handleGoToLogin, variant: "text", size: "small", children: t('Auth.SIGNUP_GO_TO_LOGIN') })] }) })] }));
123
39
  }
@@ -1,64 +1,27 @@
1
- import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // src/pages/SignupConfirmPage.jsx
3
3
  //
4
4
  // S13: Completes a pending registration. Reads the signed pending-token from
5
- // the URL (`?token=...`), asks the user for a password, and POSTs to
6
- // `register_confirm`. On success, the user is sent to /login to sign in
7
- // explicitly — matches the existing invite/password-reset pattern and
8
- // preserves any MFA / login-event flow the app may enforce.
9
- import React, { useMemo, useState } from 'react';
5
+ // the URL (`?token=...`) and hands it to SignupConfirmContent, which asks for a
6
+ // password and POSTs to `register_confirm`. On success, the user is sent to
7
+ // /login to sign in explicitly — matches the existing invite/password-reset
8
+ // pattern and preserves any MFA / login-event flow the app may enforce.
9
+ import React, { useMemo } from 'react';
10
10
  import { useLocation, useNavigate } from 'react-router-dom';
11
- import { Alert, Box, Button, Stack, TextField, Typography, } from '@mui/material';
12
11
  import { useTranslation } from 'react-i18next';
13
12
  import { NarrowPage } from '../layout/PageLayout';
14
- import { confirmRegistration } from '../auth/authApi';
15
- import { resolveErrorText } from '../utils/resolveErrorText';
16
- export const SIGNUP_CONFIRM_PAGE_ALERT_SX = { mb: 2 };
13
+ import { SIGNUP_CONFIRM_PAGE_ALERT_SX, SignupConfirmContent, } from '../components/SignupConfirmContent';
14
+ export { SIGNUP_CONFIRM_PAGE_ALERT_SX };
17
15
  export function SignupConfirmPage() {
18
- const { t, i18n } = useTranslation();
16
+ const { t } = useTranslation();
19
17
  const location = useLocation();
20
18
  const navigate = useNavigate();
21
19
  const tokenFromUrl = useMemo(() => {
22
20
  const query = new URLSearchParams(location.search);
23
21
  return query.get('token') || '';
24
22
  }, [location.search]);
25
- const [password, setPassword] = useState('');
26
- const [confirmPassword, setConfirmPassword] = useState('');
27
- const [submitting, setSubmitting] = useState(false);
28
- const [errorKey, setErrorKey] = useState(null);
29
- const handleSubmit = async (event) => {
30
- event.preventDefault();
31
- setErrorKey(null);
32
- if (!tokenFromUrl) {
33
- setErrorKey(t('Auth.PENDING_TOKEN_INVALID'));
34
- return;
35
- }
36
- if (!password || password.length < 8) {
37
- setErrorKey(t('Auth.PASSWORD_TOO_SHORT'));
38
- return;
39
- }
40
- if (password !== confirmPassword) {
41
- setErrorKey(t('Auth.PASSWORD_MISMATCH'));
42
- return;
43
- }
44
- setSubmitting(true);
45
- try {
46
- await confirmRegistration({ token: tokenFromUrl, password });
47
- // Send the user to /login. Aligned with PasswordInvitePage; no implicit
48
- // session that would bypass MFA challenges or skip the explicit login
49
- // event in audit logs.
50
- navigate('/login', { replace: true });
51
- return;
52
- }
53
- catch (err) {
54
- setErrorKey(resolveErrorText(i18n, err, 'Auth.PENDING_TOKEN_INVALID'));
55
- }
56
- finally {
57
- setSubmitting(false);
58
- }
59
- };
60
- const tokenMissing = !tokenFromUrl;
61
- return (_jsxs(NarrowPage, { title: t('Auth.SIGNUP_CONFIRM_TITLE', 'Confirm your registration'), subtitle: t('Auth.SIGNUP_CONFIRM_SUBTITLE', 'Choose a password to finish creating your account.'), children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.SIGNUP_CONFIRM_TITLE', 'Confirm your registration')}` }), tokenMissing ? (_jsxs(_Fragment, { children: [_jsx(Alert, { severity: "error", sx: SIGNUP_CONFIRM_PAGE_ALERT_SX, children: t('Auth.PENDING_TOKEN_INVALID', 'This confirmation link is invalid or expired.') }), _jsxs(Stack, { direction: "row", spacing: 1, sx: { mt: 1 }, children: [_jsx(Button, { onClick: () => navigate('/signup'), variant: "contained", children: t('Auth.SIGNUP_REQUEST_NEW', 'Request a new invitation') }), _jsx(Button, { onClick: () => navigate('/login'), variant: "text", children: t('Auth.SIGNUP_GO_TO_LOGIN', 'Go to login') })] })] })) : (_jsxs(_Fragment, { children: [errorKey && (_jsx(Alert, { severity: "error", sx: SIGNUP_CONFIRM_PAGE_ALERT_SX, children: errorKey })), _jsxs(Box, { component: "form", onSubmit: handleSubmit, sx: { display: 'flex', flexDirection: 'column', gap: 2 }, children: [_jsx(TextField, { label: t('Auth.NEW_PASSWORD_LABEL', 'New password'), type: "password", required: true, fullWidth: true, value: password, onChange: (e) => setPassword(e.target.value), disabled: submitting, autoComplete: "new-password" }), _jsx(TextField, { label: t('Auth.PASSWORD_CONFIRM_LABEL', 'Confirm new password'), type: "password", required: true, fullWidth: true, value: confirmPassword, onChange: (e) => setConfirmPassword(e.target.value), disabled: submitting, autoComplete: "new-password" }), _jsx(Button, { type: "submit", variant: "contained", disabled: submitting, children: submitting
62
- ? t('Auth.SIGNUP_CONFIRM_SUBMITTING', 'Confirming…')
63
- : t('Auth.SIGNUP_CONFIRM_SUBMIT', 'Confirm registration') })] }), _jsxs(Stack, { direction: "row", spacing: 1, sx: { mt: 3 }, children: [_jsx(Typography, { variant: "body2", children: t('Auth.SIGNUP_ALREADY_HAVE_ACCOUNT', 'Already have an account?') }), _jsx(Button, { onClick: () => navigate('/login'), variant: "text", size: "small", children: t('Auth.SIGNUP_GO_TO_LOGIN', 'Go to login') })] })] }))] }));
23
+ return (_jsxs(NarrowPage, { title: t('Auth.SIGNUP_CONFIRM_TITLE', 'Confirm your registration'), subtitle: t('Auth.SIGNUP_CONFIRM_SUBTITLE', 'Choose a password to finish creating your account.'), children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.SIGNUP_CONFIRM_TITLE', 'Confirm your registration')}` }), _jsx(SignupConfirmContent, { token: tokenFromUrl,
24
+ // Aligned with PasswordInvitePage; no implicit session that would bypass
25
+ // MFA challenges or skip the explicit login event in audit logs.
26
+ onSuccess: () => navigate('/login', { replace: true }), onGoToSignup: () => navigate('/signup'), onGoToLogin: () => navigate('/login') })] }));
64
27
  }
@@ -31,6 +31,9 @@ import { ACCOUNT_PAGE_SECTION_PAPER_SX } from '../pages/AccountPage';
31
31
  import { LOGIN_PAGE_ALERT_SX } from '../pages/LoginPage';
32
32
  import { SIGN_UP_PAGE_ALERT_SX } from '../pages/SignUpPage';
33
33
  import { SIGNUP_CONFIRM_PAGE_ALERT_SX } from '../pages/SignupConfirmPage';
34
+ import { SIGN_UP_PROVIDER_ALERT_SX, SIGN_UP_PROVIDER_DIVIDER_SX } from '../components/SignUpContent';
35
+ import { PROFILE_STEP_CHECKBOX_SX, PROFILE_STEP_OPTION_SX } from '../components/ProfileStepContent';
36
+ import { SETUP_WIZARD_CARD_SX } from '../onboarding/SetupWizardShell';
34
37
  import { REAUTH_MODAL_ALERT_SX, REAUTH_MODAL_TEXT_FIELD_SX } from '../auth/ReauthModal';
35
38
  import { createKitSxEntry } from './kitSxEntry';
36
39
  import { ACCESS_ENDED_BANNER_ALERT_SX } from '../billing/AccessEndedBanner';
@@ -112,6 +115,11 @@ const SX_EXPORTS = {
112
115
  SOFT_CHIP_STATUS_SX,
113
116
  SIGNUP_CONFIRM_PAGE_ALERT_SX,
114
117
  SIGN_UP_PAGE_ALERT_SX,
118
+ SIGN_UP_PROVIDER_ALERT_SX,
119
+ SIGN_UP_PROVIDER_DIVIDER_SX,
120
+ PROFILE_STEP_CHECKBOX_SX,
121
+ PROFILE_STEP_OPTION_SX,
122
+ SETUP_WIZARD_CARD_SX,
115
123
  SUPPORT_RECOVERY_AGENT_BUTTON_SX,
116
124
  SUPPORT_RECOVERY_AGENT_PAPER_SX,
117
125
  SUPPORT_RECOVERY_ALERT_SX,
@@ -235,6 +243,11 @@ export const KIT_COMPONENT_SX_REGISTRY = [
235
243
  entry('LoginPage.alert', 'MuiAlert', LOGIN_PAGE_ALERT_SX),
236
244
  entry('SignUpPage.alert', 'MuiAlert', SIGN_UP_PAGE_ALERT_SX),
237
245
  entry('SignupConfirmPage.alert', 'MuiAlert', SIGNUP_CONFIRM_PAGE_ALERT_SX),
246
+ entry('SignUpContent.providerAlert', 'MuiAlert', SIGN_UP_PROVIDER_ALERT_SX),
247
+ entry('SignUpContent.providerDivider', 'MuiDivider', SIGN_UP_PROVIDER_DIVIDER_SX),
248
+ entry('ProfileStepContent.option', 'MuiFormControlLabel', PROFILE_STEP_OPTION_SX),
249
+ entry('ProfileStepContent.checkbox', 'MuiCheckbox', PROFILE_STEP_CHECKBOX_SX),
250
+ entry('SetupWizardShell.card', 'MuiPaper', SETUP_WIZARD_CARD_SX),
238
251
  entry('ReauthModal.alert', 'MuiAlert', REAUTH_MODAL_ALERT_SX),
239
252
  entry('ReauthModal.field', 'MuiTextField', REAUTH_MODAL_TEXT_FIELD_SX),
240
253
  entry('AccessEndedBanner.alert', 'MuiAlert', ACCESS_ENDED_BANNER_ALERT_SX),