@authara/react-native 0.0.0-stage → 0.0.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,195 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { ActivityIndicator, Pressable, StyleSheet, Text, View, useColorScheme, } from "react-native";
4
+ import { Path, Rect, Svg } from "react-native-svg";
5
+ import { resolveAutharaAction, } from "./button-contract.js";
6
+ import { appleButtonAppearance, autharaButtonLabel, googleButtonAppearance, microsoftButtonAppearance, } from "./button-appearance.js";
7
+ import { autharaButtonErrorMessage, isAutharaProviderCancellation, toAutharaButtonError, } from "./button-error.js";
8
+ import { useAuthara } from "./context.js";
9
+ function useResolvedColorMode(mode) {
10
+ const system = useColorScheme();
11
+ return mode === "system" ? (system ?? "light") : mode;
12
+ }
13
+ function reportError(error, setError, onError) {
14
+ setError(autharaButtonErrorMessage(error));
15
+ onError?.(error);
16
+ }
17
+ function ProviderButton({ provider, providerLabel, action, audience, authenticationChallengeId, recoveryLinkId, onSuccess, onError, onCancel, variant, label, appearance, style, textStyle, errorTextStyle, fallback = null, showError = true, onUnavailable, disabled, accessibilityLabel, accessibilityState, onPress, ...pressableProps }) {
18
+ const { client } = useAuthara();
19
+ const [pending, setPending] = useState(false);
20
+ const [error, setError] = useState();
21
+ const unavailableNotified = useRef(false);
22
+ const available = client.hasNativeProvider(provider);
23
+ const inactive = Boolean(disabled || pending);
24
+ useEffect(() => {
25
+ if (!available && !unavailableNotified.current) {
26
+ unavailableNotified.current = true;
27
+ onUnavailable?.();
28
+ }
29
+ }, [available, onUnavailable]);
30
+ if (!available)
31
+ return _jsx(_Fragment, { children: fallback });
32
+ const icon = pending ? (_jsx(ActivityIndicator, { color: appearance.text, size: "small" })) : (_jsx(ProviderIcon, { provider: provider, color: appearance.text }));
33
+ return (_jsxs(View, { style: [styles.container, { width: appearance.width }], children: [_jsxs(Pressable, { ...pressableProps, accessibilityRole: "button", accessibilityLabel: accessibilityLabel ?? label, accessibilityState: {
34
+ ...accessibilityState,
35
+ disabled: inactive,
36
+ busy: pending,
37
+ }, disabled: inactive, onPress: (event) => {
38
+ onPress?.(event);
39
+ if (event.isDefaultPrevented())
40
+ return;
41
+ setPending(true);
42
+ setError(undefined);
43
+ void (async () => {
44
+ let selected;
45
+ try {
46
+ selected = resolveAutharaAction(action, audience, authenticationChallengeId, recoveryLinkId);
47
+ }
48
+ catch (caught) {
49
+ reportError(toAutharaButtonError(caught, `The ${providerLabel} button action is not configured correctly.`, "configuration"), setError, onError);
50
+ return;
51
+ }
52
+ let result;
53
+ try {
54
+ result = await client.runNativeProviderAction(provider, selected);
55
+ }
56
+ catch (caught) {
57
+ if (isAutharaProviderCancellation(caught)) {
58
+ onCancel?.();
59
+ return;
60
+ }
61
+ reportError(toAutharaButtonError(caught, `${providerLabel} ${selected.action} failed.`, "provider"), setError, onError);
62
+ return;
63
+ }
64
+ try {
65
+ await onSuccess?.(result);
66
+ }
67
+ catch (caught) {
68
+ reportError(toAutharaButtonError(caught, `The ${providerLabel} success callback failed.`, "consumer"), setError, onError);
69
+ }
70
+ })().finally(() => setPending(false));
71
+ }, style: ({ pressed }) => [
72
+ styles.button,
73
+ {
74
+ height: appearance.height,
75
+ paddingHorizontal: variant === "icon" ? 0 : appearance.horizontalPadding,
76
+ borderColor: appearance.border,
77
+ borderRadius: appearance.borderRadius,
78
+ borderWidth: appearance.borderWidth,
79
+ backgroundColor: appearance.fill,
80
+ },
81
+ style,
82
+ pressed && !inactive && styles.pressed,
83
+ inactive && styles.disabled,
84
+ ], children: [_jsx(View, { accessibilityElementsHidden: true, importantForAccessibility: "no-hide-descendants", style: [
85
+ styles.iconSlot,
86
+ appearance.iconLeft !== undefined && {
87
+ position: "absolute",
88
+ left: appearance.iconLeft,
89
+ },
90
+ ], children: icon }), variant !== "icon" ? (_jsx(Text, { numberOfLines: 1, style: [
91
+ styles.label,
92
+ {
93
+ color: appearance.text,
94
+ fontFamily: appearance.fontFamily,
95
+ fontWeight: appearance.fontWeight,
96
+ },
97
+ textStyle,
98
+ ], children: label })) : null] }), showError && error ? (_jsx(Text, { accessibilityRole: "alert", selectable: true, style: [styles.error, errorTextStyle], children: error })) : null] }));
99
+ }
100
+ export function GoogleButton(props) {
101
+ const internal = props;
102
+ const { action = "login", audience, authenticationChallengeId, recoveryLinkId, onSuccess, onError, variant = "text", size = "large", label = action === "login" ? "sign-in" : "continue", mode = "light", theme, border, shape = "rectangular", logoAlignment = "center", buttonText, width, locale, ...buttonProps } = internal;
103
+ void locale;
104
+ const resolvedMode = useResolvedColorMode(mode);
105
+ const visibleLabel = buttonText ??
106
+ (variant === "provider" ? "Google" : autharaButtonLabel(label, "Google"));
107
+ return (_jsx(ProviderButton, { ...buttonProps, provider: "google", providerLabel: "Google", action: action, audience: audience, authenticationChallengeId: authenticationChallengeId, recoveryLinkId: recoveryLinkId, onSuccess: onSuccess, onError: onError, variant: variant, label: visibleLabel, appearance: googleButtonAppearance({
108
+ variant,
109
+ size,
110
+ width,
111
+ mode: resolvedMode,
112
+ theme,
113
+ border,
114
+ shape,
115
+ logoAlignment,
116
+ }) }));
117
+ }
118
+ export function AppleButton(props) {
119
+ const internal = props;
120
+ const { action = "login", audience, authenticationChallengeId, recoveryLinkId, onSuccess, onError, onCancel, variant = "text", size = "large", label = action === "login" ? "sign-in" : "continue", mode = "light", color, border = false, borderRadius = 12, align = "center", buttonText, width, locale, ...buttonProps } = internal;
121
+ void locale;
122
+ const resolvedMode = useResolvedColorMode(mode);
123
+ const resolvedColor = color ?? (resolvedMode === "dark" ? "white" : "black");
124
+ const visibleLabel = buttonText ??
125
+ (variant === "provider" ? "Apple" : autharaButtonLabel(label, "Apple"));
126
+ return (_jsx(ProviderButton, { ...buttonProps, provider: "apple", providerLabel: "Apple", action: action, audience: audience, authenticationChallengeId: authenticationChallengeId, recoveryLinkId: recoveryLinkId, onSuccess: onSuccess, onError: onError, onCancel: onCancel, variant: variant, label: visibleLabel, appearance: appleButtonAppearance({
127
+ variant,
128
+ size,
129
+ width,
130
+ color: resolvedColor,
131
+ border,
132
+ borderRadius,
133
+ align,
134
+ }) }));
135
+ }
136
+ export function MicrosoftButton(props) {
137
+ const internal = props;
138
+ const { action = "login", audience, authenticationChallengeId, recoveryLinkId, onSuccess, onError, onCancel, variant = "text", size = "large", label = action === "login" ? "sign-in" : "continue", mode = "light", border, align = "center", buttonText, width, ...buttonProps } = internal;
139
+ const resolvedMode = useResolvedColorMode(mode);
140
+ const visibleLabel = buttonText ??
141
+ (variant === "provider"
142
+ ? "Microsoft"
143
+ : autharaButtonLabel(label, "Microsoft"));
144
+ return (_jsx(ProviderButton, { ...buttonProps, provider: "microsoft", providerLabel: "Microsoft", action: action, audience: audience, authenticationChallengeId: authenticationChallengeId, recoveryLinkId: recoveryLinkId, onSuccess: onSuccess, onError: onError, onCancel: onCancel, variant: variant, label: visibleLabel, appearance: microsoftButtonAppearance({
145
+ variant,
146
+ size,
147
+ width,
148
+ mode: resolvedMode,
149
+ border,
150
+ align,
151
+ }) }));
152
+ }
153
+ function ProviderIcon({ provider, color, }) {
154
+ if (provider === "google")
155
+ return _jsx(GoogleLogo, {});
156
+ if (provider === "microsoft")
157
+ return _jsx(MicrosoftLogo, {});
158
+ return _jsx(AppleLogo, { color: color });
159
+ }
160
+ function GoogleLogo() {
161
+ return (_jsxs(Svg, { accessibilityElementsHidden: true, width: 18, height: 18, viewBox: "0 0 18 18", children: [_jsx(Path, { fill: "#4285F4", d: "M17.64 9.205c0-.638-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.797 2.715v2.258h2.909c1.702-1.567 2.684-3.875 2.684-6.613Z" }), _jsx(Path, { fill: "#34A853", d: "M9 18c2.43 0 4.468-.806 5.956-2.182l-2.91-2.258c-.805.54-1.835.86-3.046.86-2.344 0-4.328-1.585-5.037-3.714H.956v2.332A9 9 0 0 0 9 18Z" }), _jsx(Path, { fill: "#FBBC05", d: "M3.963 10.706A5.41 5.41 0 0 1 3.682 9c0-.592.102-1.168.281-1.706V4.962H.956A9 9 0 0 0 0 9c0 1.452.347 2.827.956 4.038l3.007-2.332Z" }), _jsx(Path, { fill: "#EA4335", d: "M9 3.58c1.321 0 2.507.454 3.44 1.345l2.581-2.58C13.464.892 11.426 0 9 0A9 9 0 0 0 .956 4.962l3.007 2.332C4.672 5.165 6.656 3.58 9 3.58Z" })] }));
162
+ }
163
+ function AppleLogo({ color }) {
164
+ return (_jsx(Svg, { accessibilityElementsHidden: true, width: 16, height: 20, viewBox: "0 0 814 1000", children: _jsx(Path, { fill: color, d: "M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z" }) }));
165
+ }
166
+ function MicrosoftLogo() {
167
+ return (_jsxs(Svg, { accessibilityElementsHidden: true, width: 18, height: 18, viewBox: "0 0 18 18", children: [_jsx(Rect, { width: 8.5, height: 8.5, fill: "#f25022" }), _jsx(Rect, { x: 9.5, width: 8.5, height: 8.5, fill: "#7fba00" }), _jsx(Rect, { y: 9.5, width: 8.5, height: 8.5, fill: "#00a4ef" }), _jsx(Rect, { x: 9.5, y: 9.5, width: 8.5, height: 8.5, fill: "#ffb900" })] }));
168
+ }
169
+ const styles = StyleSheet.create({
170
+ container: { gap: 7 },
171
+ button: {
172
+ position: "relative",
173
+ minWidth: 0,
174
+ flexDirection: "row",
175
+ alignItems: "center",
176
+ justifyContent: "center",
177
+ gap: 10,
178
+ overflow: "hidden",
179
+ },
180
+ iconSlot: {
181
+ width: 20,
182
+ height: 20,
183
+ alignItems: "center",
184
+ justifyContent: "center",
185
+ },
186
+ label: { fontSize: 14, lineHeight: 20 },
187
+ error: {
188
+ color: "#ff9d8e",
189
+ fontSize: 13,
190
+ lineHeight: 18,
191
+ paddingHorizontal: 4,
192
+ },
193
+ pressed: { opacity: 0.86 },
194
+ disabled: { opacity: 0.62 },
195
+ });
@@ -0,0 +1,65 @@
1
+ import type { AccountRecoveryLink, AuthUser } from "./generated/types.js";
2
+ import type { AutharaTokenStorage } from "./storage.js";
3
+ type QueryValue = string | number | boolean | Array<string | number | boolean>;
4
+ export type AutharaAudience = "app" | "admin" | "operator";
5
+ export type AutharaSessionStatus = "loading" | "authenticated" | "anonymous";
6
+ export interface AutharaSessionSnapshot {
7
+ status: AutharaSessionStatus;
8
+ user: AuthUser | null;
9
+ }
10
+ export interface AutharaErrorDetails {
11
+ error?: {
12
+ code?: string;
13
+ message?: string;
14
+ };
15
+ authentication_challenge?: {
16
+ id: string;
17
+ expires_at: string;
18
+ };
19
+ reauthenticate_url?: string;
20
+ recovery?: AccountRecoveryLink;
21
+ }
22
+ export interface AutharaClientOptions {
23
+ baseUrl: string;
24
+ storage: AutharaTokenStorage;
25
+ audience?: AutharaAudience;
26
+ fetch?: typeof globalThis.fetch;
27
+ }
28
+ export declare class AutharaApiError extends Error {
29
+ readonly status: number;
30
+ readonly code?: string;
31
+ readonly details?: AutharaErrorDetails;
32
+ constructor(status: number, details?: AutharaErrorDetails);
33
+ }
34
+ export declare class AutharaClient {
35
+ private readonly baseUrl;
36
+ private readonly storage;
37
+ private readonly audience;
38
+ private readonly fetchImpl;
39
+ private accessToken;
40
+ private refreshToken;
41
+ private refreshPromise?;
42
+ private snapshot;
43
+ private readonly listeners;
44
+ constructor(options: AutharaClientOptions);
45
+ getSessionSnapshot: () => AutharaSessionSnapshot;
46
+ subscribe: (listener: () => void) => (() => void);
47
+ protected setCurrentUser(user: AuthUser | null): void;
48
+ protected restoreTokens(): Promise<boolean>;
49
+ signOut(): Promise<void>;
50
+ protected request<T>(method: string, path: string, options?: {
51
+ query?: Record<string, QueryValue | undefined>;
52
+ body?: unknown;
53
+ csrf?: boolean;
54
+ authenticated?: boolean;
55
+ }): Promise<T>;
56
+ private rawRequest;
57
+ private refresh;
58
+ private performRefresh;
59
+ private captureTokens;
60
+ private setTokens;
61
+ private clearSession;
62
+ private updateSnapshot;
63
+ private readJSON;
64
+ }
65
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,190 @@
1
+ export class AutharaApiError extends Error {
2
+ status;
3
+ code;
4
+ details;
5
+ constructor(status, details) {
6
+ super(details?.error?.message ?? `Authara request failed (${status})`);
7
+ this.name = "AutharaApiError";
8
+ this.status = status;
9
+ this.code = details?.error?.code;
10
+ this.details = details;
11
+ }
12
+ }
13
+ export class AutharaClient {
14
+ baseUrl;
15
+ storage;
16
+ audience;
17
+ fetchImpl;
18
+ accessToken = null;
19
+ refreshToken = null;
20
+ refreshPromise;
21
+ snapshot = { status: "loading", user: null };
22
+ listeners = new Set();
23
+ constructor(options) {
24
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
25
+ this.storage = options.storage;
26
+ this.audience = options.audience ?? "app";
27
+ const fetchImpl = options.fetch ?? globalThis.fetch;
28
+ if (!fetchImpl)
29
+ throw new Error("Authara requires a fetch implementation");
30
+ this.fetchImpl = fetchImpl;
31
+ }
32
+ getSessionSnapshot = () => this.snapshot;
33
+ subscribe = (listener) => {
34
+ this.listeners.add(listener);
35
+ return () => this.listeners.delete(listener);
36
+ };
37
+ setCurrentUser(user) {
38
+ this.updateSnapshot({
39
+ status: this.refreshToken ? "authenticated" : "anonymous",
40
+ user,
41
+ });
42
+ }
43
+ async restoreTokens() {
44
+ this.refreshToken = await this.storage.getRefreshToken();
45
+ if (!this.refreshToken) {
46
+ this.updateSnapshot({ status: "anonymous", user: null });
47
+ return false;
48
+ }
49
+ const restored = await this.refresh();
50
+ if (!restored && this.snapshot.status === "loading") {
51
+ this.updateSnapshot({ status: "anonymous", user: null });
52
+ }
53
+ return restored;
54
+ }
55
+ async signOut() {
56
+ const refreshToken = this.refreshToken ?? (await this.storage.getRefreshToken());
57
+ try {
58
+ if (refreshToken) {
59
+ await this.rawRequest("POST", "/auth/api/v1/tokens/revoke", {
60
+ body: { refresh_token: refreshToken },
61
+ });
62
+ }
63
+ }
64
+ catch {
65
+ // Local sign-out must still complete while offline.
66
+ }
67
+ finally {
68
+ await this.clearSession();
69
+ }
70
+ }
71
+ async request(method, path, options = {}) {
72
+ const query = { ...options.query };
73
+ if (options.csrf && !options.authenticated)
74
+ query.session_transport = "token";
75
+ let response = await this.rawRequest(method, path, {
76
+ ...options,
77
+ query,
78
+ accessToken: options.authenticated ? this.accessToken : null,
79
+ });
80
+ if (response.status === 401 &&
81
+ options.authenticated &&
82
+ (await this.refresh())) {
83
+ response = await this.rawRequest(method, path, {
84
+ ...options,
85
+ query,
86
+ accessToken: this.accessToken,
87
+ });
88
+ }
89
+ const payload = await this.readJSON(response);
90
+ if (!response.ok)
91
+ throw new AutharaApiError(response.status, payload);
92
+ if (response.status === 204)
93
+ return undefined;
94
+ await this.captureTokens(payload);
95
+ return payload;
96
+ }
97
+ async rawRequest(method, path, options = {}) {
98
+ const query = new URLSearchParams();
99
+ for (const [name, value] of Object.entries(options.query ?? {})) {
100
+ if (value === undefined)
101
+ continue;
102
+ if (Array.isArray(value)) {
103
+ for (const item of value)
104
+ query.append(name, String(item));
105
+ }
106
+ else {
107
+ query.set(name, String(value));
108
+ }
109
+ }
110
+ const queryString = query.toString();
111
+ const url = `${this.baseUrl}${path}${queryString ? `?${queryString}` : ""}`;
112
+ const headers = { Accept: "application/json" };
113
+ if (options.body !== undefined)
114
+ headers["Content-Type"] = "application/json";
115
+ if (options.accessToken)
116
+ headers.Authorization = `Bearer ${options.accessToken}`;
117
+ return this.fetchImpl(url, {
118
+ method,
119
+ headers,
120
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
121
+ });
122
+ }
123
+ async refresh() {
124
+ if (!this.refreshToken)
125
+ return false;
126
+ if (!this.refreshPromise) {
127
+ this.refreshPromise = this.performRefresh().finally(() => {
128
+ this.refreshPromise = undefined;
129
+ });
130
+ }
131
+ return this.refreshPromise;
132
+ }
133
+ async performRefresh() {
134
+ let response;
135
+ try {
136
+ response = await this.rawRequest("POST", "/auth/api/v1/tokens/refresh", {
137
+ body: { refresh_token: this.refreshToken, audience: this.audience },
138
+ });
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ if (response.status === 401) {
144
+ await this.clearSession();
145
+ return false;
146
+ }
147
+ if (!response.ok)
148
+ return false;
149
+ const tokens = (await this.readJSON(response));
150
+ if (!tokens?.access_token || !tokens.refresh_token)
151
+ return false;
152
+ await this.setTokens(tokens.access_token, tokens.refresh_token);
153
+ return true;
154
+ }
155
+ async captureTokens(payload) {
156
+ if (!payload || typeof payload !== "object")
157
+ return;
158
+ const candidate = payload;
159
+ if (!candidate.access_token || !candidate.refresh_token)
160
+ return;
161
+ await this.setTokens(candidate.access_token, candidate.refresh_token);
162
+ if (candidate.user)
163
+ this.setCurrentUser(candidate.user);
164
+ }
165
+ async setTokens(accessToken, refreshToken) {
166
+ this.accessToken = accessToken;
167
+ this.refreshToken = refreshToken;
168
+ await this.storage.setRefreshToken(refreshToken);
169
+ this.updateSnapshot({ status: "authenticated", user: this.snapshot.user });
170
+ }
171
+ async clearSession() {
172
+ this.accessToken = null;
173
+ this.refreshToken = null;
174
+ await this.storage.removeRefreshToken();
175
+ this.updateSnapshot({ status: "anonymous", user: null });
176
+ }
177
+ updateSnapshot(snapshot) {
178
+ this.snapshot = snapshot;
179
+ for (const listener of this.listeners)
180
+ listener();
181
+ }
182
+ async readJSON(response) {
183
+ try {
184
+ return await response.json();
185
+ }
186
+ catch {
187
+ return undefined;
188
+ }
189
+ }
190
+ }
@@ -0,0 +1,12 @@
1
+ import { type PropsWithChildren } from "react";
2
+ import type { AutharaSessionSnapshot } from "./client.js";
3
+ import type { AutharaNativeClient } from "./native-client.js";
4
+ export interface AutharaProviderProps extends PropsWithChildren {
5
+ client: AutharaNativeClient;
6
+ }
7
+ export declare function AutharaProvider({ client, children }: AutharaProviderProps): import("react").JSX.Element;
8
+ export interface UseAutharaResult extends AutharaSessionSnapshot {
9
+ client: AutharaNativeClient;
10
+ signOut(): Promise<void>;
11
+ }
12
+ export declare function useAuthara(): UseAutharaResult;
@@ -0,0 +1,16 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext, useEffect, useMemo, useSyncExternalStore, } from "react";
3
+ const AutharaContext = createContext(null);
4
+ export function AutharaProvider({ client, children }) {
5
+ useEffect(() => {
6
+ void client.restore();
7
+ }, [client]);
8
+ return (_jsx(AutharaContext.Provider, { value: client, children: children }));
9
+ }
10
+ export function useAuthara() {
11
+ const client = useContext(AutharaContext);
12
+ if (!client)
13
+ throw new Error("useAuthara must be used inside AutharaProvider");
14
+ const snapshot = useSyncExternalStore(client.subscribe, client.getSessionSnapshot, client.getSessionSnapshot);
15
+ return useMemo(() => ({ ...snapshot, client, signOut: () => client.signOut() }), [client, snapshot]);
16
+ }
@@ -0,0 +1,2 @@
1
+ import type { AppleNativeAdapter } from "./native-client.js";
2
+ export declare function createExpoAppleAuthentication(): AppleNativeAdapter;
@@ -0,0 +1,38 @@
1
+ import * as AppleAuthentication from "expo-apple-authentication";
2
+ import { AutharaProviderCancellationError } from "./button-error.js";
3
+ export function createExpoAppleAuthentication() {
4
+ return {
5
+ async authorize(options) {
6
+ if (!(await AppleAuthentication.isAvailableAsync())) {
7
+ throw new Error("Sign in with Apple is not available on this device");
8
+ }
9
+ let credential;
10
+ try {
11
+ credential = await AppleAuthentication.signInAsync({
12
+ nonce: options.nonce,
13
+ state: options.state,
14
+ requestedScopes: [
15
+ AppleAuthentication.AppleAuthenticationScope.EMAIL,
16
+ AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
17
+ ],
18
+ });
19
+ }
20
+ catch (error) {
21
+ if (typeof error === "object" &&
22
+ error !== null &&
23
+ "code" in error &&
24
+ error.code === "ERR_REQUEST_CANCELED") {
25
+ throw new AutharaProviderCancellationError("Apple");
26
+ }
27
+ throw error;
28
+ }
29
+ if (!credential.authorizationCode) {
30
+ throw new Error("Apple did not return an authorization code");
31
+ }
32
+ if (credential.state && credential.state !== options.state) {
33
+ throw new Error("Apple returned an unexpected OAuth state");
34
+ }
35
+ return { code: credential.authorizationCode };
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,7 @@
1
+ import type { MicrosoftNativeAdapter } from "./native-client.js";
2
+ export interface ExpoMicrosoftAuthSessionOptions {
3
+ redirectUri?: string;
4
+ scheme?: string;
5
+ path?: string;
6
+ }
7
+ export declare function createExpoMicrosoftAuthSession(config?: ExpoMicrosoftAuthSessionOptions): MicrosoftNativeAdapter;
@@ -0,0 +1,57 @@
1
+ import { AuthRequest, Prompt, ResponseType, exchangeCodeAsync, fetchDiscoveryAsync, makeRedirectUri, } from "expo-auth-session";
2
+ import { AutharaProviderCancellationError } from "./button-error.js";
3
+ export function createExpoMicrosoftAuthSession(config = {}) {
4
+ return {
5
+ async authorize(options) {
6
+ const redirectUri = config.redirectUri ??
7
+ makeRedirectUri({
8
+ scheme: config.scheme,
9
+ path: config.path ?? "microsoft",
10
+ });
11
+ const issuer = `${options.authority.replace(/\/$/, "")}/v2.0`;
12
+ const discovered = await fetchDiscoveryAsync(issuer);
13
+ if (!discovered.authorizationEndpoint || !discovered.tokenEndpoint) {
14
+ throw new Error("Microsoft OpenID discovery is incomplete");
15
+ }
16
+ const discovery = {
17
+ authorizationEndpoint: discovered.authorizationEndpoint,
18
+ tokenEndpoint: discovered.tokenEndpoint,
19
+ };
20
+ const scopes = ["openid", "profile", "email"];
21
+ const request = new AuthRequest({
22
+ clientId: options.client_id,
23
+ redirectUri,
24
+ responseType: ResponseType.Code,
25
+ scopes,
26
+ prompt: Prompt.SelectAccount,
27
+ usePKCE: true,
28
+ extraParams: { nonce: options.nonce },
29
+ });
30
+ const result = await request.promptAsync(discovery, {
31
+ preferEphemeralSession: true,
32
+ });
33
+ if (result.type !== "success") {
34
+ if (result.type === "cancel" || result.type === "dismiss") {
35
+ throw new AutharaProviderCancellationError("Microsoft");
36
+ }
37
+ const message = result.type === "error" ? result.error?.description : undefined;
38
+ throw new Error(message ?? "Microsoft sign-in failed");
39
+ }
40
+ const code = result.params.code;
41
+ if (!code || !request.codeVerifier) {
42
+ throw new Error("Microsoft did not return a usable authorization code");
43
+ }
44
+ const tokens = await exchangeCodeAsync({
45
+ clientId: options.client_id,
46
+ code,
47
+ redirectUri,
48
+ scopes,
49
+ extraParams: { code_verifier: request.codeVerifier },
50
+ }, discovery);
51
+ if (!tokens.idToken) {
52
+ throw new Error("Microsoft did not return an ID token");
53
+ }
54
+ return { credential: tokens.idToken };
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,6 @@
1
+ import * as SecureStore from "expo-secure-store";
2
+ import type { AutharaTokenStorage } from "./storage.js";
3
+ export interface ExpoSecureStoreOptions extends SecureStore.SecureStoreOptions {
4
+ key?: string;
5
+ }
6
+ export declare function createExpoSecureStore(options?: ExpoSecureStoreOptions): AutharaTokenStorage;
@@ -0,0 +1,9 @@
1
+ import * as SecureStore from "expo-secure-store";
2
+ export function createExpoSecureStore(options = {}) {
3
+ const { key = "authara.refresh-token", ...secureStoreOptions } = options;
4
+ return {
5
+ getRefreshToken: () => SecureStore.getItemAsync(key, secureStoreOptions),
6
+ setRefreshToken: (token) => SecureStore.setItemAsync(key, token, secureStoreOptions),
7
+ removeRefreshToken: () => SecureStore.deleteItemAsync(key, secureStoreOptions),
8
+ };
9
+ }