@vvedantb/native-ui 0.10.0 → 0.11.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.
- package/README.md +13 -5
- package/package.json +5 -1
- package/src/PasswordInput.tsx +101 -0
- package/src/auth/SignInScreen.tsx +128 -21
- package/src/auth/authErrors.ts +90 -12
- package/src/auth/index.ts +11 -1
- package/src/auth/totp.ts +98 -0
- package/src/entries/password-input.ts +4 -0
- package/src/entries/primitives.ts +2 -0
- package/src/index.ts +2 -0
package/README.md
CHANGED
|
@@ -65,8 +65,9 @@ The root entry exports everything. It still imports `BottomSheetContainer` and `
|
|
|
65
65
|
| `@vvedantb/native-ui/tab-bar` | `FloatingTabBar`, `FloatingTabBarProps`, `FLOATING_INSET`, `FLOATING_TAB_BAR_HEIGHT`, `FLOATING_TAB_BAR_HEIGHT_LARGE`, `tabBarReserve` | `expo-blur`, `expo-haptics` (loaders) |
|
|
66
66
|
| `@vvedantb/native-ui/brand` | `AppMark`, `AppWordmark`, `GoogleMark` (from 0.3.15), `APP_ICONS`, `IconVibot` and the other `Icon*`, the SVG helpers (`APP_MARKS`, `appMarkSvg`, `appTileSvg` and the rest), `FAMILY_APPS`, `familyApp`, `V_PRO_APP_BENEFITS` | none |
|
|
67
67
|
| `@vvedantb/native-ui/button` | `Button`, `ButtonProps`, `ButtonShape` (0.6.0), `ButtonSize`, `ButtonVariant` | none |
|
|
68
|
-
| `@vvedantb/native-ui/primitives` | `Button`, `Input`, `SearchInput`, `Textarea`, `Label`, `Select`, `Switch`, `LabeledSwitchRow`, `Checkbox`, `Card` and its parts, `Badge`, `StatusDot`, `Avatar`, `Separator`, `Progress`, `Spinner`, `Skeleton`, `EmptyState`, `ListRow`, `Chip`, `HeaderIconButton`, `ThemeToggle` (from 0.3.16), `Tabs`, `PillTabs`, `Dialog`, `AlertDialog`, `ConfirmDialog`, `Sheet`, `toast`, `Toaster`. From 0.5.0: `Text` and `TextClassContext` (only here, not on the root), `ColorSwatches`, `StatGrid`, `SectionLabel`, `SheetRow`, `PageIndicator`, `IconButton`, `CaptureButton`, and the `ListRowProps` and `CardProps` types. From 0.6.0: the `ButtonShape` type. Unreleased: `DropdownMenu` and its parts, `BulkActionBar` | `expo-blur`, `expo-haptics` (loaders) |
|
|
68
|
+
| `@vvedantb/native-ui/primitives` | `Button`, `Input`, `SearchInput`, `PasswordInput` (0.11.0), `Textarea`, `Label`, `Select`, `Switch`, `LabeledSwitchRow`, `Checkbox`, `Card` and its parts, `Badge`, `StatusDot`, `Avatar`, `Separator`, `Progress`, `Spinner`, `Skeleton`, `EmptyState`, `ListRow`, `Chip`, `HeaderIconButton`, `ThemeToggle` (from 0.3.16), `Tabs`, `PillTabs`, `Dialog`, `AlertDialog`, `ConfirmDialog`, `Sheet`, `toast`, `Toaster`. From 0.5.0: `Text` and `TextClassContext` (only here, not on the root), `ColorSwatches`, `StatGrid`, `SectionLabel`, `SheetRow`, `PageIndicator`, `IconButton`, `CaptureButton`, and the `ListRowProps` and `CardProps` types. From 0.6.0: the `ButtonShape` type. Unreleased: `DropdownMenu` and its parts, `BulkActionBar` | `expo-blur`, `expo-haptics` (loaders) |
|
|
69
69
|
| `@vvedantb/native-ui/search-input` | `SearchInput`, `SearchInputProps` | none |
|
|
70
|
+
| `@vvedantb/native-ui/password-input` | `PasswordInput`, `PasswordInputProps` (from 0.11.0) | none |
|
|
70
71
|
| `@vvedantb/native-ui/page-title` | `PageTitle`, `PageHeader`, `PageTitleProps`, `PageHeaderProps` (from 0.3.13), `StackPageHeader`, `StackPageHeaderProps` (from 0.5.0; it brings the Tabler package for its chevron) | none |
|
|
71
72
|
| `@vvedantb/native-ui/toast` | `toast`, `Toaster`, `ToastOptions`, `ToastVariant` | none (from 0.3.12) |
|
|
72
73
|
| `@vvedantb/native-ui/theme` | `NativeUiProvider`, `useNativeUi`, `useLargerText`, `useAccentColor`, `DEFAULT_ACCENT`, `tokens`, `palette`, `withAlpha`, `configureTheme` (with the `ThemeConfig`, `ThemeColors` and `ThemePalette` types), `fontClass`, `cn`, `Colors` and the colour constants | none |
|
|
@@ -80,7 +81,7 @@ The root entry exports everything. It still imports `BottomSheetContainer` and `
|
|
|
80
81
|
| `@vvedantb/native-ui/date-time` | `DateTimeField`, `DateTimeFieldProps` (0.5.0) | `@react-native-community/datetimepicker`, `dayjs` (import) |
|
|
81
82
|
| `@vvedantb/native-ui/ai` | The AI chat parts (from 0.4.0): `Conversation`, `Message`, `Reasoning`, `AgentTrace`, `ChainOfThought`, `ActivityStep`, `PromptInput`, `Suggestions`, `Sources`, `FileChip`, `Attachments`, `CodeBlock`, `ResponseText`, `Shimmer`, `Collapsible`, `useStreamingDisclosure` and their parts. See [AI chat](#ai-chat-040). Not on the root entry. | none |
|
|
82
83
|
| `@vvedantb/native-ui/ai-gallery` | `AiChatGallery`, `AiChatSamples` (from 0.4.0) | none |
|
|
83
|
-
| `@vvedantb/native-ui/auth` | From 0.7.0: `AuthProviders`, `SignInScreen`, `SignUpScreen`, `GoogleSignInButton`, `useGoogleSignIn`, `AuthScreen`, `OrDivider`, `FieldError`, `authErrorMessage`, `SecondFactorScreen`, `useSecondFactor`, `submitTotpSecondFactor`, `submitSecondFactor`, `prepareSecondFactorIfNeeded`, `TOTP_MESSAGES` and their props types. See [Auth](#auth-070). Not on the root entry. | `@clerk/clerk-expo`, `convex`, `expo-auth-session`, `expo-web-browser`, `expo-router` (import) |
|
|
84
|
+
| `@vvedantb/native-ui/auth` | From 0.7.0: `AuthProviders`, `SignInScreen`, `SignUpScreen`, `GoogleSignInButton`, `useGoogleSignIn`, `AuthScreen`, `OrDivider`, `FieldError`, `authErrorMessage`, `SecondFactorScreen`, `useSecondFactor`, `submitTotpSecondFactor`, `submitSecondFactor`, `prepareSecondFactorIfNeeded`, `prepareFirstFactorIfNeeded`, `submitFirstFactor`, `pickFirstFactorStrategy`, `TOTP_MESSAGES` and their props types. See [Auth](#auth-070). Not on the root entry. | `@clerk/clerk-expo`, `convex`, `expo-auth-session`, `expo-web-browser`, `expo-router` (import) |
|
|
84
85
|
| `@vvedantb/native-ui/expo-web-root` | From 0.7.0: `ExpoWebRoot`, `ExpoWebRootProps`, `ExpoWebRootViewport`, `EXPO_WEB_VIEWPORT`, `expoWebBackgroundCss`. Not on the root entry. | `expo-router` (import of `expo-router/html`) |
|
|
85
86
|
| `@vvedantb/native-ui/tailwind-preset` | From 0.7.0, CommonJS for `tailwind.config.js`: `nativeUiPreset`, `nativeUiContent`, `cssVar`, `hslVar`, `rgbAlpha`, `cssVariables`, `schemeColors` and a default preset. See [Expo / NativeWind](#expo--nativewind). | `nativewind` (`require`, when installed) |
|
|
86
87
|
|
|
@@ -212,8 +213,9 @@ export default function SignUp() {
|
|
|
212
213
|
- `header` and `footer` slots for app chrome, such as a brand header or credit. The screen itself is neutral: background fill, title, subtitle, fields.
|
|
213
214
|
- Messages are generic ("Sign in failed", "Invalid email or password", "Could not continue with Google") and never name the auth provider. `authErrorMessage(error, fallback)` shows an API error's own text only when it does not name it.
|
|
214
215
|
- Two-step verification: when sign-in returns `needs_second_factor` or `needs_client_trust`, the screen shows `SecondFactorScreen` with the account's default method: authenticator app (`totp`), then `email_code`, `phone_code`, `backup_code`. Email and text codes are sent first. A "Use a backup code" link (and a link back) switches method. A valid code runs the same success path. Back returns to the email and password form.
|
|
216
|
+
- `needs_first_factor`: when the account has an `email_code` or `phone_code` first factor (with its `emailAddressId` or `phoneNumberId`), the screen sends the code (`prepareFirstFactor`), shows `SecondFactorScreen`, and checks it with `attemptFirstFactor`. The result then runs the usual path: session, new password, or second factor. Email is preferred; a link switches to phone, and back. Back returns to the email and password form.
|
|
215
217
|
- `needs_new_password` shows a new-password step (`signIn.resetPassword`), then starts the session.
|
|
216
|
-
- `onIncomplete(signIn)`: optional. Called only for statuses the built-in UI cannot finish: `needs_identifier`, `needs_first_factor
|
|
218
|
+
- `onIncomplete(signIn)`: optional. Called only for statuses the built-in UI cannot finish: `needs_identifier`, `needs_first_factor` without an `email_code` or `phone_code` first factor, unknown statuses, and `needs_second_factor` or `needs_client_trust` when no supported strategy (totp, backup code, phone code, email code) exists. The built-in screen always runs `needs_second_factor`, `needs_client_trust` and `needs_new_password`, and runs `needs_first_factor` when an email or phone code exists. When `onIncomplete` is called, the screen shows no message. Without it, those statuses show "This account needs another step to sign in. Finish it on the web." and log the status and strategy ids with `console.warn`. Ignored in `sign-up`.
|
|
217
219
|
- Keyboard: `AuthScreen` (and so every screen here) pads for the soft keyboard on iOS and Android, including edge-to-edge Android, and scrolls the focused field and the button above it.
|
|
218
220
|
- No forgot-password step. An app that needs one keeps its own screen.
|
|
219
221
|
|
|
@@ -309,7 +311,7 @@ Limits: a call after the first render does not redraw mounted components. Only t
|
|
|
309
311
|
|
|
310
312
|
| Area | Exports |
|
|
311
313
|
| --- | --- |
|
|
312
|
-
| Actions and fields | `Button` (`default`/`primary`, `secondary`, `outline`, `destructive`, `ghost`, `link`, `tinted`; `sm`/`small`, `default`/`medium`, `lg`/`large`, `icon`; `shape` `pill`/`rounded` from 0.6.0), `IconButton` (0.5.0), `CaptureButton` (0.5.0), `Input`, `SearchInput` (0.3.9), `Textarea`, `Label`, `Select`, `Switch`, `Checkbox`, `LabeledSwitchRow`, `ColorSwatches` (0.5.0), `DateTimeField` (date-only, empty and clearable from 0.5.0) |
|
|
314
|
+
| Actions and fields | `Button` (`default`/`primary`, `secondary`, `outline`, `destructive`, `ghost`, `link`, `tinted`; `sm`/`small`, `default`/`medium`, `lg`/`large`, `icon`; `shape` `pill`/`rounded` from 0.6.0), `IconButton` (0.5.0), `CaptureButton` (0.5.0), `Input`, `SearchInput` (0.3.9), `PasswordInput` (0.11.0), `Textarea`, `Label`, `Select`, `Switch`, `Checkbox`, `LabeledSwitchRow`, `ColorSwatches` (0.5.0), `DateTimeField` (date-only, empty and clearable from 0.5.0) |
|
|
313
315
|
| Display | `Card` (+ `CardHeader`, `CardTitle`, `CardDescription`, `CardContent`, `CardFooter`; `onPress` from 0.5.0), `Badge`, `StatusDot` (`info` from 0.5.0), `Avatar` (+ `AvatarImage`, `AvatarFallback`, `initials()`), `Separator`, `Progress`, `Spinner`, `CenteredSpinner`, `Skeleton`, `EmptyState` (+ `EmptyState.Root` and parts), `ListRow` (`leading`, `titleEnd`, `control`, `onLongPress` from 0.5.0), `StatGrid` (0.5.0), `SectionLabel` (0.5.0), `Chip`, `Text` (0.5.0, `/primitives` only) |
|
|
314
316
|
| Navigation | `Tabs` (+ `TabsList`, `TabsTrigger`, `TabsContent`), `PillTabs`, `PageIndicator` (0.5.0), `FloatingTabBar`, `FloatingFAB`, `HeaderIconButton`, `ThemeToggle` (0.3.16), `StackPageHeader` (0.5.0) |
|
|
315
317
|
| Overlays | `Dialog`, `AlertDialog`, `ConfirmDialog`, `Sheet` (RN `Modal`, each with the web part names), `SheetRow` (0.5.0), `BottomSheetContainer` (`@gorhom/bottom-sheet`), `DropdownMenu` (Unreleased; see below) |
|
|
@@ -360,6 +362,12 @@ const [query, setQuery] = useState("");
|
|
|
360
362
|
<SearchInput value={query} onChange={setQuery} label="Search apps" />
|
|
361
363
|
```
|
|
362
364
|
|
|
365
|
+
From 0.11.0 `PasswordInput` is `Input` with a show/hide eye button at the end (`IconEye` and `IconEyeOff`). The password is hidden at first. The button is labelled "Show password" or "Hide password" to match, has the test ID `${testID}-toggle` (`password-input-toggle` without a `testID`), is painted at 24 and reaches 44 with its hit slop. It flips `secureTextEntry` on the same mounted field, so focus and the cursor stay. The component owns `secureTextEntry`, so that prop is not accepted. Other `Input` props and `ref` pass through; the button is hidden when `editable={false}`. The `SignInScreen` password, new-password and confirm-password fields use it. Inside a `ScrollView`, set `keyboardShouldPersistTaps="handled"`.
|
|
366
|
+
|
|
367
|
+
```tsx
|
|
368
|
+
<PasswordInput value={password} onChangeText={setPassword} placeholder="Password" autoComplete="password" textContentType="password" />
|
|
369
|
+
```
|
|
370
|
+
|
|
363
371
|
From 0.3.13 `PageTitle` is the web page title, the type on the web `Breadcrumb` (`text-xl font-semibold leading-tight tracking-tight`): Instrument Sans 600 at 20 / 25 with -0.5 letter spacing (-0.025em), in the foreground colour. It sets the semibold face class and `fontWeight: "600"` together, so it is not drawn Regular on Android or Expo web. It is a header for VoiceOver and TalkBack, one line (pass `numberOfLines={0}` to wrap), and scales with the system font size. `PageHeader` is a tab-root title row: `PageTitle` at the start and an optional `action` at the end, which keeps its width while a long title is cut off. It has the `ScreenContainer` side padding (`px-4`) and a row at least 56 high, so tabs with and without an action put their titles at the same height. It pads the top by the safe-area inset; pass `safeTop={false}` under a native header or inside a view that already pads it. Give a `Button` in `action` `fullWidth={false}`.
|
|
364
372
|
|
|
365
373
|
```tsx
|
|
@@ -554,7 +562,7 @@ The bar is the glass `FloatingSurface` at radius 16 with `px-2.5 py-2`. It holds
|
|
|
554
562
|
|
|
555
563
|
## Phones and accessibility
|
|
556
564
|
|
|
557
|
-
The components keep the web sizes on screen and reach a 44 pt touch target with `hitSlop` (`touchSlop` in `src/controlStyles.ts`): `Checkbox` (16), `Switch` (36 × 20), tab triggers (30 high), the `Select` trigger (40 high), the `SearchInput` clear button (24), the `UpgradeToProCard` pill (32 high, slop 8) and `Button` (the slop brings each size to at least 48). From 0.5.0 so do `ColorSwatches` swatches and `IconButton` (32 and 40); the `DateTimeField` clear button and the pressable `PageIndicator` dots are 44 squares. Controls set their role and state for VoiceOver and TalkBack: `Button` (`disabled`, `busy` while loading), `Checkbox` (`checked`, `mixed`), `Switch` (`checked`), `Tabs` and `PillTabs` (`tablist`, `tab`, `selected`) and the `Select` trigger (`combobox`, with an `accessibilityLabel` prop). Give a `Button` with no text child an `accessibilityLabel`.
|
|
565
|
+
The components keep the web sizes on screen and reach a 44 pt touch target with `hitSlop` (`touchSlop` in `src/controlStyles.ts`): `Checkbox` (16), `Switch` (36 × 20), tab triggers (30 high), the `Select` trigger (40 high), the `SearchInput` clear button (24), the `PasswordInput` show/hide button (24), the `UpgradeToProCard` pill (32 high, slop 8) and `Button` (the slop brings each size to at least 48). From 0.5.0 so do `ColorSwatches` swatches and `IconButton` (32 and 40); the `DateTimeField` clear button and the pressable `PageIndicator` dots are 44 squares. Controls set their role and state for VoiceOver and TalkBack: `Button` (`disabled`, `busy` while loading), `Checkbox` (`checked`, `mixed`), `Switch` (`checked`), `Tabs` and `PillTabs` (`tablist`, `tab`, `selected`) and the `Select` trigger (`combobox`, with an `accessibilityLabel` prop). Give a `Button` with no text child an `accessibilityLabel`.
|
|
558
566
|
|
|
559
567
|
Text scales with the system font size. Labelled controls have minimum heights, so a large Dynamic Type size grows them instead of clipping the label (the `SearchInput` lock grows with the font scale); only the `FloatingTabBar` labels are capped (1.5×), to fit the fixed bar. With Reduce Motion on, dialogs, sheets, toasts, the `Select` popover, `PricingModal`, `Progress`, `Skeleton` and the `FloatingTabBar` pill do not animate. Dialogs, sheets, toasts, `FloatingTabBar` and `FloatingFAB` stay inside the safe-area insets, and dialog and sheet fields stay above the keyboard on iOS and Android.
|
|
560
568
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/native-ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Shared React Native / Expo UI primitives. Floating surfaces, forms, overlays, toasts, settings chrome, tab bar, AI chat parts, the family app marks, a NativeWind preset, the Expo web root and Clerk + Convex auth screens.",
|
|
6
6
|
"type": "module",
|
|
@@ -37,6 +37,10 @@
|
|
|
37
37
|
"types": "./src/entries/search-input.ts",
|
|
38
38
|
"default": "./src/entries/search-input.ts"
|
|
39
39
|
},
|
|
40
|
+
"./password-input": {
|
|
41
|
+
"types": "./src/entries/password-input.ts",
|
|
42
|
+
"default": "./src/entries/password-input.ts"
|
|
43
|
+
},
|
|
40
44
|
"./page-title": {
|
|
41
45
|
"types": "./src/entries/page-title.ts",
|
|
42
46
|
"default": "./src/entries/page-title.ts"
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { Pressable, View } from "react-native";
|
|
3
|
+
import { IconEye, IconEyeOff } from "@tabler/icons-react-native";
|
|
4
|
+
import { Input } from "./Input";
|
|
5
|
+
import { cn } from "./cn";
|
|
6
|
+
import { fieldStyle, fieldTextStyle, touchSlop, typeStyle } from "./controlStyles";
|
|
7
|
+
import { tokens } from "./tokens";
|
|
8
|
+
import { useLargerText } from "./theme";
|
|
9
|
+
import { useScheme } from "./useScheme";
|
|
10
|
+
|
|
11
|
+
type PasswordInputProps = Omit<React.ComponentPropsWithoutRef<typeof Input>, "secureTextEntry"> & {
|
|
12
|
+
/** Classes for the `View` around the field and the toggle. */
|
|
13
|
+
wrapperClassName?: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Toggle metrics: painted 24 (32 with larger text), 44 with its hit slop. */
|
|
17
|
+
function passwordToggleSize(largerText: boolean) {
|
|
18
|
+
return largerText
|
|
19
|
+
? ({ button: 32, icon: 20, right: 12, paddingRight: 56 } as const)
|
|
20
|
+
: ({ button: 24, icon: 18, right: 8, paddingRight: 44 } as const);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* `Input` for a password, with a show/hide eye button at the end. The text is
|
|
25
|
+
* hidden at first. The toggle flips `secureTextEntry` on the same mounted
|
|
26
|
+
* field, so focus and the cursor stay where they were. The `secureTextEntry`
|
|
27
|
+
* prop is not accepted: the toggle owns it. Every other `Input` prop, `ref`
|
|
28
|
+
* and `testID` pass through. The toggle is labelled "Show password" while the
|
|
29
|
+
* text is hidden and "Hide password" while it shows, has the test ID
|
|
30
|
+
* `${testID}-toggle` (`password-input-toggle` without a `testID`), is painted
|
|
31
|
+
* at 24 and reaches 44 with its hit slop (`touchSlop`). It is hidden when the
|
|
32
|
+
* field is not editable. Inside a `ScrollView`, set
|
|
33
|
+
* `keyboardShouldPersistTaps="handled"` so the first tap toggles while the
|
|
34
|
+
* keyboard is up.
|
|
35
|
+
*/
|
|
36
|
+
const PasswordInput = React.forwardRef<
|
|
37
|
+
React.ElementRef<typeof Input>,
|
|
38
|
+
PasswordInputProps
|
|
39
|
+
>(({ wrapperClassName, className, style, testID, ...props }, ref) => {
|
|
40
|
+
const largerText = useLargerText();
|
|
41
|
+
const scheme = useScheme();
|
|
42
|
+
const [visible, setVisible] = React.useState(false);
|
|
43
|
+
const metrics = passwordToggleSize(largerText);
|
|
44
|
+
const muted = tokens.color.muted[scheme];
|
|
45
|
+
const Icon = visible ? IconEyeOff : IconEye;
|
|
46
|
+
return (
|
|
47
|
+
<View className={cn("relative w-full", wrapperClassName)}>
|
|
48
|
+
<Input
|
|
49
|
+
{...props}
|
|
50
|
+
ref={ref}
|
|
51
|
+
testID={testID}
|
|
52
|
+
// The same size and font classes as `Input`, so the field has the same
|
|
53
|
+
// height and type. `Input` adds them too; `cn` merges the repeat.
|
|
54
|
+
// The type comes from these classes only (no style `fontSize`), so it
|
|
55
|
+
// cannot diverge from NativeWind's `text-base` / `text-xl`.
|
|
56
|
+
className={cn(
|
|
57
|
+
"min-h-10 border px-3.5 py-2 text-base font-instrument-sans",
|
|
58
|
+
largerText && "min-h-16 px-4 py-4 text-xl font-instrument-sans-medium",
|
|
59
|
+
className,
|
|
60
|
+
)}
|
|
61
|
+
// After the spread, so a caller cannot fight the toggle.
|
|
62
|
+
secureTextEntry={!visible}
|
|
63
|
+
// The `Input` styles. `fontSize` and `lineHeight` are not set: the field
|
|
64
|
+
// inherits `Input`'s type through the same className. Then room for the
|
|
65
|
+
// toggle, so text does not run under it.
|
|
66
|
+
style={[
|
|
67
|
+
fieldStyle(scheme),
|
|
68
|
+
fieldTextStyle(scheme),
|
|
69
|
+
largerText ? typeStyle("medium") : null,
|
|
70
|
+
{ paddingRight: metrics.paddingRight },
|
|
71
|
+
style,
|
|
72
|
+
]}
|
|
73
|
+
/>
|
|
74
|
+
{props.editable !== false ? (
|
|
75
|
+
<View
|
|
76
|
+
pointerEvents="box-none"
|
|
77
|
+
className="absolute bottom-0 top-0 justify-center"
|
|
78
|
+
style={{ right: metrics.right }}
|
|
79
|
+
>
|
|
80
|
+
<Pressable
|
|
81
|
+
testID={testID ? `${testID}-toggle` : "password-input-toggle"}
|
|
82
|
+
accessibilityRole="button"
|
|
83
|
+
accessibilityLabel={visible ? "Hide password" : "Show password"}
|
|
84
|
+
hitSlop={touchSlop(metrics.button)}
|
|
85
|
+
onPress={() => setVisible((current) => !current)}
|
|
86
|
+
className="items-center justify-center rounded-md active:opacity-70"
|
|
87
|
+
style={{ width: metrics.button, height: metrics.button }}
|
|
88
|
+
>
|
|
89
|
+
{/* `strokeWidth`, not `stroke`: here `stroke` is the colour. */}
|
|
90
|
+
<Icon size={metrics.icon} color={muted} strokeWidth={1.75} />
|
|
91
|
+
</Pressable>
|
|
92
|
+
</View>
|
|
93
|
+
) : null}
|
|
94
|
+
</View>
|
|
95
|
+
);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
PasswordInput.displayName = "PasswordInput";
|
|
99
|
+
|
|
100
|
+
export { PasswordInput };
|
|
101
|
+
export type { PasswordInputProps };
|
|
@@ -5,15 +5,22 @@ import { useRouter } from "expo-router";
|
|
|
5
5
|
import { Button } from "../Button";
|
|
6
6
|
import { textStyle } from "../controlStyles";
|
|
7
7
|
import { Input } from "../Input";
|
|
8
|
+
import { PasswordInput } from "../PasswordInput";
|
|
8
9
|
import { toast } from "../toastStore";
|
|
9
10
|
import { useScheme } from "../useScheme";
|
|
10
11
|
import { AuthScreen, FieldError, OrDivider } from "./AuthScreen";
|
|
11
|
-
import { authErrorMessage } from "./authErrors";
|
|
12
|
+
import { authErrorMessage, logAuthFailure } from "./authErrors";
|
|
12
13
|
import { SecondFactorScreen } from "./SecondFactorScreen";
|
|
13
14
|
import {
|
|
15
|
+
pickFirstFactorStrategy,
|
|
14
16
|
pickSecondFactorStrategy,
|
|
17
|
+
prepareFirstFactorIfNeeded,
|
|
18
|
+
submitFirstFactor,
|
|
19
|
+
supportedFirstFactorStrategies,
|
|
15
20
|
supportedSecondFactorStrategies,
|
|
16
21
|
useSecondFactor,
|
|
22
|
+
type FirstFactor,
|
|
23
|
+
type FirstFactorStrategy,
|
|
17
24
|
type SecondFactor,
|
|
18
25
|
type SecondFactorStrategy,
|
|
19
26
|
} from "./totp";
|
|
@@ -121,11 +128,13 @@ export type SignInScreenProps = AuthNavigationOptions & {
|
|
|
121
128
|
footer?: ReactNode;
|
|
122
129
|
/**
|
|
123
130
|
* Called with the sign-in when the built-in UI cannot finish it:
|
|
124
|
-
* `needs_identifier`,
|
|
131
|
+
* `needs_identifier`, any unknown status, `needs_first_factor` when no
|
|
132
|
+
* `email_code` or `phone_code` first factor exists (with its id), and
|
|
125
133
|
* `needs_second_factor` or `needs_client_trust` when no supported strategy
|
|
126
134
|
* (totp, backup code, phone code, email code) exists. The built-in screen
|
|
127
|
-
*
|
|
128
|
-
* `
|
|
135
|
+
* runs `needs_first_factor` with an email or phone code, and always runs
|
|
136
|
+
* `needs_second_factor`, `needs_client_trust` and `needs_new_password`
|
|
137
|
+
* itself. When called, the web-fallback message is not
|
|
129
138
|
* shown. Without it, the screen shows the web fallback and logs
|
|
130
139
|
* `console.warn`. Ignored in `sign-up`.
|
|
131
140
|
*/
|
|
@@ -168,6 +177,11 @@ export function SignInScreen({
|
|
|
168
177
|
const [code, setCode] = useState("");
|
|
169
178
|
const [pendingVerification, setPendingVerification] = useState(false);
|
|
170
179
|
const [pendingSecondFactor, setPendingSecondFactor] = useState(false);
|
|
180
|
+
const [pendingFirstFactor, setPendingFirstFactor] = useState(false);
|
|
181
|
+
const [firstFactors, setFirstFactors] = useState<FirstFactor[]>([]);
|
|
182
|
+
const [firstStrategy, setFirstStrategy] = useState<FirstFactorStrategy>("email_code");
|
|
183
|
+
const [firstLoading, setFirstLoading] = useState(false);
|
|
184
|
+
const [firstError, setFirstError] = useState("");
|
|
171
185
|
const [factors, setFactors] = useState<SecondFactor[]>([]);
|
|
172
186
|
const [clientTrust, setClientTrust] = useState(false);
|
|
173
187
|
const [pendingNewPassword, setPendingNewPassword] = useState(false);
|
|
@@ -224,6 +238,71 @@ export function SignInScreen({
|
|
|
224
238
|
await chooseStrategy(strategy, list);
|
|
225
239
|
};
|
|
226
240
|
|
|
241
|
+
const chooseFirstStrategy = async (strategy: FirstFactorStrategy, list: FirstFactor[]) => {
|
|
242
|
+
const { signIn } = signInState;
|
|
243
|
+
if (!signIn) return;
|
|
244
|
+
setFirstError("");
|
|
245
|
+
setFirstStrategy(strategy);
|
|
246
|
+
setPendingFirstFactor(true);
|
|
247
|
+
setFirstLoading(true);
|
|
248
|
+
const sent = await prepareFirstFactorIfNeeded({
|
|
249
|
+
signIn,
|
|
250
|
+
strategy,
|
|
251
|
+
factor: list.find((factor) => factor.strategy === strategy),
|
|
252
|
+
});
|
|
253
|
+
if (!sent.ok) setFirstError(sent.error);
|
|
254
|
+
setFirstLoading(false);
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const startFirstFactor = async (attempt: IncompleteSignIn) => {
|
|
258
|
+
const list = attempt.supportedFirstFactors ?? [];
|
|
259
|
+
const strategy = pickFirstFactorStrategy(list);
|
|
260
|
+
if (!strategy) return unhandled(attempt);
|
|
261
|
+
setFirstFactors(list);
|
|
262
|
+
await chooseFirstStrategy(strategy, list);
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// Routes a sign-in attempt. `needs_first_factor` is built in only after `signIn.create`.
|
|
266
|
+
const routeAttempt = async (attempt: IncompleteSignIn, afterCreate: boolean) => {
|
|
267
|
+
const { setActive } = signInState;
|
|
268
|
+
// Clerk's `SignInStatus` omits `needs_client_trust`: widen before comparing.
|
|
269
|
+
const status: string | null = attempt.status;
|
|
270
|
+
if (status === "complete" && attempt.createdSessionId && setActive) {
|
|
271
|
+
await setActive({ session: attempt.createdSessionId });
|
|
272
|
+
done();
|
|
273
|
+
} else if (status === "needs_new_password") {
|
|
274
|
+
setPendingFirstFactor(false);
|
|
275
|
+
setPendingNewPassword(true);
|
|
276
|
+
} else if (status === "needs_second_factor" || status === "needs_client_trust") {
|
|
277
|
+
setPendingFirstFactor(false);
|
|
278
|
+
await startSecondFactor(attempt, status === "needs_client_trust");
|
|
279
|
+
} else if (status === "needs_first_factor" && afterCreate) {
|
|
280
|
+
await startFirstFactor(attempt);
|
|
281
|
+
} else {
|
|
282
|
+
unhandled(attempt);
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
const onFirstFactor = async (firstCode: string) => {
|
|
287
|
+
const { isLoaded, signIn } = signInState;
|
|
288
|
+
if (!isLoaded || !signIn || firstLoading) return;
|
|
289
|
+
setFirstLoading(true);
|
|
290
|
+
setFirstError("");
|
|
291
|
+
const result = await submitFirstFactor({ signIn, code: firstCode, strategy: firstStrategy });
|
|
292
|
+
if (!result.ok) {
|
|
293
|
+
setFirstError(result.error);
|
|
294
|
+
setFirstLoading(false);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
await routeAttempt(result.attempt, false);
|
|
299
|
+
} catch (caught) {
|
|
300
|
+
setFirstError(authErrorMessage(caught, AUTH_MESSAGES.verifyFailed));
|
|
301
|
+
} finally {
|
|
302
|
+
setFirstLoading(false);
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
|
|
227
306
|
const onNewPassword = async () => {
|
|
228
307
|
const { isLoaded, signIn, setActive } = signInState;
|
|
229
308
|
if (!isLoaded || !signIn || !setActive || submitting) return;
|
|
@@ -262,18 +341,13 @@ export function SignInScreen({
|
|
|
262
341
|
setError("");
|
|
263
342
|
try {
|
|
264
343
|
const attempt = await signIn.create({ identifier: email, password });
|
|
265
|
-
|
|
266
|
-
await setActive({ session: attempt.createdSessionId });
|
|
267
|
-
done();
|
|
268
|
-
} else if (attempt.status === "needs_new_password") {
|
|
269
|
-
setPendingNewPassword(true);
|
|
270
|
-
} else if (attempt.status === "needs_second_factor" || attempt.status === "needs_client_trust") {
|
|
271
|
-
await startSecondFactor(attempt, attempt.status === "needs_client_trust");
|
|
272
|
-
} else {
|
|
273
|
-
unhandled(attempt);
|
|
274
|
-
}
|
|
344
|
+
await routeAttempt(attempt, true);
|
|
275
345
|
} catch (caught) {
|
|
276
|
-
|
|
346
|
+
logAuthFailure("create", caught);
|
|
347
|
+
fail(
|
|
348
|
+
AUTH_MESSAGES.signInFailed,
|
|
349
|
+
authErrorMessage(caught, AUTH_MESSAGES.invalidCredentials, { credentials: true }),
|
|
350
|
+
);
|
|
277
351
|
} finally {
|
|
278
352
|
setSubmitting(false);
|
|
279
353
|
}
|
|
@@ -287,6 +361,8 @@ export function SignInScreen({
|
|
|
287
361
|
const onSecondFactorBack = () => {
|
|
288
362
|
// The pending attempt stays; the next `signIn.create` replaces it.
|
|
289
363
|
setPendingSecondFactor(false);
|
|
364
|
+
setPendingFirstFactor(false);
|
|
365
|
+
setFirstError("");
|
|
290
366
|
setPendingNewPassword(false);
|
|
291
367
|
setNewPassword("");
|
|
292
368
|
setConfirmPassword("");
|
|
@@ -368,26 +444,24 @@ export function SignInScreen({
|
|
|
368
444
|
subtitle={AUTH_MESSAGES.newPasswordDescription}
|
|
369
445
|
header={header}
|
|
370
446
|
>
|
|
371
|
-
<
|
|
447
|
+
<PasswordInput
|
|
372
448
|
testID={id("new-password")}
|
|
373
449
|
accessibilityLabel={AUTH_MESSAGES.newPasswordLabel}
|
|
374
450
|
autoCapitalize="none"
|
|
375
451
|
autoComplete="new-password"
|
|
376
452
|
textContentType="newPassword"
|
|
377
|
-
secureTextEntry
|
|
378
453
|
autoFocus
|
|
379
454
|
returnKeyType="next"
|
|
380
455
|
value={newPassword}
|
|
381
456
|
placeholder={AUTH_MESSAGES.newPasswordLabel}
|
|
382
457
|
onChangeText={setNewPassword}
|
|
383
458
|
/>
|
|
384
|
-
<
|
|
459
|
+
<PasswordInput
|
|
385
460
|
testID={id("confirm-password")}
|
|
386
461
|
accessibilityLabel={AUTH_MESSAGES.confirmPasswordLabel}
|
|
387
462
|
autoCapitalize="none"
|
|
388
463
|
autoComplete="new-password"
|
|
389
464
|
textContentType="newPassword"
|
|
390
|
-
secureTextEntry
|
|
391
465
|
returnKeyType="go"
|
|
392
466
|
value={confirmPassword}
|
|
393
467
|
placeholder={AUTH_MESSAGES.confirmPasswordLabel}
|
|
@@ -405,6 +479,40 @@ export function SignInScreen({
|
|
|
405
479
|
);
|
|
406
480
|
}
|
|
407
481
|
|
|
482
|
+
if (pendingFirstFactor && !pendingSecondFactor && !pendingNewPassword) {
|
|
483
|
+
const others = supportedFirstFactorStrategies(firstFactors).filter((strategy) => strategy !== firstStrategy);
|
|
484
|
+
const switchTo = others[0] ?? null;
|
|
485
|
+
const copy = secondFactorCopy(firstStrategy, false);
|
|
486
|
+
return (
|
|
487
|
+
<SecondFactorScreen
|
|
488
|
+
key={`first-${firstStrategy}`}
|
|
489
|
+
title={copy.title}
|
|
490
|
+
description={copy.description}
|
|
491
|
+
footer={
|
|
492
|
+
switchTo ? (
|
|
493
|
+
<Button
|
|
494
|
+
testID={id("first-factor-switch")}
|
|
495
|
+
variant="link"
|
|
496
|
+
size="sm"
|
|
497
|
+
fullWidth={false}
|
|
498
|
+
disabled={firstLoading}
|
|
499
|
+
onPress={() => void chooseFirstStrategy(switchTo, firstFactors)}
|
|
500
|
+
>
|
|
501
|
+
{METHOD_LABEL[switchTo]}
|
|
502
|
+
</Button>
|
|
503
|
+
) : undefined
|
|
504
|
+
}
|
|
505
|
+
onSubmit={onFirstFactor}
|
|
506
|
+
error={firstError}
|
|
507
|
+
loading={firstLoading}
|
|
508
|
+
onBack={onSecondFactorBack}
|
|
509
|
+
backLabel="Use a different account"
|
|
510
|
+
header={header}
|
|
511
|
+
testIDPrefix={id("first-factor")}
|
|
512
|
+
/>
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
|
|
408
516
|
if (pendingSecondFactor) {
|
|
409
517
|
const active = secondFactor.strategy;
|
|
410
518
|
const available = supportedSecondFactorStrategies(factors);
|
|
@@ -528,13 +636,12 @@ export function SignInScreen({
|
|
|
528
636
|
placeholder="Email"
|
|
529
637
|
onChangeText={setEmail}
|
|
530
638
|
/>
|
|
531
|
-
<
|
|
639
|
+
<PasswordInput
|
|
532
640
|
testID={id("password")}
|
|
533
641
|
accessibilityLabel="Password"
|
|
534
642
|
autoCapitalize="none"
|
|
535
643
|
autoComplete={signUp ? "new-password" : "password"}
|
|
536
644
|
textContentType={signUp ? "newPassword" : "password"}
|
|
537
|
-
secureTextEntry
|
|
538
645
|
returnKeyType="go"
|
|
539
646
|
value={password}
|
|
540
647
|
placeholder="Password"
|
package/src/auth/authErrors.ts
CHANGED
|
@@ -1,19 +1,97 @@
|
|
|
1
1
|
import { isClerkAPIResponseError } from "@clerk/clerk-expo";
|
|
2
2
|
|
|
3
3
|
/** Words that must not reach the user: the auth provider and stack names. */
|
|
4
|
-
const PRODUCT_NAMES = /\b(clerk|convex)\b/
|
|
4
|
+
const PRODUCT_NAMES = /\b(clerk|convex)\b/gi;
|
|
5
|
+
|
|
6
|
+
/** The only Clerk codes that mean "Invalid email or password". */
|
|
7
|
+
export const CREDENTIAL_ERROR_CODES = ["form_password_incorrect", "form_identifier_not_found"] as const;
|
|
8
|
+
|
|
9
|
+
type ClerkErrorItem = {
|
|
10
|
+
code?: unknown;
|
|
11
|
+
message?: unknown;
|
|
12
|
+
longMessage?: unknown;
|
|
13
|
+
meta?: { paramName?: unknown } | null;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
type ParsedAuthError = {
|
|
17
|
+
errors: ClerkErrorItem[];
|
|
18
|
+
status?: number;
|
|
19
|
+
clerkTraceId?: string;
|
|
20
|
+
errorName?: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const asString = (value: unknown): string | undefined =>
|
|
24
|
+
typeof value === "string" && value.length > 0 ? value : undefined;
|
|
25
|
+
|
|
26
|
+
/** Reads a Clerk API error, or a plain `{ errors: [...] }` object. No `zod`. */
|
|
27
|
+
function parseAuthError(error: unknown): ParsedAuthError | null {
|
|
28
|
+
if (typeof error !== "object" || error === null) return null;
|
|
29
|
+
const record = error as Record<string, unknown>;
|
|
30
|
+
if (!isClerkAPIResponseError(error) && !Array.isArray(record.errors)) return null;
|
|
31
|
+
const errors = Array.isArray(record.errors)
|
|
32
|
+
? (record.errors as unknown[]).filter((item): item is ClerkErrorItem => typeof item === "object" && item !== null)
|
|
33
|
+
: [];
|
|
34
|
+
return {
|
|
35
|
+
errors,
|
|
36
|
+
status: typeof record.status === "number" ? record.status : undefined,
|
|
37
|
+
clerkTraceId: asString(record.clerkTraceId),
|
|
38
|
+
errorName: asString(record.name),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function firstError(parsed: ParsedAuthError | null) {
|
|
43
|
+
const first = parsed?.errors[0];
|
|
44
|
+
return {
|
|
45
|
+
code: asString(first?.code),
|
|
46
|
+
message: asString(first?.message),
|
|
47
|
+
longMessage: asString(first?.longMessage),
|
|
48
|
+
paramName: asString(first?.meta?.paramName),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Logs a failed auth call as one structured `console.error`. It holds the
|
|
54
|
+
* Clerk code, message, longMessage and meta.paramName, plus stage, errorName,
|
|
55
|
+
* status and clerkTraceId when present. Only the error object is read, so a
|
|
56
|
+
* password or one-time code is never logged.
|
|
57
|
+
*/
|
|
58
|
+
export function logAuthFailure(stage: string, error: unknown): void {
|
|
59
|
+
const parsed = parseAuthError(error);
|
|
60
|
+
const { code, message, longMessage, paramName } = firstError(parsed);
|
|
61
|
+
const errorName = parsed?.errorName ?? (error instanceof Error ? error.name : undefined);
|
|
62
|
+
console.error("[sign-in] failure", {
|
|
63
|
+
stage,
|
|
64
|
+
...(errorName ? { errorName } : {}),
|
|
65
|
+
...(parsed?.status !== undefined ? { status: parsed.status } : {}),
|
|
66
|
+
...(parsed?.clerkTraceId ? { clerkTraceId: parsed.clerkTraceId } : {}),
|
|
67
|
+
code,
|
|
68
|
+
message,
|
|
69
|
+
longMessage,
|
|
70
|
+
meta: { paramName },
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type AuthErrorOptions = {
|
|
75
|
+
/**
|
|
76
|
+
* Sign-in with email and password. `form_password_incorrect` and
|
|
77
|
+
* `form_identifier_not_found` (only these) return `fallback`.
|
|
78
|
+
*/
|
|
79
|
+
credentials?: boolean;
|
|
80
|
+
};
|
|
5
81
|
|
|
6
82
|
/**
|
|
7
|
-
* A message to show for an auth error.
|
|
8
|
-
* `longMessage` or `message`
|
|
9
|
-
*
|
|
10
|
-
*
|
|
83
|
+
* A message to show for an auth error. For a Clerk error it gives the first
|
|
84
|
+
* `longMessage` or `message`, with `clerk` and `convex` written as "the
|
|
85
|
+
* sign-in service", then `(code: <code>)`. With no text it gives `fallback`,
|
|
86
|
+
* still followed by the code when there is one. With `credentials: true`, the
|
|
87
|
+
* two credential codes give `fallback` alone. Anything that is not a Clerk
|
|
88
|
+
* error gives `fallback`. Never shows a raw exception message.
|
|
11
89
|
*/
|
|
12
|
-
export function authErrorMessage(error: unknown, fallback: string): string {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return
|
|
90
|
+
export function authErrorMessage(error: unknown, fallback: string, options: AuthErrorOptions = {}): string {
|
|
91
|
+
const parsed = parseAuthError(error);
|
|
92
|
+
if (!parsed) return fallback;
|
|
93
|
+
const { code, message, longMessage } = firstError(parsed);
|
|
94
|
+
if (options.credentials && code && (CREDENTIAL_ERROR_CODES as readonly string[]).includes(code)) return fallback;
|
|
95
|
+
const text = (longMessage ?? message)?.replace(PRODUCT_NAMES, "the sign-in service") ?? fallback;
|
|
96
|
+
return code ? `${text} (code: ${code})` : text;
|
|
19
97
|
}
|
package/src/auth/index.ts
CHANGED
|
@@ -6,7 +6,8 @@ export { AuthProviders } from "./AuthProviders";
|
|
|
6
6
|
export type { AuthProvidersProps } from "./AuthProviders";
|
|
7
7
|
export { AuthScreen, OrDivider, FieldError } from "./AuthScreen";
|
|
8
8
|
export type { AuthScreenProps } from "./AuthScreen";
|
|
9
|
-
export { authErrorMessage } from "./authErrors";
|
|
9
|
+
export { authErrorMessage, logAuthFailure, CREDENTIAL_ERROR_CODES } from "./authErrors";
|
|
10
|
+
export type { AuthErrorOptions } from "./authErrors";
|
|
10
11
|
export {
|
|
11
12
|
GoogleSignInButton,
|
|
12
13
|
useGoogleSignIn,
|
|
@@ -26,6 +27,11 @@ export {
|
|
|
26
27
|
submitTotpSecondFactor,
|
|
27
28
|
submitSecondFactor,
|
|
28
29
|
prepareSecondFactorIfNeeded,
|
|
30
|
+
prepareFirstFactorIfNeeded,
|
|
31
|
+
submitFirstFactor,
|
|
32
|
+
pickFirstFactorStrategy,
|
|
33
|
+
supportedFirstFactorStrategies,
|
|
34
|
+
FIRST_FACTOR_PREFERENCE,
|
|
29
35
|
pickSecondFactorStrategy,
|
|
30
36
|
supportedSecondFactorStrategies,
|
|
31
37
|
SECOND_FACTOR_PREFERENCE,
|
|
@@ -33,6 +39,10 @@ export {
|
|
|
33
39
|
TOTP_MESSAGES,
|
|
34
40
|
} from "./totp";
|
|
35
41
|
export type {
|
|
42
|
+
FirstFactor,
|
|
43
|
+
FirstFactorResult,
|
|
44
|
+
FirstFactorSignIn,
|
|
45
|
+
FirstFactorStrategy,
|
|
36
46
|
SecondFactor,
|
|
37
47
|
SecondFactorSignIn,
|
|
38
48
|
SecondFactorStrategy,
|
package/src/auth/totp.ts
CHANGED
|
@@ -125,6 +125,104 @@ export async function submitSecondFactor(args: {
|
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
/** The first-factor code strategies the built-in step handles. */
|
|
129
|
+
export type FirstFactorStrategy = "email_code" | "phone_code";
|
|
130
|
+
|
|
131
|
+
/** Default order: `email_code`, then `phone_code`. */
|
|
132
|
+
export const FIRST_FACTOR_PREFERENCE: readonly FirstFactorStrategy[] = ["email_code", "phone_code"];
|
|
133
|
+
|
|
134
|
+
/** One entry of `signIn.supportedFirstFactors`. */
|
|
135
|
+
export type FirstFactor = {
|
|
136
|
+
strategy: string;
|
|
137
|
+
emailAddressId?: string;
|
|
138
|
+
phoneNumberId?: string;
|
|
139
|
+
safeIdentifier?: string;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** The part of the sign-in resource that a first-factor code needs. Tests pass a mock. */
|
|
143
|
+
export type FirstFactorSignIn = {
|
|
144
|
+
supportedFirstFactors?: FirstFactor[] | null;
|
|
145
|
+
prepareFirstFactor?(params: {
|
|
146
|
+
strategy: FirstFactorStrategy;
|
|
147
|
+
phoneNumberId?: string;
|
|
148
|
+
emailAddressId?: string;
|
|
149
|
+
}): Promise<unknown>;
|
|
150
|
+
attemptFirstFactor(params: { strategy: FirstFactorStrategy; code: string }): Promise<AttemptResult>;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
/** A first-factor result: the attempt, for the caller to route, or an error. */
|
|
154
|
+
export type FirstFactorResult = { ok: true; attempt: AttemptResult } | { ok: false; error: string };
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The first-factor strategies in `factors` that the built-in step handles, in
|
|
158
|
+
* preference order. A factor counts only when it has the id that
|
|
159
|
+
* `prepareFirstFactor` needs (`emailAddressId` or `phoneNumberId`).
|
|
160
|
+
*/
|
|
161
|
+
export function supportedFirstFactorStrategies(
|
|
162
|
+
factors: readonly FirstFactor[] | null | undefined,
|
|
163
|
+
): FirstFactorStrategy[] {
|
|
164
|
+
const list = factors ?? [];
|
|
165
|
+
return FIRST_FACTOR_PREFERENCE.filter((strategy) =>
|
|
166
|
+
list.some(
|
|
167
|
+
(factor) =>
|
|
168
|
+
factor.strategy === strategy &&
|
|
169
|
+
Boolean(strategy === "email_code" ? factor.emailAddressId : factor.phoneNumberId),
|
|
170
|
+
),
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The default first-factor strategy: `email_code`, then `phone_code`. `null` when none is supported. */
|
|
175
|
+
export function pickFirstFactorStrategy(
|
|
176
|
+
factors: readonly FirstFactor[] | null | undefined,
|
|
177
|
+
): FirstFactorStrategy | null {
|
|
178
|
+
return supportedFirstFactorStrategies(factors)[0] ?? null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Sends the first-factor code with the `emailAddressId` or `phoneNumberId` of
|
|
183
|
+
* the matching factor. Without that id it returns an error and makes no call.
|
|
184
|
+
* Never throws.
|
|
185
|
+
*/
|
|
186
|
+
export async function prepareFirstFactorIfNeeded(args: {
|
|
187
|
+
signIn: Pick<FirstFactorSignIn, "supportedFirstFactors" | "prepareFirstFactor">;
|
|
188
|
+
strategy: FirstFactorStrategy;
|
|
189
|
+
factor?: FirstFactor;
|
|
190
|
+
}): Promise<TotpResult> {
|
|
191
|
+
const { signIn, strategy } = args;
|
|
192
|
+
if (!signIn.prepareFirstFactor) return { ok: false, error: TOTP_MESSAGES.sendFailed };
|
|
193
|
+
const factor = args.factor ?? signIn.supportedFirstFactors?.find((item) => item.strategy === strategy);
|
|
194
|
+
try {
|
|
195
|
+
if (strategy === "phone_code") {
|
|
196
|
+
if (!factor?.phoneNumberId) return { ok: false, error: TOTP_MESSAGES.sendFailed };
|
|
197
|
+
await signIn.prepareFirstFactor({ strategy, phoneNumberId: factor.phoneNumberId });
|
|
198
|
+
} else {
|
|
199
|
+
if (!factor?.emailAddressId) return { ok: false, error: TOTP_MESSAGES.sendFailed };
|
|
200
|
+
await signIn.prepareFirstFactor({ strategy, emailAddressId: factor.emailAddressId });
|
|
201
|
+
}
|
|
202
|
+
return { ok: true };
|
|
203
|
+
} catch (caught) {
|
|
204
|
+
return { ok: false, error: authErrorMessage(caught, TOTP_MESSAGES.sendFailed) };
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Checks a first-factor code. It does not start the session: the attempt may
|
|
210
|
+
* need a second factor or a new password, so the caller routes it. Never
|
|
211
|
+
* throws: a failure is `{ ok: false, error }`.
|
|
212
|
+
*/
|
|
213
|
+
export async function submitFirstFactor(args: {
|
|
214
|
+
signIn: Pick<FirstFactorSignIn, "attemptFirstFactor">;
|
|
215
|
+
code: string;
|
|
216
|
+
strategy: FirstFactorStrategy;
|
|
217
|
+
}): Promise<FirstFactorResult> {
|
|
218
|
+
try {
|
|
219
|
+
const attempt = await args.signIn.attemptFirstFactor({ strategy: args.strategy, code: args.code });
|
|
220
|
+
return { ok: true, attempt };
|
|
221
|
+
} catch (caught) {
|
|
222
|
+
return { ok: false, error: authErrorMessage(caught, TOTP_MESSAGES.invalidCodeGeneric) };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
128
226
|
/** Checks a TOTP code and starts the session. TOTP needs no `prepareSecondFactor`. Same as `submitSecondFactor` with `strategy: "totp"`. */
|
|
129
227
|
export function submitTotpSecondFactor(args: {
|
|
130
228
|
signIn: TotpSignIn;
|
|
@@ -9,6 +9,8 @@ export { Input } from "../Input";
|
|
|
9
9
|
export type { InputProps } from "../Input";
|
|
10
10
|
export { SearchInput } from "../SearchInput";
|
|
11
11
|
export type { SearchInputProps } from "../SearchInput";
|
|
12
|
+
export { PasswordInput } from "../PasswordInput";
|
|
13
|
+
export type { PasswordInputProps } from "../PasswordInput";
|
|
12
14
|
export { Textarea } from "../Textarea";
|
|
13
15
|
export type { TextareaProps } from "../Textarea";
|
|
14
16
|
export { Label } from "../Label";
|
package/src/index.ts
CHANGED
|
@@ -45,6 +45,8 @@ export { Input } from "./Input";
|
|
|
45
45
|
export type { InputProps } from "./Input";
|
|
46
46
|
export { SearchInput } from "./SearchInput";
|
|
47
47
|
export type { SearchInputProps } from "./SearchInput";
|
|
48
|
+
export { PasswordInput } from "./PasswordInput";
|
|
49
|
+
export type { PasswordInputProps } from "./PasswordInput";
|
|
48
50
|
export { Textarea } from "./Textarea";
|
|
49
51
|
export type { TextareaProps } from "./Textarea";
|
|
50
52
|
export { Label } from "./Label";
|