@smartcrab/react-native 0.3.2 → 0.4.0-next-20261016193833

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/src/errors.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { AdaptiveChallengeAction } from "@smartcrab/contracts-public";
2
+
1
3
  import type { OAuthErrorCode } from "@smartcrab/contracts-public";
2
4
 
3
5
  /**
@@ -44,6 +46,14 @@ export interface ProblemDetailsError {
44
46
  readonly detail?: string;
45
47
  readonly requestId?: string;
46
48
  }
49
+ export interface AdaptiveChallengeRequiredError {
50
+ readonly type: "adaptive_challenge_required";
51
+ readonly challengeId: string;
52
+ readonly siteKey: string;
53
+ readonly action: AdaptiveChallengeAction;
54
+ readonly transactionId: string;
55
+ readonly requestId?: string;
56
+ }
47
57
 
48
58
  export interface OAuthFailureError {
49
59
  readonly type: "oauth_error";
@@ -99,12 +109,17 @@ export interface InvalidFlowStateError {
99
109
  export interface NotConfiguredError {
100
110
  readonly type: "not_configured";
101
111
  }
112
+ export interface SecureStorageError {
113
+ readonly type: "secure_storage_error";
114
+ readonly message: string;
115
+ }
102
116
 
103
117
  export type ReactNativeAuthError =
104
118
  | NetworkFailureError
105
119
  | InvalidResponseError
106
120
  | RateLimitedError
107
121
  | ProblemDetailsError
122
+ | AdaptiveChallengeRequiredError
108
123
  | OAuthFailureError
109
124
  | StateMismatchError
110
125
  | NotAuthenticatedError
@@ -112,6 +127,7 @@ export type ReactNativeAuthError =
112
127
  | PasskeyOperationError
113
128
  | SocialCancelledError
114
129
  | InvalidFlowStateError
130
+ | SecureStorageError
115
131
  | NotConfiguredError;
116
132
 
117
133
  /**
@@ -141,6 +157,8 @@ const describeReactNativeAuthError = (error: ReactNativeAuthError): string => {
141
157
  return "Rate limited";
142
158
  case "problem_details":
143
159
  return `${error.code}: ${error.title}`;
160
+ case "adaptive_challenge_required":
161
+ return "An interactive challenge is required before this request can continue";
144
162
  case "oauth_error":
145
163
  return `OAuth error: ${error.code}`;
146
164
  case "state_mismatch":
@@ -155,6 +173,8 @@ const describeReactNativeAuthError = (error: ReactNativeAuthError): string => {
155
173
  return "Social sign-in was cancelled";
156
174
  case "invalid_flow_state":
157
175
  return error.message;
176
+ case "secure_storage_error":
177
+ return `Secure storage failed: ${error.message}`;
158
178
  case "not_configured":
159
179
  return "configure() must be called before using the auth client";
160
180
  }
package/src/hooks.ts CHANGED
@@ -182,7 +182,7 @@ export interface UsePasskeyResult {
182
182
  readonly isLoading: boolean;
183
183
  readonly error: ReactNativeAuthClientError | null;
184
184
  readonly reload: () => Promise<Passkey[]>;
185
- readonly signIn: () => Promise<AuthResult>;
185
+ readonly signIn: (input?: { challengeToken?: string }) => Promise<AuthResult>;
186
186
  readonly register: (input?: RegisterPasskeyInput) => Promise<Passkey>;
187
187
  readonly remove: (passkeyId: string) => Promise<void>;
188
188
  }
@@ -245,7 +245,8 @@ export const usePasskey = (): UsePasskeyResult => {
245
245
  );
246
246
 
247
247
  const signIn = useCallback(
248
- (): Promise<AuthResult> => ceremony(client.signInWithPasskey()),
248
+ (input?: { challengeToken?: string }): Promise<AuthResult> =>
249
+ ceremony(client.signInWithPasskey(input)),
249
250
  [client, ceremony],
250
251
  );
251
252
 
@@ -277,7 +278,14 @@ export const usePasskey = (): UsePasskeyResult => {
277
278
  // ---------------------------------------------------------------------------
278
279
 
279
280
  export interface UseEmailOtpResult {
280
- readonly sendCode: (email: string) => Promise<EmailCodeChallenge>;
281
+ readonly sendCode: (
282
+ email: string,
283
+ input?: { challengeToken?: string },
284
+ ) => Promise<EmailCodeChallenge>;
285
+ readonly resendCode: (
286
+ challengeId: string,
287
+ input?: { challengeToken?: string },
288
+ ) => Promise<EmailCodeChallenge>;
281
289
  readonly verifyCode: (input: { challengeId: string; code: string }) => Promise<AuthResult>;
282
290
  }
283
291
 
@@ -286,7 +294,10 @@ export const useEmailOtp = (): UseEmailOtpResult => {
286
294
  const client = useAuthClient();
287
295
  return useMemo<UseEmailOtpResult>(
288
296
  () => ({
289
- sendCode: (email: string) => client.sendEmailCode({ email }),
297
+ sendCode: (email: string, input?: { challengeToken?: string }) =>
298
+ client.sendEmailCode({ email, ...input }),
299
+ resendCode: (challengeId: string, input?: { challengeToken?: string }) =>
300
+ client.resendEmailCode({ challengeId, ...input }),
290
301
  verifyCode: (input) => client.verifyEmailCode(input),
291
302
  }),
292
303
  [client],
@@ -298,7 +309,10 @@ export const useEmailOtp = (): UseEmailOtpResult => {
298
309
  // ---------------------------------------------------------------------------
299
310
 
300
311
  export interface UseSocialSignInResult {
301
- readonly signIn: (provider: SocialProvider) => Promise<AuthResult>;
312
+ readonly signIn: (
313
+ provider: SocialProvider,
314
+ input?: { challengeToken?: string },
315
+ ) => Promise<AuthResult>;
302
316
  readonly link: (provider: SocialProvider) => Promise<void>;
303
317
  }
304
318
 
@@ -307,7 +321,8 @@ export const useSocialSignIn = (): UseSocialSignInResult => {
307
321
  const client = useAuthClient();
308
322
  return useMemo<UseSocialSignInResult>(
309
323
  () => ({
310
- signIn: (provider: SocialProvider) => client.signInWithSocial({ provider }),
324
+ signIn: (provider: SocialProvider, input?: { challengeToken?: string }) =>
325
+ client.signInWithSocial({ provider, ...input }),
311
326
  link: (provider: SocialProvider) => client.linkSocialAccount({ provider }),
312
327
  }),
313
328
  [client],
package/src/http.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { adaptiveChallengeRequiredResponseSchema } from "@smartcrab/contracts-public";
2
+
1
3
  import type { Outcome } from "@smartcrab/contracts-public";
2
4
  import { OAUTH_ERROR_CODES, err, ok } from "@smartcrab/contracts-public";
3
5
  import type { OAuthErrorCode } from "@smartcrab/contracts-public";
@@ -30,6 +32,7 @@ export interface JsonRequest {
30
32
  readonly body?: unknown;
31
33
  readonly accessToken?: string;
32
34
  readonly transactionSecret?: string;
35
+ readonly idempotencyKey?: string;
33
36
  }
34
37
 
35
38
  const OAUTH_ERROR_CODE_SET: ReadonlySet<string> = new Set(OAUTH_ERROR_CODES);
@@ -90,6 +93,7 @@ export const requestJson = async <T>(
90
93
  ...(request.transactionSecret !== undefined
91
94
  ? { "x-transaction-secret": request.transactionSecret }
92
95
  : {}),
96
+ ...(request.idempotencyKey !== undefined ? { "Idempotency-Key": request.idempotencyKey } : {}),
93
97
  };
94
98
 
95
99
  const responseOutcome = await fetchPort(request.url, {
@@ -125,6 +129,19 @@ export const requestJson = async <T>(
125
129
  }
126
130
 
127
131
  if (!response.ok) {
132
+ const adaptiveChallenge = adaptiveChallengeRequiredResponseSchema.safeParse(json);
133
+ if (adaptiveChallenge.success) {
134
+ return err({
135
+ type: "adaptive_challenge_required",
136
+ challengeId: adaptiveChallenge.data.challenge_id,
137
+ siteKey: adaptiveChallenge.data.site_key,
138
+ action: adaptiveChallenge.data.action,
139
+ transactionId: adaptiveChallenge.data.transaction_id,
140
+ ...(adaptiveChallenge.data.request_id !== undefined
141
+ ? { requestId: adaptiveChallenge.data.request_id }
142
+ : {}),
143
+ });
144
+ }
128
145
  const problem = parseProblemDetailsWire(json);
129
146
  if (problem !== null) {
130
147
  return err({
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ export type {
37
37
  ReactNativeAuthConfig,
38
38
  RegisterPasskeyInput,
39
39
  UpdateUserProfileInput,
40
+ RecoveryCompletionInput,
40
41
  UserProfile,
41
42
  } from "./types.js";
42
43
  /**
@@ -45,7 +46,13 @@ export type {
45
46
  * name the exact type `signInWithSocial`/`linkSocialAccount` take, without
46
47
  * needing their own dependency on contracts-public.
47
48
  */
48
- export type { SocialProvider } from "@smartcrab/contracts-public";
49
+ export type {
50
+ AdaptiveChallengeAction,
51
+ MeIdentityLinkCompleteResponse,
52
+ MeRecoveryCompleteResponse,
53
+ SocialProvider,
54
+ } from "@smartcrab/contracts-public";
55
+ export type { AdaptiveChallengeRequiredError, SecureStorageError } from "./errors.js";
49
56
 
50
57
  export { ReactNativeAuthClientError } from "./errors.js";
51
58
  export type {
@@ -12,6 +12,9 @@
12
12
  * OTP codes. The access token lives in the client's in-memory closure only
13
13
  * (`client.ts`); nothing in this module ever touches it.
14
14
  */
15
+ import type { ClientId, SocialProvider } from "@smartcrab/contracts-public";
16
+ import { socialProviderSchema } from "@smartcrab/contracts-public";
17
+
15
18
  export interface SecureStorePort {
16
19
  getItemAsync(key: string): Promise<string | null>;
17
20
  setItemAsync(key: string, value: string): Promise<void>;
@@ -34,6 +37,10 @@ export const refreshRecordKey = (environmentId: string, clientId: string): strin
34
37
  export const pendingTransactionKey = (environmentId: string, clientId: string): string =>
35
38
  secureStoreKey(environmentId, clientId, "pkce");
36
39
 
40
+ /** App-held identity-link PKCE state is separate from sign-in transactions. */
41
+ export const pendingIdentityLinkKey = (environmentId: string, clientId: string): string =>
42
+ secureStoreKey(environmentId, clientId, "identity-link");
43
+
37
44
  /** Minimal session metadata persisted alongside the refresh token (design.md §21.6). */
38
45
  export interface PersistedRefreshRecord {
39
46
  readonly refreshToken: string;
@@ -65,6 +72,17 @@ export interface PersistedPendingTransaction {
65
72
  readonly challengeId?: string;
66
73
  }
67
74
 
75
+ /** Pending app-held identity-link material, stored only in SecureStore. */
76
+ export interface PersistedPendingIdentityLink {
77
+ readonly provider: SocialProvider;
78
+ readonly state: string;
79
+ readonly codeVerifier: string;
80
+ readonly redirectUri: string;
81
+ readonly clientId: ClientId;
82
+ readonly userId: string;
83
+ readonly createdAt: number;
84
+ }
85
+
68
86
  const isRecord = (value: unknown): value is Record<string, unknown> =>
69
87
  typeof value === "object" && value !== null && !Array.isArray(value);
70
88
 
@@ -111,3 +129,27 @@ export const parsePersistedPendingTransaction = (
111
129
  ...(challengeId !== undefined ? { challengeId } : {}),
112
130
  };
113
131
  };
132
+
133
+ export const parsePersistedPendingIdentityLink = (
134
+ value: unknown,
135
+ ): PersistedPendingIdentityLink | null => {
136
+ if (!isRecord(value)) return null;
137
+ const { provider, state, codeVerifier, redirectUri, clientId, userId, createdAt } = value;
138
+ const parsedProvider = socialProviderSchema.safeParse(provider);
139
+ if (!parsedProvider.success) return null;
140
+ if (typeof state !== "string" || state.length === 0) return null;
141
+ if (typeof codeVerifier !== "string" || codeVerifier.length === 0) return null;
142
+ if (typeof redirectUri !== "string" || redirectUri.length === 0) return null;
143
+ if (typeof clientId !== "string" || clientId.length === 0) return null;
144
+ if (typeof userId !== "string" || userId.length === 0) return null;
145
+ if (typeof createdAt !== "number" || !Number.isFinite(createdAt)) return null;
146
+ return {
147
+ provider: parsedProvider.data,
148
+ state,
149
+ codeVerifier,
150
+ redirectUri,
151
+ clientId,
152
+ userId,
153
+ createdAt,
154
+ };
155
+ };
package/src/types.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { ClientId, SocialProvider } from "@smartcrab/contracts-public";
2
+ import type { MeRecoveryCompleteResponse } from "@smartcrab/contracts-public";
3
+
2
4
  import type { WebBrowserPort } from "./browser-port.js";
3
5
  import type { CryptoPort } from "./crypto-port.js";
4
6
  import type { FetchPort } from "./http.js";
@@ -112,6 +114,10 @@ export interface RegisterPasskeyInput {
112
114
  readonly name?: string;
113
115
  }
114
116
 
117
+ export interface RecoveryCompletionInput {
118
+ readonly idempotencyKey: string;
119
+ }
120
+
115
121
  export interface AuthStateSnapshot {
116
122
  readonly status: "signed_out" | "signed_in";
117
123
  /** Runtime WebAuthn capability (design.md §21.2): the prebuilt UI hides `<PasskeyButton/>` when false. */
@@ -160,12 +166,20 @@ export interface ReactNativeAuthClient {
160
166
  configure(config: ReactNativeAuthConfig): void;
161
167
  getSession(): Promise<AuthSession | null>;
162
168
  getAccessToken(input?: AccessTokenRequest): Promise<string>;
163
- signInWithPasskey(): Promise<AuthResult>;
169
+ signInWithPasskey(input?: { challengeToken?: string }): Promise<AuthResult>;
164
170
  registerPasskey(input?: RegisterPasskeyInput): Promise<Passkey>;
165
- sendEmailCode(input: { email: string }): Promise<EmailCodeChallenge>;
171
+ sendEmailCode(input: { email: string; challengeToken?: string }): Promise<EmailCodeChallenge>;
172
+ resendEmailCode(input: {
173
+ challengeId: string;
174
+ challengeToken?: string;
175
+ }): Promise<EmailCodeChallenge>;
166
176
  verifyEmailCode(input: { challengeId: string; code: string }): Promise<AuthResult>;
167
- signInWithSocial(input: { provider: SocialProvider }): Promise<AuthResult>;
177
+ signInWithSocial(input: {
178
+ provider: SocialProvider;
179
+ challengeToken?: string;
180
+ }): Promise<AuthResult>;
168
181
  linkSocialAccount(input: { provider: SocialProvider }): Promise<void>;
182
+ completeRecovery(input: RecoveryCompletionInput): Promise<MeRecoveryCompleteResponse>;
169
183
  listPasskeys(): Promise<Passkey[]>;
170
184
  deletePasskey(passkeyId: string): Promise<void>;
171
185
  listSessions(): Promise<DeviceSession[]>;