@rakomi/react-native 0.1.0 → 0.3.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,6 +1,6 @@
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';
3
- export { MfaStepUpRequiredError, MfaStepUpUnavailableError, base64url, createTranslator, decodeJwtPayload, decodeSession, decodeUser, generatePkce, getErrorMessage, hasPermission, hasRole, isSafeUrl, networkError, parseOAuthCallbackError, parseTokenEndpointError, scorePassword, selectPluralForm } from '@rakomi/sdk-core';
1
+ import { createContext, useMemo, useReducer, useRef, useEffect, useState, useCallback, useContext } from 'react';
2
+ import { createAuthorizationEndpointCache, 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
+ export { MfaStepUpRequiredError, MfaStepUpUnavailableError, base64url, createAuthorizationEndpointCache, createTranslator, decodeJwtPayload, decodeSession, decodeUser, deriveAuthorizationEndpointFallback, 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';
6
6
 
@@ -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
  }
@@ -940,8 +1012,24 @@ function RakomiProvider(props) {
940
1012
  return Object.freeze(built);
941
1013
  }, [props.nativeAdapter, props.tokenCache]);
942
1014
  const http = useMemo(() => createRnHttpClient({ baseUrl: props.baseUrl }), [props.baseUrl]);
1015
+ const authorizationEndpointCache = useMemo(
1016
+ () => createAuthorizationEndpointCache({
1017
+ fetchDiscoveryDocument: async () => {
1018
+ const response = await http.fetch("/.well-known/openid-configuration", {
1019
+ method: "GET",
1020
+ headers: { Accept: "application/json" }
1021
+ });
1022
+ if (!response.ok) {
1023
+ throw new Error(`discovery fetch failed: HTTP ${response.status}`);
1024
+ }
1025
+ return response.json();
1026
+ }
1027
+ }),
1028
+ [http]
1029
+ );
943
1030
  const events = useMemo(() => new EventLog(props.onEvent), [props.onEvent]);
944
1031
  const [snapshot, dispatch] = useReducer(reduce, INITIAL_SNAPSHOT);
1032
+ const passkeyCeremonyLock = useRef(createCeremonyLock()).current;
945
1033
  const translate = useMemo(
946
1034
  () => createTranslator(props.locale ?? "en", props.translations),
947
1035
  [props.locale, props.translations]
@@ -1074,6 +1162,7 @@ function RakomiProvider(props) {
1074
1162
  redirectUri: props.redirectUri,
1075
1163
  adapter,
1076
1164
  http,
1165
+ authorizationEndpointCache,
1077
1166
  snapshot,
1078
1167
  state: snapshot.state,
1079
1168
  isSignedIn: isSignedIn(snapshot),
@@ -1085,10 +1174,11 @@ function RakomiProvider(props) {
1085
1174
  signOut,
1086
1175
  getToken,
1087
1176
  submitOAuthTokens,
1177
+ passkeyCeremonyLock,
1088
1178
  beginAuthFlow,
1089
1179
  dpopSession
1090
1180
  }),
1091
- [adapter, http, snapshot, events, props.publishableKey, props.baseUrl, props.redirectUri, props.locale, translate, signOut, getToken, submitOAuthTokens, beginAuthFlow, dpopSession]
1181
+ [adapter, http, authorizationEndpointCache, snapshot, events, props.publishableKey, props.baseUrl, props.redirectUri, props.locale, translate, signOut, getToken, submitOAuthTokens, beginAuthFlow, dpopSession, passkeyCeremonyLock]
1092
1182
  );
1093
1183
  return /* @__PURE__ */ jsx(RakomiContext.Provider, { value, children: props.children });
1094
1184
  }
@@ -1202,19 +1292,20 @@ function useFlag(flag, options) {
1202
1292
  }
1203
1293
  function useOrganization() {
1204
1294
  const { user } = useRakomiContext();
1205
- const orgId = user?.rawClaims["org_id"];
1206
- const orgRole = user?.rawClaims["org_role"];
1207
- const orgMemberships = user?.rawClaims["org_memberships"] ?? [];
1295
+ const { org_id: orgId, org_role: orgRole, org_memberships: orgMemberships } = extractOrgClaims(
1296
+ user?.rawClaims ?? {}
1297
+ );
1208
1298
  return {
1209
1299
  isLoaded: !!user,
1210
- organization: orgId && orgRole ? { orgId, orgRole, orgMemberships } : null
1300
+ organization: orgId && orgRole ? { orgId, orgRole, orgMemberships: orgMemberships ?? [] } : null
1211
1301
  };
1212
1302
  }
1213
1303
  function useOrganizationList() {
1214
1304
  const { user } = useRakomiContext();
1305
+ const { org_memberships: organizations } = extractOrgClaims(user?.rawClaims ?? {});
1215
1306
  return {
1216
1307
  isLoaded: !!user,
1217
- organizations: user?.rawClaims["org_memberships"] ?? []
1308
+ organizations: organizations ?? []
1218
1309
  };
1219
1310
  }
1220
1311
  function useLinkedAccounts() {
@@ -1248,7 +1339,8 @@ function useAuthConfig() {
1248
1339
  headers: { Accept: "application/json", "X-API-Key": publishableKey }
1249
1340
  });
1250
1341
  if (!response.ok) return null;
1251
- return await response.json();
1342
+ const raw = await response.json();
1343
+ return parseAuthConfigResponse(raw, baseUrl);
1252
1344
  } catch {
1253
1345
  return null;
1254
1346
  }
@@ -1544,13 +1636,23 @@ function SignIn(props) {
1544
1636
  const [code, setCode] = useState("");
1545
1637
  const [busy, setBusy] = useState(false);
1546
1638
  const tokenEndpoint = props.tokenEndpoint ?? "/v1/auth/oauth/callback";
1547
- const authorizationEndpoint = props.authorizationEndpoint ?? "/oauth/authorize";
1548
1639
  const totpVerifyEndpoint = props.totpVerifyEndpoint ?? "/v1/auth/mfa/totp/verify";
1549
1640
  const providers = props.providers ?? ["google"];
1550
1641
  async function onProviderPress(provider) {
1551
1642
  if (busy) return;
1552
1643
  setBusy(true);
1553
1644
  ctx.events.push({ type: "sign_in_attempted", severity: "info", metadata: { provider } });
1645
+ let authorizationEndpoint = props.authorizationEndpoint;
1646
+ if (!authorizationEndpoint) {
1647
+ const resolved = await ctx.authorizationEndpointCache.resolve(ctx.baseUrl);
1648
+ if (!resolved.ok) {
1649
+ ctx.events.push({ type: "sign_in_failed", severity: "warning", error: resolved.error });
1650
+ setStep({ kind: "error", error: resolved.error });
1651
+ setBusy(false);
1652
+ return;
1653
+ }
1654
+ authorizationEndpoint = resolved.authorizationEndpoint;
1655
+ }
1554
1656
  const outcome = await startSocialSignIn({
1555
1657
  adapter: ctx.adapter,
1556
1658
  http: ctx.http,
@@ -1756,7 +1858,7 @@ function UserButton(props) {
1756
1858
  function UserProfile(props) {
1757
1859
  useEffect(() => {
1758
1860
  if (typeof __DEV__ !== "undefined" && __DEV__) {
1759
- console.warn("[@rakomi/react-native] <UserProfile /> is in preview until 0.2.0 \u2014 feedback welcome.");
1861
+ console.warn("[@rakomi/react-native] <UserProfile /> is in preview \u2014 feedback welcome.");
1760
1862
  }
1761
1863
  }, []);
1762
1864
  const ctx = useRakomiContext();
@@ -1804,6 +1906,264 @@ function createNativeDpopProver(options) {
1804
1906
  };
1805
1907
  }
1806
1908
 
1909
+ // src/native/passkey-envelope.ts
1910
+ var BASE64URL = /^[A-Za-z0-9_-]+$/;
1911
+ var RULES = {
1912
+ registration: {
1913
+ required: ["id", "rawId", "response.clientDataJSON", "response.attestationObject"],
1914
+ base64url: ["id", "rawId", "response.clientDataJSON", "response.attestationObject"],
1915
+ requiredStringArray: ["response.transports"],
1916
+ requiredObject: ["clientExtensionResults"],
1917
+ keep: ["id", "rawId", "type", "authenticatorAttachment", "clientExtensionResults"],
1918
+ keepInResponse: [
1919
+ "clientDataJSON",
1920
+ "attestationObject",
1921
+ "authenticatorData",
1922
+ "publicKey",
1923
+ "publicKeyAlgorithm"
1924
+ ],
1925
+ keepStringArrayInResponse: ["transports"]
1926
+ },
1927
+ assertion: {
1928
+ required: [
1929
+ "id",
1930
+ "rawId",
1931
+ "response.clientDataJSON",
1932
+ "response.authenticatorData",
1933
+ "response.signature"
1934
+ ],
1935
+ base64url: [
1936
+ "id",
1937
+ "rawId",
1938
+ "response.clientDataJSON",
1939
+ "response.authenticatorData",
1940
+ "response.signature",
1941
+ "response.userHandle"
1942
+ ],
1943
+ requiredStringArray: [],
1944
+ requiredObject: ["clientExtensionResults"],
1945
+ keep: ["id", "rawId", "type", "authenticatorAttachment", "clientExtensionResults"],
1946
+ keepInResponse: ["clientDataJSON", "authenticatorData", "signature", "userHandle"],
1947
+ keepStringArrayInResponse: []
1948
+ }
1949
+ };
1950
+ var CredentialEnvelopeError = class extends Error {
1951
+ constructor(message) {
1952
+ super(message);
1953
+ this.name = "CredentialEnvelopeError";
1954
+ }
1955
+ };
1956
+ function isRecord(value) {
1957
+ return typeof value === "object" && value !== null;
1958
+ }
1959
+ function readPath(envelope, path) {
1960
+ const dot = path.indexOf(".");
1961
+ if (dot === -1) return envelope[path];
1962
+ const parent = envelope[path.slice(0, dot)];
1963
+ return isRecord(parent) ? parent[path.slice(dot + 1)] : void 0;
1964
+ }
1965
+ function assertW3cCredentialEnvelope(kind, parsed) {
1966
+ if (!isRecord(parsed)) {
1967
+ throw new CredentialEnvelopeError(
1968
+ `the native module returned a ${parsed === null ? "null" : typeof parsed}; the contract is a JSON object`
1969
+ );
1970
+ }
1971
+ if (parsed["type"] !== "public-key") {
1972
+ throw new CredentialEnvelopeError(`'type' must be the string "public-key" (W3C WebAuthn L3)`);
1973
+ }
1974
+ if (!isRecord(parsed["response"])) {
1975
+ throw new CredentialEnvelopeError(`'response' is missing or is not an object`);
1976
+ }
1977
+ const rule = RULES[kind];
1978
+ for (const path of rule.required) {
1979
+ const value = readPath(parsed, path);
1980
+ if (typeof value !== "string" || value.length === 0) {
1981
+ throw new CredentialEnvelopeError(
1982
+ `'${path}' is required on a ${kind} response and must be a non-empty string (W3C WebAuthn L3 JSON serialization)`
1983
+ );
1984
+ }
1985
+ }
1986
+ for (const path of rule.requiredStringArray) {
1987
+ const value = readPath(parsed, path);
1988
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
1989
+ throw new CredentialEnvelopeError(
1990
+ `'${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.`
1991
+ );
1992
+ }
1993
+ }
1994
+ for (const path of rule.requiredObject) {
1995
+ const value = readPath(parsed, path);
1996
+ if (!isRecord(value)) {
1997
+ throw new CredentialEnvelopeError(
1998
+ `'${path}' is required on a ${kind} response and must be an object (an empty object is fine)`
1999
+ );
2000
+ }
2001
+ }
2002
+ for (const path of rule.base64url) {
2003
+ const value = readPath(parsed, path);
2004
+ if (value === void 0 || value === null) continue;
2005
+ if (typeof value !== "string" || !BASE64URL.test(value)) {
2006
+ throw new CredentialEnvelopeError(
2007
+ `'${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.`
2008
+ );
2009
+ }
2010
+ }
2011
+ }
2012
+ function sanitizeCredentialEnvelope(kind, parsed) {
2013
+ assertW3cCredentialEnvelope(kind, parsed);
2014
+ const envelope = parsed;
2015
+ const source = envelope["response"];
2016
+ const rule = RULES[kind];
2017
+ const response = /* @__PURE__ */ Object.create(null);
2018
+ for (const key of rule.keepInResponse) {
2019
+ const value = source[key];
2020
+ if (typeof value === "string" || typeof value === "number") response[key] = value;
2021
+ }
2022
+ for (const key of rule.keepStringArrayInResponse) {
2023
+ const value = source[key];
2024
+ if (Array.isArray(value)) response[key] = value.filter((entry) => typeof entry === "string");
2025
+ }
2026
+ const projected = /* @__PURE__ */ Object.create(null);
2027
+ for (const key of rule.keep) {
2028
+ const value = envelope[key];
2029
+ if (value !== void 0) projected[key] = value;
2030
+ }
2031
+ projected["response"] = response;
2032
+ return projected;
2033
+ }
2034
+
2035
+ // src/native/passkey-adapter.ts
2036
+ var NATIVE_CODE_TO_KIND = Object.assign(/* @__PURE__ */ Object.create(null), {
2037
+ PASSKEY_CANCELLED: "cancelled",
2038
+ PASSKEY_UNSUPPORTED: "unsupported",
2039
+ PASSKEY_NO_CREDENTIAL: "cancelled"
2040
+ });
2041
+ function isRecord2(value) {
2042
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2043
+ }
2044
+ function normalizeNativeRejection(err2) {
2045
+ const code = isRecord2(err2) ? err2["code"] : void 0;
2046
+ if (typeof code === "string") {
2047
+ const kind = NATIVE_CODE_TO_KIND[code];
2048
+ if (kind !== void 0) {
2049
+ throw new PasskeyCeremonyError(kind);
2050
+ }
2051
+ }
2052
+ throw err2;
2053
+ }
2054
+ function assertNever(value) {
2055
+ throw new PasskeyCeremonyError("failed", `unhandled ceremony-error kind: ${String(value)}`);
2056
+ }
2057
+ function describeKind(kind) {
2058
+ switch (kind) {
2059
+ case "cancelled":
2060
+ return "the user dismissed the passkey sheet";
2061
+ case "unsupported":
2062
+ return "this platform cannot run a passkey ceremony";
2063
+ case "failed":
2064
+ return "the passkey ceremony failed";
2065
+ default:
2066
+ return assertNever(kind);
2067
+ }
2068
+ }
2069
+ function createNativePasskeyAdapter(options) {
2070
+ const mod = options.module;
2071
+ let inFlight = null;
2072
+ const candidate = mod;
2073
+ const missing = ["isPasskeySupported", "createPasskey", "getPasskey"].filter(
2074
+ (method) => typeof candidate?.[method] !== "function"
2075
+ );
2076
+ if (missing.length > 0) {
2077
+ throw new Error(
2078
+ `native passkey module is missing: ${missing.join(", ")} \u2014 it does not satisfy NativePasskeyModuleSpec`
2079
+ );
2080
+ }
2081
+ async function runCeremony(kind, requestJson, ceremonyOptions) {
2082
+ const signal = ceremonyOptions?.signal;
2083
+ if (signal?.aborted === true) {
2084
+ throw new PasskeyCeremonyError("cancelled", describeKind("cancelled"));
2085
+ }
2086
+ const ticket = /* @__PURE__ */ Symbol("passkey-ceremony");
2087
+ inFlight = ticket;
2088
+ const onAbort = () => {
2089
+ if (inFlight !== ticket) return;
2090
+ try {
2091
+ void Promise.resolve(mod.cancelPasskeyRequest?.()).catch(() => void 0);
2092
+ } catch {
2093
+ }
2094
+ };
2095
+ signal?.addEventListener("abort", onAbort, { once: true });
2096
+ let raw;
2097
+ try {
2098
+ raw = await (kind === "registration" ? mod.createPasskey(requestJson) : mod.getPasskey(requestJson));
2099
+ } catch (err2) {
2100
+ normalizeNativeRejection(err2);
2101
+ } finally {
2102
+ signal?.removeEventListener("abort", onAbort);
2103
+ if (inFlight === ticket) inFlight = null;
2104
+ }
2105
+ if (typeof raw !== "string") {
2106
+ throw new CredentialEnvelopeError(
2107
+ `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`
2108
+ );
2109
+ }
2110
+ let parsed;
2111
+ try {
2112
+ parsed = JSON.parse(raw);
2113
+ } catch {
2114
+ throw new CredentialEnvelopeError(
2115
+ "the native module returned a string that is not valid JSON (a double-encoded response does this)"
2116
+ );
2117
+ }
2118
+ return sanitizeCredentialEnvelope(kind, parsed);
2119
+ }
2120
+ async function ceremonyOrMalformed(kind, requestJson, ceremonyOptions) {
2121
+ try {
2122
+ return await runCeremony(kind, requestJson, ceremonyOptions);
2123
+ } catch (err2) {
2124
+ if (err2 instanceof CredentialEnvelopeError) {
2125
+ return { rakomiEnvelopeViolation: err2.message };
2126
+ }
2127
+ throw err2;
2128
+ }
2129
+ }
2130
+ return {
2131
+ async isSupported() {
2132
+ try {
2133
+ return await mod.isPasskeySupported() === true;
2134
+ } catch {
2135
+ return false;
2136
+ }
2137
+ },
2138
+ hasPlatformAuthenticator() {
2139
+ return probePlatformAuthenticator(mod);
2140
+ },
2141
+ createCredential(creationOptions, ceremonyOptions) {
2142
+ return ceremonyOrMalformed(
2143
+ "registration",
2144
+ JSON.stringify(creationOptions),
2145
+ ceremonyOptions
2146
+ );
2147
+ },
2148
+ getCredential(requestOptions, ceremonyOptions) {
2149
+ return ceremonyOrMalformed(
2150
+ "assertion",
2151
+ JSON.stringify(requestOptions),
2152
+ ceremonyOptions
2153
+ );
2154
+ }
2155
+ };
2156
+ }
2157
+ async function probePlatformAuthenticator(mod) {
2158
+ if (typeof mod.isPlatformAuthenticatorAvailable !== "function") return null;
2159
+ try {
2160
+ const available = await mod.isPlatformAuthenticatorAvailable();
2161
+ return typeof available === "boolean" ? available : null;
2162
+ } catch {
2163
+ return null;
2164
+ }
2165
+ }
2166
+
1807
2167
  // src/internal/webhook-verify.ts
1808
2168
  var RKSEC_PREFIX = "rksec_";
1809
2169
  var EXPECTED_KEY_LENGTH = 32;
@@ -1919,6 +2279,349 @@ async function verifyPublisherWebhook(body, headers, secret, tolerance = DEFAULT
1919
2279
  const clamped = Math.min(Math.max(0, tolerance), MAX_WEBHOOK_TOLERANCE);
1920
2280
  return verifyWebhook(body, headers, secret, clamped);
1921
2281
  }
2282
+ var CEREMONY_ACTIONS = /* @__PURE__ */ new Set(["signIn", "register", "stepUp"]);
2283
+ function platformProbe(adapter) {
2284
+ const candidate = adapter.hasPlatformAuthenticator;
2285
+ return typeof candidate === "function" ? candidate.bind(adapter) : void 0;
2286
+ }
2287
+ function sessionIdentity(token) {
2288
+ const payload = decodeJwtPayload(token);
2289
+ if (payload === null) return null;
2290
+ const subject = payload["sub"];
2291
+ const session = payload["sid"];
2292
+ if (typeof subject !== "string" || !subject) return null;
2293
+ if (typeof session !== "string" || !session) return null;
2294
+ return { subject, session };
2295
+ }
2296
+ var notSupported = () => passkeyError(
2297
+ "PASSKEY_NOT_SUPPORTED",
2298
+ "no passkey ceremony adapter is wired: pass one on `nativeAdapter.passkeys` (see createNativePasskeyAdapter)"
2299
+ );
2300
+ function usePasskeys(options = {}) {
2301
+ const ctx = useRakomiContext();
2302
+ const {
2303
+ adapter: nativeAdapter,
2304
+ http,
2305
+ baseUrl,
2306
+ publishableKey,
2307
+ getToken,
2308
+ beginAuthFlow,
2309
+ submitOAuthTokens,
2310
+ passkeyCeremonyLock
2311
+ } = ctx;
2312
+ const [isSupported, setIsSupported] = useState(null);
2313
+ const [hasPlatformAuthenticator, setHasPlatformAuthenticator] = useState(null);
2314
+ const [passkeys, setPasskeys] = useState(void 0);
2315
+ const [error, setError] = useState(null);
2316
+ const [isSigningIn, setIsSigningIn] = useState(false);
2317
+ const [isRegistering, setIsRegistering] = useState(false);
2318
+ const [isSteppingUp, setIsSteppingUp] = useState(false);
2319
+ const [isLoading, setIsLoading] = useState(false);
2320
+ const [isMutating, setIsMutating] = useState(false);
2321
+ const adapter = options.adapter ?? nativeAdapter.passkeys;
2322
+ const mountedRef = useRef(true);
2323
+ const busyRef = useRef({
2324
+ signIn: false,
2325
+ register: false,
2326
+ stepUp: false,
2327
+ list: false,
2328
+ mutate: false
2329
+ });
2330
+ const inFlightRef = useRef(/* @__PURE__ */ new Set());
2331
+ useEffect(() => {
2332
+ mountedRef.current = true;
2333
+ const inFlight = inFlightRef.current;
2334
+ return () => {
2335
+ mountedRef.current = false;
2336
+ for (const controller of inFlight) controller.abort();
2337
+ inFlight.clear();
2338
+ };
2339
+ }, []);
2340
+ useEffect(() => {
2341
+ if (adapter === void 0) {
2342
+ setIsSupported(false);
2343
+ setHasPlatformAuthenticator(null);
2344
+ return;
2345
+ }
2346
+ let cancelled = false;
2347
+ void (async () => {
2348
+ const [supported, platform] = await Promise.all([
2349
+ Promise.resolve(adapter.isSupported()).catch(() => false),
2350
+ Promise.resolve(platformProbe(adapter)?.() ?? null).catch(() => null)
2351
+ ]);
2352
+ if (cancelled || !mountedRef.current) return;
2353
+ setIsSupported(supported === true);
2354
+ setHasPlatformAuthenticator(typeof platform === "boolean" ? platform : null);
2355
+ })();
2356
+ return () => {
2357
+ cancelled = true;
2358
+ };
2359
+ }, [adapter]);
2360
+ const setBusy = useCallback((key, value) => {
2361
+ busyRef.current[key] = value;
2362
+ if (key === "signIn") setIsSigningIn(value);
2363
+ else if (key === "register") setIsRegistering(value);
2364
+ else if (key === "stepUp") setIsSteppingUp(value);
2365
+ else if (key === "list") setIsLoading(value);
2366
+ else setIsMutating(value);
2367
+ }, []);
2368
+ const requireSession = useCallback(async () => {
2369
+ const expired = () => passkeyError("PASSKEY_SESSION_EXPIRED", "you must be signed in to manage passkeys");
2370
+ const token = await getToken();
2371
+ if (!token.ok) {
2372
+ const err2 = token.error;
2373
+ if (err2.code === "NETWORK_ERROR" || err2.code === "REFRESH_FAILED" && err2.reason === "network") {
2374
+ return passkeyError("PASSKEY_NETWORK_ERROR", err2.message);
2375
+ }
2376
+ return expired();
2377
+ }
2378
+ const user = decodeUser(token.token);
2379
+ if (user === null) return expired();
2380
+ return { accessToken: token.token, userId: user.id };
2381
+ }, [getToken]);
2382
+ const runAction = useCallback(
2383
+ async (key, guarded, run, onSuccess) => {
2384
+ const refuse = (result) => {
2385
+ if (!result.ok && mountedRef.current) setError(result.error);
2386
+ return result;
2387
+ };
2388
+ if (busyRef.current[key]) return refuse(guarded);
2389
+ const isCeremony = CEREMONY_ACTIONS.has(key);
2390
+ if (isCeremony && !passkeyCeremonyLock.tryAcquire()) return refuse(guarded);
2391
+ setBusy(key, true);
2392
+ setError(null);
2393
+ const controller = new AbortController();
2394
+ inFlightRef.current.add(controller);
2395
+ try {
2396
+ const result = await run(controller.signal);
2397
+ if (!result.ok && mountedRef.current) setError(result.error);
2398
+ if (result.ok && mountedRef.current) onSuccess?.(result);
2399
+ return result;
2400
+ } finally {
2401
+ inFlightRef.current.delete(controller);
2402
+ busyRef.current[key] = false;
2403
+ if (isCeremony) passkeyCeremonyLock.release();
2404
+ if (mountedRef.current) setBusy(key, false);
2405
+ }
2406
+ },
2407
+ [passkeyCeremonyLock, setBusy]
2408
+ );
2409
+ const busyResult = useCallback(
2410
+ (action) => ({
2411
+ ok: false,
2412
+ error: passkeyError("PASSKEY_INVALID_INPUT", `a passkey ${action} is already in progress`)
2413
+ }),
2414
+ []
2415
+ );
2416
+ const unsupported = useCallback(() => {
2417
+ const result = { ok: false, error: notSupported() };
2418
+ if (mountedRef.current) setError(result.error);
2419
+ return Promise.resolve(result);
2420
+ }, []);
2421
+ const sessionFailure = (session) => !("accessToken" in session);
2422
+ const signInWithPasskey = useCallback(
2423
+ (input = {}) => {
2424
+ if (adapter === void 0) return unsupported();
2425
+ return runAction("signIn", busyResult("sign-in"), async (signal) => {
2426
+ const result = await assertPasskey({
2427
+ http,
2428
+ baseUrl,
2429
+ clientId: publishableKey,
2430
+ adapter,
2431
+ ...input.userHandle === void 0 ? {} : { userHandle: input.userHandle },
2432
+ signal
2433
+ });
2434
+ if (!result.ok) return result;
2435
+ const failed = (message) => ({
2436
+ ok: false,
2437
+ error: passkeyError("PASSKEY_REQUEST_FAILED", message)
2438
+ });
2439
+ let nonce;
2440
+ try {
2441
+ nonce = await beginAuthFlow();
2442
+ } catch (err2) {
2443
+ return failed(
2444
+ `the passkey was accepted but the session could not be started: ${err2 instanceof Error ? err2.message : "unknown error"}`
2445
+ );
2446
+ }
2447
+ const tokens = result.tokens;
2448
+ if (nativeAdapter.dpopProver !== void 0 && tokens.token_type !== "DPoP") {
2449
+ return failed(
2450
+ "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."
2451
+ );
2452
+ }
2453
+ try {
2454
+ await submitOAuthTokens(tokens, nonce);
2455
+ } catch (err2) {
2456
+ return failed(
2457
+ `the passkey was accepted but the session could not be stored: ${err2 instanceof Error ? err2.message : "unknown error"}`
2458
+ );
2459
+ }
2460
+ const confirmed = await getToken();
2461
+ if (!confirmed.ok) {
2462
+ return failed(
2463
+ "the passkey was accepted but the session was not established (the token submission was rejected)"
2464
+ );
2465
+ }
2466
+ const submitted = sessionIdentity(tokens.access_token);
2467
+ const live = sessionIdentity(confirmed.token);
2468
+ if (submitted === null || live === null) {
2469
+ if (confirmed.token !== tokens.access_token) {
2470
+ return failed("the passkey was accepted but the resulting session token could not be read");
2471
+ }
2472
+ return result;
2473
+ }
2474
+ if (live.subject !== submitted.subject || live.session !== submitted.session) {
2475
+ return failed(
2476
+ "the passkey was accepted but the session was not established (the token submission was rejected)"
2477
+ );
2478
+ }
2479
+ return result;
2480
+ });
2481
+ },
2482
+ [
2483
+ adapter,
2484
+ baseUrl,
2485
+ beginAuthFlow,
2486
+ busyResult,
2487
+ getToken,
2488
+ http,
2489
+ publishableKey,
2490
+ runAction,
2491
+ submitOAuthTokens,
2492
+ unsupported
2493
+ ]
2494
+ );
2495
+ const stepUpWithPasskey$1 = useCallback(() => {
2496
+ if (adapter === void 0) return unsupported();
2497
+ return runAction("stepUp", busyResult("step-up"), async (signal) => {
2498
+ const session = await requireSession();
2499
+ if (sessionFailure(session)) return { ok: false, error: session };
2500
+ return stepUpWithPasskey({
2501
+ http,
2502
+ baseUrl,
2503
+ clientId: publishableKey,
2504
+ accessToken: session.accessToken,
2505
+ adapter,
2506
+ signal
2507
+ });
2508
+ });
2509
+ }, [adapter, baseUrl, busyResult, http, publishableKey, requireSession, runAction, unsupported]);
2510
+ const registerPasskey$1 = useCallback(
2511
+ (input) => {
2512
+ if (adapter === void 0) return unsupported();
2513
+ return runAction("register", busyResult("registration"), async (signal) => {
2514
+ const session = await requireSession();
2515
+ if (sessionFailure(session)) return { ok: false, error: session };
2516
+ return registerPasskey({
2517
+ http,
2518
+ baseUrl,
2519
+ clientId: publishableKey,
2520
+ accessToken: session.accessToken,
2521
+ stepUpToken: input.stepUpToken,
2522
+ adapter,
2523
+ ...input.nickname === void 0 ? {} : { nickname: input.nickname },
2524
+ signal
2525
+ });
2526
+ });
2527
+ },
2528
+ [adapter, baseUrl, busyResult, http, publishableKey, requireSession, runAction, unsupported]
2529
+ );
2530
+ const listPasskeys$1 = useCallback(
2531
+ (input) => runAction(
2532
+ "list",
2533
+ busyResult("list"),
2534
+ async (signal) => {
2535
+ const session = await requireSession();
2536
+ if (sessionFailure(session)) return { ok: false, error: session };
2537
+ return listPasskeys({
2538
+ http,
2539
+ baseUrl,
2540
+ clientId: publishableKey,
2541
+ accessToken: session.accessToken,
2542
+ stepUpToken: input.stepUpToken,
2543
+ userId: session.userId,
2544
+ signal
2545
+ });
2546
+ },
2547
+ (result) => {
2548
+ if (result.ok) setPasskeys(result.data);
2549
+ }
2550
+ ),
2551
+ [baseUrl, busyResult, http, publishableKey, requireSession, runAction]
2552
+ );
2553
+ const renamePasskey$1 = useCallback(
2554
+ (input) => runAction(
2555
+ "mutate",
2556
+ busyResult("mutation"),
2557
+ async (signal) => {
2558
+ const session = await requireSession();
2559
+ if (sessionFailure(session)) return { ok: false, error: session };
2560
+ return renamePasskey({
2561
+ http,
2562
+ baseUrl,
2563
+ clientId: publishableKey,
2564
+ accessToken: session.accessToken,
2565
+ stepUpToken: input.stepUpToken,
2566
+ userId: session.userId,
2567
+ passkeyId: input.passkeyId,
2568
+ nickname: input.nickname,
2569
+ signal
2570
+ });
2571
+ },
2572
+ (result) => {
2573
+ if (!result.ok) return;
2574
+ setPasskeys(
2575
+ (current) => current?.map((passkey) => passkey.id === result.passkey.id ? result.passkey : passkey)
2576
+ );
2577
+ }
2578
+ ),
2579
+ [baseUrl, busyResult, http, publishableKey, requireSession, runAction]
2580
+ );
2581
+ const deletePasskey$1 = useCallback(
2582
+ (input) => runAction(
2583
+ "mutate",
2584
+ busyResult("mutation"),
2585
+ async (signal) => {
2586
+ const session = await requireSession();
2587
+ if (sessionFailure(session)) return { ok: false, error: session };
2588
+ return deletePasskey({
2589
+ http,
2590
+ baseUrl,
2591
+ clientId: publishableKey,
2592
+ accessToken: session.accessToken,
2593
+ stepUpToken: input.stepUpToken,
2594
+ userId: session.userId,
2595
+ passkeyId: input.passkeyId,
2596
+ signal
2597
+ });
2598
+ },
2599
+ (result) => {
2600
+ if (result.ok) {
2601
+ setPasskeys((current) => current?.filter((passkey) => passkey.id !== input.passkeyId));
2602
+ }
2603
+ }
2604
+ ),
2605
+ [baseUrl, busyResult, http, publishableKey, requireSession, runAction]
2606
+ );
2607
+ return {
2608
+ isSupported,
2609
+ hasPlatformAuthenticator,
2610
+ passkeys,
2611
+ error,
2612
+ isSigningIn,
2613
+ isRegistering,
2614
+ isSteppingUp,
2615
+ isLoading,
2616
+ isMutating,
2617
+ signInWithPasskey,
2618
+ stepUpWithPasskey: stepUpWithPasskey$1,
2619
+ registerPasskey: registerPasskey$1,
2620
+ listPasskeys: listPasskeys$1,
2621
+ renamePasskey: renamePasskey$1,
2622
+ deletePasskey: deletePasskey$1
2623
+ };
2624
+ }
1922
2625
 
1923
2626
  // src/hooks/use-submit-oauth-tokens.ts
1924
2627
  function useSubmitOAuthTokens() {
@@ -2001,4 +2704,4 @@ function useMfa() {
2001
2704
  };
2002
2705
  }
2003
2706
 
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 };
2707
+ 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 };