@rakomi/react-native 0.1.0 → 0.2.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { createContext, useMemo, useReducer, useEffect, useRef, useState, useContext } from 'react';
2
- import { EventLog, reduce, INITIAL_SNAPSHOT, createTranslator, isSignedIn, hasPermission, hasRole, generatePkce, issueState, buildAuthorizationUrl, consumeState, exchangeAuthCode, parseOAuthCallbackError, scorePassword, isSafeUrl, verifyMagicLink, requestMagicLink, verifyEmailOtp, requestEmailOtp, register, verifyTotp, MfaStepUpUnavailableError, decodeUser, decodeSession, deriveTenantStorageKey, createJwksCache, refreshAccessToken } from '@rakomi/sdk-core';
1
+ import { createContext, useMemo, useReducer, useRef, useEffect, useState, useCallback, useContext } from 'react';
2
+ import { EventLog, reduce, INITIAL_SNAPSHOT, createTranslator, isSignedIn, hasPermission, hasRole, extractOrgClaims, parseAuthConfigResponse, generatePkce, issueState, buildAuthorizationUrl, consumeState, exchangeAuthCode, parseOAuthCallbackError, scorePassword, isSafeUrl, passkeyError, decodeUser, assertPasskey, stepUpWithPasskey, registerPasskey, listPasskeys, renamePasskey, deletePasskey, verifyMagicLink, requestMagicLink, verifyEmailOtp, requestEmailOtp, register, verifyTotp, MfaStepUpUnavailableError, decodeSession, deriveTenantStorageKey, createJwksCache, refreshAccessToken, decodeJwtPayload, PasskeyCeremonyError } from '@rakomi/sdk-core';
3
3
  export { MfaStepUpRequiredError, MfaStepUpUnavailableError, base64url, createTranslator, decodeJwtPayload, decodeSession, decodeUser, generatePkce, getErrorMessage, hasPermission, hasRole, isSafeUrl, networkError, parseOAuthCallbackError, parseTokenEndpointError, scorePassword, selectPluralForm } from '@rakomi/sdk-core';
4
4
  import { jwtVerify } from 'jose';
5
5
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
@@ -11,6 +11,24 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
11
11
  throw Error('Dynamic require of "' + x + '" is not supported');
12
12
  });
13
13
 
14
+ // src/internal/ceremony-lock.ts
15
+ function createCeremonyLock() {
16
+ let held = false;
17
+ return {
18
+ tryAcquire() {
19
+ if (held) return false;
20
+ held = true;
21
+ return true;
22
+ },
23
+ release() {
24
+ held = false;
25
+ },
26
+ get held() {
27
+ return held;
28
+ }
29
+ };
30
+ }
31
+
14
32
  // src/internal/canonical-url.ts
15
33
  var CanonicalizeUrlError = class extends Error {
16
34
  constructor(code, message) {
@@ -116,6 +134,37 @@ function createDpopSession(options) {
116
134
  return new DpopSession(options);
117
135
  }
118
136
 
137
+ // src/internal/compose-signals.ts
138
+ function composeSignals(caller, internal) {
139
+ if (caller === void 0) {
140
+ return { signal: internal, dispose: () => void 0 };
141
+ }
142
+ const controller = new AbortController();
143
+ const abort = (reason) => {
144
+ if (!controller.signal.aborted) controller.abort(reason);
145
+ };
146
+ const onCaller = () => abort(caller.reason);
147
+ const onInternal = () => abort(internal.reason);
148
+ if (caller.aborted) {
149
+ abort(caller.reason);
150
+ } else if (internal.aborted) {
151
+ abort(internal.reason);
152
+ } else {
153
+ caller.addEventListener("abort", onCaller, { once: true });
154
+ internal.addEventListener("abort", onInternal, { once: true });
155
+ }
156
+ let disposed = false;
157
+ return {
158
+ signal: controller.signal,
159
+ dispose: () => {
160
+ if (disposed) return;
161
+ disposed = true;
162
+ caller.removeEventListener("abort", onCaller);
163
+ internal.removeEventListener("abort", onInternal);
164
+ }
165
+ };
166
+ }
167
+
119
168
  // src/internal/http-client.ts
120
169
  function createRnHttpClient(options = {}) {
121
170
  const baseUrl = options.baseUrl?.replace(/\/$/, "") ?? "";
@@ -124,18 +173,41 @@ function createRnHttpClient(options = {}) {
124
173
  fetch: async (url, init = {}) => {
125
174
  const fullUrl = url.startsWith("http://") || url.startsWith("https://") ? url : `${baseUrl}${url.startsWith("/") ? "" : "/"}${url}`;
126
175
  const controller = new AbortController();
127
- const timer = setTimeout(() => controller.abort(), timeout);
176
+ const timedOut = Object.assign(new Error("request timed out"), { name: "TimeoutError" });
177
+ const timer = setTimeout(() => controller.abort(timedOut), timeout);
178
+ const composed = composeSignals(init.signal, controller.signal);
179
+ let response;
128
180
  try {
129
- return await fetch(fullUrl, {
181
+ response = await fetch(fullUrl, {
130
182
  method: init.method ?? "GET",
131
183
  headers: init.headers,
132
184
  body: init.body,
133
185
  redirect: "error",
134
- signal: init.signal ?? controller.signal
186
+ signal: composed.signal
135
187
  });
136
- } finally {
188
+ } catch (err2) {
137
189
  clearTimeout(timer);
190
+ composed.dispose();
191
+ throw err2;
192
+ }
193
+ clearTimeout(timer);
194
+ const body = response.body;
195
+ const streaming = body !== null && body !== void 0 && typeof body.pipeThrough === "function" && typeof TransformStream !== "undefined";
196
+ if (!streaming) {
197
+ composed.dispose();
198
+ return response;
138
199
  }
200
+ const release = new TransformStream({
201
+ flush: () => composed.dispose()
202
+ });
203
+ const piped = body.pipeThrough(release);
204
+ const wrapped = new Response(piped, {
205
+ status: response.status,
206
+ statusText: response.statusText,
207
+ headers: response.headers
208
+ });
209
+ composed.signal.addEventListener("abort", () => composed.dispose(), { once: true });
210
+ return wrapped;
139
211
  }
140
212
  };
141
213
  }
@@ -224,8 +296,8 @@ function deriveDefaultJwksUri(tokenEndpoint) {
224
296
  return tokenEndpoint.replace(/\/[^/]*$/, "") + "/.well-known/jwks.json";
225
297
  }
226
298
  }
227
- var RAKOMI_PLATFORM_ISSUER_DEFAULT = "https://rakomi.com";
228
- var RAKOMI_PLATFORM_AUDIENCE_DEFAULT = "https://rakomi.com";
299
+ var RAKOMI_PLATFORM_ISSUER_DEFAULT = "https://api.rakomi.com";
300
+ var RAKOMI_PLATFORM_AUDIENCE_DEFAULT = "https://api.rakomi.com";
229
301
  function deriveDefaultIssuer(_tokenEndpoint) {
230
302
  return RAKOMI_PLATFORM_ISSUER_DEFAULT;
231
303
  }
@@ -942,6 +1014,7 @@ function RakomiProvider(props) {
942
1014
  const http = useMemo(() => createRnHttpClient({ baseUrl: props.baseUrl }), [props.baseUrl]);
943
1015
  const events = useMemo(() => new EventLog(props.onEvent), [props.onEvent]);
944
1016
  const [snapshot, dispatch] = useReducer(reduce, INITIAL_SNAPSHOT);
1017
+ const passkeyCeremonyLock = useRef(createCeremonyLock()).current;
945
1018
  const translate = useMemo(
946
1019
  () => createTranslator(props.locale ?? "en", props.translations),
947
1020
  [props.locale, props.translations]
@@ -1085,10 +1158,11 @@ function RakomiProvider(props) {
1085
1158
  signOut,
1086
1159
  getToken,
1087
1160
  submitOAuthTokens,
1161
+ passkeyCeremonyLock,
1088
1162
  beginAuthFlow,
1089
1163
  dpopSession
1090
1164
  }),
1091
- [adapter, http, snapshot, events, props.publishableKey, props.baseUrl, props.redirectUri, props.locale, translate, signOut, getToken, submitOAuthTokens, beginAuthFlow, dpopSession]
1165
+ [adapter, http, snapshot, events, props.publishableKey, props.baseUrl, props.redirectUri, props.locale, translate, signOut, getToken, submitOAuthTokens, beginAuthFlow, dpopSession, passkeyCeremonyLock]
1092
1166
  );
1093
1167
  return /* @__PURE__ */ jsx(RakomiContext.Provider, { value, children: props.children });
1094
1168
  }
@@ -1202,19 +1276,20 @@ function useFlag(flag, options) {
1202
1276
  }
1203
1277
  function useOrganization() {
1204
1278
  const { user } = useRakomiContext();
1205
- const orgId = user?.rawClaims["org_id"];
1206
- const orgRole = user?.rawClaims["org_role"];
1207
- const orgMemberships = user?.rawClaims["org_memberships"] ?? [];
1279
+ const { org_id: orgId, org_role: orgRole, org_memberships: orgMemberships } = extractOrgClaims(
1280
+ user?.rawClaims ?? {}
1281
+ );
1208
1282
  return {
1209
1283
  isLoaded: !!user,
1210
- organization: orgId && orgRole ? { orgId, orgRole, orgMemberships } : null
1284
+ organization: orgId && orgRole ? { orgId, orgRole, orgMemberships: orgMemberships ?? [] } : null
1211
1285
  };
1212
1286
  }
1213
1287
  function useOrganizationList() {
1214
1288
  const { user } = useRakomiContext();
1289
+ const { org_memberships: organizations } = extractOrgClaims(user?.rawClaims ?? {});
1215
1290
  return {
1216
1291
  isLoaded: !!user,
1217
- organizations: user?.rawClaims["org_memberships"] ?? []
1292
+ organizations: organizations ?? []
1218
1293
  };
1219
1294
  }
1220
1295
  function useLinkedAccounts() {
@@ -1248,7 +1323,8 @@ function useAuthConfig() {
1248
1323
  headers: { Accept: "application/json", "X-API-Key": publishableKey }
1249
1324
  });
1250
1325
  if (!response.ok) return null;
1251
- return await response.json();
1326
+ const raw = await response.json();
1327
+ return parseAuthConfigResponse(raw, baseUrl);
1252
1328
  } catch {
1253
1329
  return null;
1254
1330
  }
@@ -1804,6 +1880,264 @@ function createNativeDpopProver(options) {
1804
1880
  };
1805
1881
  }
1806
1882
 
1883
+ // src/native/passkey-envelope.ts
1884
+ var BASE64URL = /^[A-Za-z0-9_-]+$/;
1885
+ var RULES = {
1886
+ registration: {
1887
+ required: ["id", "rawId", "response.clientDataJSON", "response.attestationObject"],
1888
+ base64url: ["id", "rawId", "response.clientDataJSON", "response.attestationObject"],
1889
+ requiredStringArray: ["response.transports"],
1890
+ requiredObject: ["clientExtensionResults"],
1891
+ keep: ["id", "rawId", "type", "authenticatorAttachment", "clientExtensionResults"],
1892
+ keepInResponse: [
1893
+ "clientDataJSON",
1894
+ "attestationObject",
1895
+ "authenticatorData",
1896
+ "publicKey",
1897
+ "publicKeyAlgorithm"
1898
+ ],
1899
+ keepStringArrayInResponse: ["transports"]
1900
+ },
1901
+ assertion: {
1902
+ required: [
1903
+ "id",
1904
+ "rawId",
1905
+ "response.clientDataJSON",
1906
+ "response.authenticatorData",
1907
+ "response.signature"
1908
+ ],
1909
+ base64url: [
1910
+ "id",
1911
+ "rawId",
1912
+ "response.clientDataJSON",
1913
+ "response.authenticatorData",
1914
+ "response.signature",
1915
+ "response.userHandle"
1916
+ ],
1917
+ requiredStringArray: [],
1918
+ requiredObject: ["clientExtensionResults"],
1919
+ keep: ["id", "rawId", "type", "authenticatorAttachment", "clientExtensionResults"],
1920
+ keepInResponse: ["clientDataJSON", "authenticatorData", "signature", "userHandle"],
1921
+ keepStringArrayInResponse: []
1922
+ }
1923
+ };
1924
+ var CredentialEnvelopeError = class extends Error {
1925
+ constructor(message) {
1926
+ super(message);
1927
+ this.name = "CredentialEnvelopeError";
1928
+ }
1929
+ };
1930
+ function isRecord(value) {
1931
+ return typeof value === "object" && value !== null;
1932
+ }
1933
+ function readPath(envelope, path) {
1934
+ const dot = path.indexOf(".");
1935
+ if (dot === -1) return envelope[path];
1936
+ const parent = envelope[path.slice(0, dot)];
1937
+ return isRecord(parent) ? parent[path.slice(dot + 1)] : void 0;
1938
+ }
1939
+ function assertW3cCredentialEnvelope(kind, parsed) {
1940
+ if (!isRecord(parsed)) {
1941
+ throw new CredentialEnvelopeError(
1942
+ `the native module returned a ${parsed === null ? "null" : typeof parsed}; the contract is a JSON object`
1943
+ );
1944
+ }
1945
+ if (parsed["type"] !== "public-key") {
1946
+ throw new CredentialEnvelopeError(`'type' must be the string "public-key" (W3C WebAuthn L3)`);
1947
+ }
1948
+ if (!isRecord(parsed["response"])) {
1949
+ throw new CredentialEnvelopeError(`'response' is missing or is not an object`);
1950
+ }
1951
+ const rule = RULES[kind];
1952
+ for (const path of rule.required) {
1953
+ const value = readPath(parsed, path);
1954
+ if (typeof value !== "string" || value.length === 0) {
1955
+ throw new CredentialEnvelopeError(
1956
+ `'${path}' is required on a ${kind} response and must be a non-empty string (W3C WebAuthn L3 JSON serialization)`
1957
+ );
1958
+ }
1959
+ }
1960
+ for (const path of rule.requiredStringArray) {
1961
+ const value = readPath(parsed, path);
1962
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
1963
+ throw new CredentialEnvelopeError(
1964
+ `'${path}' is required on a ${kind} response and must be an array of strings (W3C WebAuthn L3). The server stores it and replays it into allowCredentials \u2014 omitting it silently breaks cross-device sign-in later, on another device.`
1965
+ );
1966
+ }
1967
+ }
1968
+ for (const path of rule.requiredObject) {
1969
+ const value = readPath(parsed, path);
1970
+ if (!isRecord(value)) {
1971
+ throw new CredentialEnvelopeError(
1972
+ `'${path}' is required on a ${kind} response and must be an object (an empty object is fine)`
1973
+ );
1974
+ }
1975
+ }
1976
+ for (const path of rule.base64url) {
1977
+ const value = readPath(parsed, path);
1978
+ if (value === void 0 || value === null) continue;
1979
+ if (typeof value !== "string" || !BASE64URL.test(value)) {
1980
+ throw new CredentialEnvelopeError(
1981
+ `'${path}' is not unpadded base64url (RFC 4648 \xA75). On iOS, Data.base64EncodedString() emits standard base64 (RFC 4648 \xA74, with '+', '/' and '=' padding) \u2014 use the URL-safe, unpadded variant.`
1982
+ );
1983
+ }
1984
+ }
1985
+ }
1986
+ function sanitizeCredentialEnvelope(kind, parsed) {
1987
+ assertW3cCredentialEnvelope(kind, parsed);
1988
+ const envelope = parsed;
1989
+ const source = envelope["response"];
1990
+ const rule = RULES[kind];
1991
+ const response = /* @__PURE__ */ Object.create(null);
1992
+ for (const key of rule.keepInResponse) {
1993
+ const value = source[key];
1994
+ if (typeof value === "string" || typeof value === "number") response[key] = value;
1995
+ }
1996
+ for (const key of rule.keepStringArrayInResponse) {
1997
+ const value = source[key];
1998
+ if (Array.isArray(value)) response[key] = value.filter((entry) => typeof entry === "string");
1999
+ }
2000
+ const projected = /* @__PURE__ */ Object.create(null);
2001
+ for (const key of rule.keep) {
2002
+ const value = envelope[key];
2003
+ if (value !== void 0) projected[key] = value;
2004
+ }
2005
+ projected["response"] = response;
2006
+ return projected;
2007
+ }
2008
+
2009
+ // src/native/passkey-adapter.ts
2010
+ var NATIVE_CODE_TO_KIND = Object.assign(/* @__PURE__ */ Object.create(null), {
2011
+ PASSKEY_CANCELLED: "cancelled",
2012
+ PASSKEY_UNSUPPORTED: "unsupported",
2013
+ PASSKEY_NO_CREDENTIAL: "cancelled"
2014
+ });
2015
+ function isRecord2(value) {
2016
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2017
+ }
2018
+ function normalizeNativeRejection(err2) {
2019
+ const code = isRecord2(err2) ? err2["code"] : void 0;
2020
+ if (typeof code === "string") {
2021
+ const kind = NATIVE_CODE_TO_KIND[code];
2022
+ if (kind !== void 0) {
2023
+ throw new PasskeyCeremonyError(kind);
2024
+ }
2025
+ }
2026
+ throw err2;
2027
+ }
2028
+ function assertNever(value) {
2029
+ throw new PasskeyCeremonyError("failed", `unhandled ceremony-error kind: ${String(value)}`);
2030
+ }
2031
+ function describeKind(kind) {
2032
+ switch (kind) {
2033
+ case "cancelled":
2034
+ return "the user dismissed the passkey sheet";
2035
+ case "unsupported":
2036
+ return "this platform cannot run a passkey ceremony";
2037
+ case "failed":
2038
+ return "the passkey ceremony failed";
2039
+ default:
2040
+ return assertNever(kind);
2041
+ }
2042
+ }
2043
+ function createNativePasskeyAdapter(options) {
2044
+ const mod = options.module;
2045
+ let inFlight = null;
2046
+ const candidate = mod;
2047
+ const missing = ["isPasskeySupported", "createPasskey", "getPasskey"].filter(
2048
+ (method) => typeof candidate?.[method] !== "function"
2049
+ );
2050
+ if (missing.length > 0) {
2051
+ throw new Error(
2052
+ `native passkey module is missing: ${missing.join(", ")} \u2014 it does not satisfy NativePasskeyModuleSpec`
2053
+ );
2054
+ }
2055
+ async function runCeremony(kind, requestJson, ceremonyOptions) {
2056
+ const signal = ceremonyOptions?.signal;
2057
+ if (signal?.aborted === true) {
2058
+ throw new PasskeyCeremonyError("cancelled", describeKind("cancelled"));
2059
+ }
2060
+ const ticket = /* @__PURE__ */ Symbol("passkey-ceremony");
2061
+ inFlight = ticket;
2062
+ const onAbort = () => {
2063
+ if (inFlight !== ticket) return;
2064
+ try {
2065
+ void Promise.resolve(mod.cancelPasskeyRequest?.()).catch(() => void 0);
2066
+ } catch {
2067
+ }
2068
+ };
2069
+ signal?.addEventListener("abort", onAbort, { once: true });
2070
+ let raw;
2071
+ try {
2072
+ raw = await (kind === "registration" ? mod.createPasskey(requestJson) : mod.getPasskey(requestJson));
2073
+ } catch (err2) {
2074
+ normalizeNativeRejection(err2);
2075
+ } finally {
2076
+ signal?.removeEventListener("abort", onAbort);
2077
+ if (inFlight === ticket) inFlight = null;
2078
+ }
2079
+ if (typeof raw !== "string") {
2080
+ throw new CredentialEnvelopeError(
2081
+ `the native module returned ${raw === null ? "null" : `a ${typeof raw}`}; the contract is a JSON string \u2014 wrap a module with an object API so it stringifies its argument and its result`
2082
+ );
2083
+ }
2084
+ let parsed;
2085
+ try {
2086
+ parsed = JSON.parse(raw);
2087
+ } catch {
2088
+ throw new CredentialEnvelopeError(
2089
+ "the native module returned a string that is not valid JSON (a double-encoded response does this)"
2090
+ );
2091
+ }
2092
+ return sanitizeCredentialEnvelope(kind, parsed);
2093
+ }
2094
+ async function ceremonyOrMalformed(kind, requestJson, ceremonyOptions) {
2095
+ try {
2096
+ return await runCeremony(kind, requestJson, ceremonyOptions);
2097
+ } catch (err2) {
2098
+ if (err2 instanceof CredentialEnvelopeError) {
2099
+ return { rakomiEnvelopeViolation: err2.message };
2100
+ }
2101
+ throw err2;
2102
+ }
2103
+ }
2104
+ return {
2105
+ async isSupported() {
2106
+ try {
2107
+ return await mod.isPasskeySupported() === true;
2108
+ } catch {
2109
+ return false;
2110
+ }
2111
+ },
2112
+ hasPlatformAuthenticator() {
2113
+ return probePlatformAuthenticator(mod);
2114
+ },
2115
+ createCredential(creationOptions, ceremonyOptions) {
2116
+ return ceremonyOrMalformed(
2117
+ "registration",
2118
+ JSON.stringify(creationOptions),
2119
+ ceremonyOptions
2120
+ );
2121
+ },
2122
+ getCredential(requestOptions, ceremonyOptions) {
2123
+ return ceremonyOrMalformed(
2124
+ "assertion",
2125
+ JSON.stringify(requestOptions),
2126
+ ceremonyOptions
2127
+ );
2128
+ }
2129
+ };
2130
+ }
2131
+ async function probePlatformAuthenticator(mod) {
2132
+ if (typeof mod.isPlatformAuthenticatorAvailable !== "function") return null;
2133
+ try {
2134
+ const available = await mod.isPlatformAuthenticatorAvailable();
2135
+ return typeof available === "boolean" ? available : null;
2136
+ } catch {
2137
+ return null;
2138
+ }
2139
+ }
2140
+
1807
2141
  // src/internal/webhook-verify.ts
1808
2142
  var RKSEC_PREFIX = "rksec_";
1809
2143
  var EXPECTED_KEY_LENGTH = 32;
@@ -1919,6 +2253,349 @@ async function verifyPublisherWebhook(body, headers, secret, tolerance = DEFAULT
1919
2253
  const clamped = Math.min(Math.max(0, tolerance), MAX_WEBHOOK_TOLERANCE);
1920
2254
  return verifyWebhook(body, headers, secret, clamped);
1921
2255
  }
2256
+ var CEREMONY_ACTIONS = /* @__PURE__ */ new Set(["signIn", "register", "stepUp"]);
2257
+ function platformProbe(adapter) {
2258
+ const candidate = adapter.hasPlatformAuthenticator;
2259
+ return typeof candidate === "function" ? candidate.bind(adapter) : void 0;
2260
+ }
2261
+ function sessionIdentity(token) {
2262
+ const payload = decodeJwtPayload(token);
2263
+ if (payload === null) return null;
2264
+ const subject = payload["sub"];
2265
+ const session = payload["sid"];
2266
+ if (typeof subject !== "string" || !subject) return null;
2267
+ if (typeof session !== "string" || !session) return null;
2268
+ return { subject, session };
2269
+ }
2270
+ var notSupported = () => passkeyError(
2271
+ "PASSKEY_NOT_SUPPORTED",
2272
+ "no passkey ceremony adapter is wired: pass one on `nativeAdapter.passkeys` (see createNativePasskeyAdapter)"
2273
+ );
2274
+ function usePasskeys(options = {}) {
2275
+ const ctx = useRakomiContext();
2276
+ const {
2277
+ adapter: nativeAdapter,
2278
+ http,
2279
+ baseUrl,
2280
+ publishableKey,
2281
+ getToken,
2282
+ beginAuthFlow,
2283
+ submitOAuthTokens,
2284
+ passkeyCeremonyLock
2285
+ } = ctx;
2286
+ const [isSupported, setIsSupported] = useState(null);
2287
+ const [hasPlatformAuthenticator, setHasPlatformAuthenticator] = useState(null);
2288
+ const [passkeys, setPasskeys] = useState(void 0);
2289
+ const [error, setError] = useState(null);
2290
+ const [isSigningIn, setIsSigningIn] = useState(false);
2291
+ const [isRegistering, setIsRegistering] = useState(false);
2292
+ const [isSteppingUp, setIsSteppingUp] = useState(false);
2293
+ const [isLoading, setIsLoading] = useState(false);
2294
+ const [isMutating, setIsMutating] = useState(false);
2295
+ const adapter = options.adapter ?? nativeAdapter.passkeys;
2296
+ const mountedRef = useRef(true);
2297
+ const busyRef = useRef({
2298
+ signIn: false,
2299
+ register: false,
2300
+ stepUp: false,
2301
+ list: false,
2302
+ mutate: false
2303
+ });
2304
+ const inFlightRef = useRef(/* @__PURE__ */ new Set());
2305
+ useEffect(() => {
2306
+ mountedRef.current = true;
2307
+ const inFlight = inFlightRef.current;
2308
+ return () => {
2309
+ mountedRef.current = false;
2310
+ for (const controller of inFlight) controller.abort();
2311
+ inFlight.clear();
2312
+ };
2313
+ }, []);
2314
+ useEffect(() => {
2315
+ if (adapter === void 0) {
2316
+ setIsSupported(false);
2317
+ setHasPlatformAuthenticator(null);
2318
+ return;
2319
+ }
2320
+ let cancelled = false;
2321
+ void (async () => {
2322
+ const [supported, platform] = await Promise.all([
2323
+ Promise.resolve(adapter.isSupported()).catch(() => false),
2324
+ Promise.resolve(platformProbe(adapter)?.() ?? null).catch(() => null)
2325
+ ]);
2326
+ if (cancelled || !mountedRef.current) return;
2327
+ setIsSupported(supported === true);
2328
+ setHasPlatformAuthenticator(typeof platform === "boolean" ? platform : null);
2329
+ })();
2330
+ return () => {
2331
+ cancelled = true;
2332
+ };
2333
+ }, [adapter]);
2334
+ const setBusy = useCallback((key, value) => {
2335
+ busyRef.current[key] = value;
2336
+ if (key === "signIn") setIsSigningIn(value);
2337
+ else if (key === "register") setIsRegistering(value);
2338
+ else if (key === "stepUp") setIsSteppingUp(value);
2339
+ else if (key === "list") setIsLoading(value);
2340
+ else setIsMutating(value);
2341
+ }, []);
2342
+ const requireSession = useCallback(async () => {
2343
+ const expired = () => passkeyError("PASSKEY_SESSION_EXPIRED", "you must be signed in to manage passkeys");
2344
+ const token = await getToken();
2345
+ if (!token.ok) {
2346
+ const err2 = token.error;
2347
+ if (err2.code === "NETWORK_ERROR" || err2.code === "REFRESH_FAILED" && err2.reason === "network") {
2348
+ return passkeyError("PASSKEY_NETWORK_ERROR", err2.message);
2349
+ }
2350
+ return expired();
2351
+ }
2352
+ const user = decodeUser(token.token);
2353
+ if (user === null) return expired();
2354
+ return { accessToken: token.token, userId: user.id };
2355
+ }, [getToken]);
2356
+ const runAction = useCallback(
2357
+ async (key, guarded, run, onSuccess) => {
2358
+ const refuse = (result) => {
2359
+ if (!result.ok && mountedRef.current) setError(result.error);
2360
+ return result;
2361
+ };
2362
+ if (busyRef.current[key]) return refuse(guarded);
2363
+ const isCeremony = CEREMONY_ACTIONS.has(key);
2364
+ if (isCeremony && !passkeyCeremonyLock.tryAcquire()) return refuse(guarded);
2365
+ setBusy(key, true);
2366
+ setError(null);
2367
+ const controller = new AbortController();
2368
+ inFlightRef.current.add(controller);
2369
+ try {
2370
+ const result = await run(controller.signal);
2371
+ if (!result.ok && mountedRef.current) setError(result.error);
2372
+ if (result.ok && mountedRef.current) onSuccess?.(result);
2373
+ return result;
2374
+ } finally {
2375
+ inFlightRef.current.delete(controller);
2376
+ busyRef.current[key] = false;
2377
+ if (isCeremony) passkeyCeremonyLock.release();
2378
+ if (mountedRef.current) setBusy(key, false);
2379
+ }
2380
+ },
2381
+ [passkeyCeremonyLock, setBusy]
2382
+ );
2383
+ const busyResult = useCallback(
2384
+ (action) => ({
2385
+ ok: false,
2386
+ error: passkeyError("PASSKEY_INVALID_INPUT", `a passkey ${action} is already in progress`)
2387
+ }),
2388
+ []
2389
+ );
2390
+ const unsupported = useCallback(() => {
2391
+ const result = { ok: false, error: notSupported() };
2392
+ if (mountedRef.current) setError(result.error);
2393
+ return Promise.resolve(result);
2394
+ }, []);
2395
+ const sessionFailure = (session) => !("accessToken" in session);
2396
+ const signInWithPasskey = useCallback(
2397
+ (input = {}) => {
2398
+ if (adapter === void 0) return unsupported();
2399
+ return runAction("signIn", busyResult("sign-in"), async (signal) => {
2400
+ const result = await assertPasskey({
2401
+ http,
2402
+ baseUrl,
2403
+ clientId: publishableKey,
2404
+ adapter,
2405
+ ...input.userHandle === void 0 ? {} : { userHandle: input.userHandle },
2406
+ signal
2407
+ });
2408
+ if (!result.ok) return result;
2409
+ const failed = (message) => ({
2410
+ ok: false,
2411
+ error: passkeyError("PASSKEY_REQUEST_FAILED", message)
2412
+ });
2413
+ let nonce;
2414
+ try {
2415
+ nonce = await beginAuthFlow();
2416
+ } catch (err2) {
2417
+ return failed(
2418
+ `the passkey was accepted but the session could not be started: ${err2 instanceof Error ? err2.message : "unknown error"}`
2419
+ );
2420
+ }
2421
+ const tokens = result.tokens;
2422
+ if (nativeAdapter.dpopProver !== void 0 && tokens.token_type !== "DPoP") {
2423
+ return failed(
2424
+ "the passkey was accepted but the session was refused: this app is configured for sender-constrained (DPoP) sessions, and the passkey sign-in returned an unbound bearer session. Storing it would silently downgrade the app\u2019s security posture."
2425
+ );
2426
+ }
2427
+ try {
2428
+ await submitOAuthTokens(tokens, nonce);
2429
+ } catch (err2) {
2430
+ return failed(
2431
+ `the passkey was accepted but the session could not be stored: ${err2 instanceof Error ? err2.message : "unknown error"}`
2432
+ );
2433
+ }
2434
+ const confirmed = await getToken();
2435
+ if (!confirmed.ok) {
2436
+ return failed(
2437
+ "the passkey was accepted but the session was not established (the token submission was rejected)"
2438
+ );
2439
+ }
2440
+ const submitted = sessionIdentity(tokens.access_token);
2441
+ const live = sessionIdentity(confirmed.token);
2442
+ if (submitted === null || live === null) {
2443
+ if (confirmed.token !== tokens.access_token) {
2444
+ return failed("the passkey was accepted but the resulting session token could not be read");
2445
+ }
2446
+ return result;
2447
+ }
2448
+ if (live.subject !== submitted.subject || live.session !== submitted.session) {
2449
+ return failed(
2450
+ "the passkey was accepted but the session was not established (the token submission was rejected)"
2451
+ );
2452
+ }
2453
+ return result;
2454
+ });
2455
+ },
2456
+ [
2457
+ adapter,
2458
+ baseUrl,
2459
+ beginAuthFlow,
2460
+ busyResult,
2461
+ getToken,
2462
+ http,
2463
+ publishableKey,
2464
+ runAction,
2465
+ submitOAuthTokens,
2466
+ unsupported
2467
+ ]
2468
+ );
2469
+ const stepUpWithPasskey$1 = useCallback(() => {
2470
+ if (adapter === void 0) return unsupported();
2471
+ return runAction("stepUp", busyResult("step-up"), async (signal) => {
2472
+ const session = await requireSession();
2473
+ if (sessionFailure(session)) return { ok: false, error: session };
2474
+ return stepUpWithPasskey({
2475
+ http,
2476
+ baseUrl,
2477
+ clientId: publishableKey,
2478
+ accessToken: session.accessToken,
2479
+ adapter,
2480
+ signal
2481
+ });
2482
+ });
2483
+ }, [adapter, baseUrl, busyResult, http, publishableKey, requireSession, runAction, unsupported]);
2484
+ const registerPasskey$1 = useCallback(
2485
+ (input) => {
2486
+ if (adapter === void 0) return unsupported();
2487
+ return runAction("register", busyResult("registration"), async (signal) => {
2488
+ const session = await requireSession();
2489
+ if (sessionFailure(session)) return { ok: false, error: session };
2490
+ return registerPasskey({
2491
+ http,
2492
+ baseUrl,
2493
+ clientId: publishableKey,
2494
+ accessToken: session.accessToken,
2495
+ stepUpToken: input.stepUpToken,
2496
+ adapter,
2497
+ ...input.nickname === void 0 ? {} : { nickname: input.nickname },
2498
+ signal
2499
+ });
2500
+ });
2501
+ },
2502
+ [adapter, baseUrl, busyResult, http, publishableKey, requireSession, runAction, unsupported]
2503
+ );
2504
+ const listPasskeys$1 = useCallback(
2505
+ (input) => runAction(
2506
+ "list",
2507
+ busyResult("list"),
2508
+ async (signal) => {
2509
+ const session = await requireSession();
2510
+ if (sessionFailure(session)) return { ok: false, error: session };
2511
+ return listPasskeys({
2512
+ http,
2513
+ baseUrl,
2514
+ clientId: publishableKey,
2515
+ accessToken: session.accessToken,
2516
+ stepUpToken: input.stepUpToken,
2517
+ userId: session.userId,
2518
+ signal
2519
+ });
2520
+ },
2521
+ (result) => {
2522
+ if (result.ok) setPasskeys(result.data);
2523
+ }
2524
+ ),
2525
+ [baseUrl, busyResult, http, publishableKey, requireSession, runAction]
2526
+ );
2527
+ const renamePasskey$1 = useCallback(
2528
+ (input) => runAction(
2529
+ "mutate",
2530
+ busyResult("mutation"),
2531
+ async (signal) => {
2532
+ const session = await requireSession();
2533
+ if (sessionFailure(session)) return { ok: false, error: session };
2534
+ return renamePasskey({
2535
+ http,
2536
+ baseUrl,
2537
+ clientId: publishableKey,
2538
+ accessToken: session.accessToken,
2539
+ stepUpToken: input.stepUpToken,
2540
+ userId: session.userId,
2541
+ passkeyId: input.passkeyId,
2542
+ nickname: input.nickname,
2543
+ signal
2544
+ });
2545
+ },
2546
+ (result) => {
2547
+ if (!result.ok) return;
2548
+ setPasskeys(
2549
+ (current) => current?.map((passkey) => passkey.id === result.passkey.id ? result.passkey : passkey)
2550
+ );
2551
+ }
2552
+ ),
2553
+ [baseUrl, busyResult, http, publishableKey, requireSession, runAction]
2554
+ );
2555
+ const deletePasskey$1 = useCallback(
2556
+ (input) => runAction(
2557
+ "mutate",
2558
+ busyResult("mutation"),
2559
+ async (signal) => {
2560
+ const session = await requireSession();
2561
+ if (sessionFailure(session)) return { ok: false, error: session };
2562
+ return deletePasskey({
2563
+ http,
2564
+ baseUrl,
2565
+ clientId: publishableKey,
2566
+ accessToken: session.accessToken,
2567
+ stepUpToken: input.stepUpToken,
2568
+ userId: session.userId,
2569
+ passkeyId: input.passkeyId,
2570
+ signal
2571
+ });
2572
+ },
2573
+ (result) => {
2574
+ if (result.ok) {
2575
+ setPasskeys((current) => current?.filter((passkey) => passkey.id !== input.passkeyId));
2576
+ }
2577
+ }
2578
+ ),
2579
+ [baseUrl, busyResult, http, publishableKey, requireSession, runAction]
2580
+ );
2581
+ return {
2582
+ isSupported,
2583
+ hasPlatformAuthenticator,
2584
+ passkeys,
2585
+ error,
2586
+ isSigningIn,
2587
+ isRegistering,
2588
+ isSteppingUp,
2589
+ isLoading,
2590
+ isMutating,
2591
+ signInWithPasskey,
2592
+ stepUpWithPasskey: stepUpWithPasskey$1,
2593
+ registerPasskey: registerPasskey$1,
2594
+ listPasskeys: listPasskeys$1,
2595
+ renamePasskey: renamePasskey$1,
2596
+ deletePasskey: deletePasskey$1
2597
+ };
2598
+ }
1922
2599
 
1923
2600
  // src/hooks/use-submit-oauth-tokens.ts
1924
2601
  function useSubmitOAuthTokens() {
@@ -2001,4 +2678,4 @@ function useMfa() {
2001
2678
  };
2002
2679
  }
2003
2680
 
2004
- export { DEFAULT_WEBHOOK_TOLERANCE, DpopSession, Feature, MAX_WEBHOOK_TOLERANCE, Protect, RakomiProvider, SignIn, SignUp, SignedIn, SignedOut, UserButton, UserProfile, createDefaultExpoAdapter, createDpopSession, createNativeDpopProver, createRnHttpClient, startSocialSignIn, useAnonymousSignin, useAuth, useAuthConfig, useBaasPlans, useBaasSubscription, useBranding, useEmailOtp, useFlag, useLinkedAccounts, useMagicLink, useMfa, useOrganization, useOrganizationList, useRegister, useSession, useSubmitOAuthTokens, useTranslation, useUser, verifyPublisherWebhook, verifyWebhook };
2681
+ export { DEFAULT_WEBHOOK_TOLERANCE, DpopSession, Feature, MAX_WEBHOOK_TOLERANCE, Protect, RakomiProvider, SignIn, SignUp, SignedIn, SignedOut, UserButton, UserProfile, createDefaultExpoAdapter, createDpopSession, createNativeDpopProver, createNativePasskeyAdapter, createRnHttpClient, startSocialSignIn, useAnonymousSignin, useAuth, useAuthConfig, useBaasPlans, useBaasSubscription, useBranding, useEmailOtp, useFlag, useLinkedAccounts, useMagicLink, useMfa, useOrganization, useOrganizationList, usePasskeys, useRegister, useSession, useSubmitOAuthTokens, useTranslation, useUser, verifyPublisherWebhook, verifyWebhook };