@getpara/react-native-wallet 2.0.0-alpha.7 → 2.0.0-alpha.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ https://www.npmjs.com/package/@getpara/react-native-wallet
2
+
3
+ The `@getpara/react-native-wallet` package is Para's React Native SDK for building mobile wallet applications.
4
+
5
+ ###Key Features
6
+
7
+ - Native Passkey Authentication: Uses device biometrics and passkeys for secure wallet access
8
+ - Multi-blockchain Support: Works with EVM, Solana, and Cosmos networks
9
+ - Custom Storage: Supports MMKV for improved performance over AsyncStorage
10
+ - OAuth Integration: Supports social login with Google, Discord, and Farcaster
11
+ - Pregenerated Wallets: Create wallets before user authentication
12
+
13
+ ###Prerequisites
14
+
15
+ To use Para, you need an API key. This key authenticates your requests to Para services and is essential for integration.
16
+
17
+ Don't have an API key yet? Request access to the [Developer Portal](https://developer.getpara.com/) to create API keys, manage billing, teams, and more.
18
+
19
+ ###Learn more
20
+
21
+ For more information on Para’s React Native SDK visit the [Para Docs](https://docs.getpara.com/v2/react-native/setup/react-native)
package/dist/config.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import { Environment } from '@getpara/web-sdk';
2
+ declare function getPortalBaseURL(env: Environment): "http://localhost:3003" | "https://app.sandbox.usecapsule.com" | "https://app.beta.usecapsule.com" | "https://app.usecapsule.com";
3
+ declare function getBaseUrl(env: Environment): string;
2
4
  export declare function getBaseMPCNetworkWSUrl(env: Environment): string;
3
5
  export declare let userManagementServer: string;
4
6
  export declare let portalBase: string;
5
7
  export declare let mpcNetworkWSServer: string;
6
8
  export declare function setEnv(env: Environment): void;
7
9
  export declare const DEBUG_MODE_ENABLED = false;
10
+ export { getBaseUrl, getPortalBaseURL };
package/dist/config.js CHANGED
@@ -58,3 +58,4 @@ function init() {
58
58
  ParaSignerModule.setWsServerUrl(mpcNetworkWSServer);
59
59
  }
60
60
  init();
61
+ export { getBaseUrl, getPortalBaseURL };
@@ -11,13 +11,16 @@ export declare class ParaMobile extends ParaCore {
11
11
  private relyingPartyId;
12
12
  /**
13
13
  * Creates an instance of ParaMobile.
14
- * @param {Environment} env - The environment to use (DEV, SANDBOX, BETA, or PROD).
14
+ * @param {Environment} env - The environment to use (DEV, SANDBOX, BETA, or PROD). Optional if the apiKey contains an environment prefix (e.g., "prod_your_api_key"). Updated API keys can be found at https://developer.getpara.com.
15
15
  * @param {string} [apiKey] - The API key for authentication.
16
16
  * @param {string} [relyingPartyId] - The relying party ID for WebAuthn.
17
17
  * @param {ConstructorOpts} [opts] - Additional constructor options.
18
18
  */
19
- constructor(env: Environment, apiKey: string, relyingPartyId?: string, opts?: ConstructorOpts);
19
+ constructor(env: Environment | undefined, apiKey: string, relyingPartyId?: string, opts?: ConstructorOpts);
20
+ constructor(apiKey: string, relyingPartyId?: string, opts?: ConstructorOpts);
21
+ ready(): Promise<void>;
20
22
  protected getPlatformUtils(): PlatformUtils;
23
+ isPasskeySupported(): Promise<boolean>;
21
24
  /**
22
25
  * Registers a passkey for the user.
23
26
  * @param {Auth<'email'> | Auth<'phone'>} auth - The user's authentication details
@@ -8,10 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { ParaCore, Environment, decryptPrivateKeyAndDecryptShare, encryptPrivateKey, getAsymmetricKeyPair, getDerivedPrivateKeyAndDecrypt, getPublicKeyHex, getSHA256HashHex, parseCredentialCreationRes, } from '@getpara/web-sdk';
11
- import * as Sentry from '@sentry/react-native';
12
11
  import { ReactNativeUtils } from './ReactNativeUtils.js';
13
12
  import { Passkey, } from 'react-native-passkey';
14
- import { PublicKeyStatus } from '@getpara/user-management-client';
13
+ import { AuthMethodStatus } from '@getpara/user-management-client';
15
14
  import { setEnv } from '../config.js';
16
15
  import base64url from 'base64url';
17
16
  import { webcrypto } from 'crypto';
@@ -25,24 +24,61 @@ const RS256_ALGORITHM = -257;
25
24
  * const para = new ParaMobile(Environment.BETA, "api_key");
26
25
  */
27
26
  export class ParaMobile extends ParaCore {
28
- /**
29
- * Creates an instance of ParaMobile.
30
- * @param {Environment} env - The environment to use (DEV, SANDBOX, BETA, or PROD).
31
- * @param {string} [apiKey] - The API key for authentication.
32
- * @param {string} [relyingPartyId] - The relying party ID for WebAuthn.
33
- * @param {ConstructorOpts} [opts] - Additional constructor options.
34
- */
35
- constructor(env, apiKey, relyingPartyId, opts) {
27
+ constructor(envOrApiKey, apiKeyOrRelyingPartyId, relyingPartyIdOrOpts, optsArg) {
28
+ let env, apiKey, relyingPartyId, opts;
29
+ // Helper function to check if value is a valid Environment
30
+ const isEnvironment = (value) => {
31
+ return Object.values(Environment).includes(value);
32
+ };
33
+ if (arguments.length === 1) {
34
+ // 1-parameter case: (apiKey)
35
+ env = undefined;
36
+ apiKey = envOrApiKey;
37
+ relyingPartyId = undefined;
38
+ opts = undefined;
39
+ }
40
+ else if (arguments.length === 2) {
41
+ if (isEnvironment(envOrApiKey)) {
42
+ // 2-parameter case: (env, apiKey)
43
+ env = envOrApiKey;
44
+ apiKey = apiKeyOrRelyingPartyId;
45
+ relyingPartyId = undefined;
46
+ opts = undefined;
47
+ }
48
+ else {
49
+ // 2-parameter case: (apiKey, relyingPartyId)
50
+ env = undefined;
51
+ apiKey = envOrApiKey;
52
+ relyingPartyId = apiKeyOrRelyingPartyId;
53
+ opts = undefined;
54
+ }
55
+ }
56
+ else if (arguments.length === 3) {
57
+ if (isEnvironment(envOrApiKey)) {
58
+ // 3-parameter case: (env, apiKey, relyingPartyId)
59
+ env = envOrApiKey;
60
+ apiKey = apiKeyOrRelyingPartyId;
61
+ relyingPartyId = relyingPartyIdOrOpts;
62
+ opts = undefined;
63
+ }
64
+ else {
65
+ // 3-parameter case: (apiKey, relyingPartyId, opts)
66
+ env = undefined;
67
+ apiKey = envOrApiKey;
68
+ relyingPartyId = apiKeyOrRelyingPartyId;
69
+ opts = relyingPartyIdOrOpts;
70
+ }
71
+ }
72
+ else {
73
+ // 4-parameter case: (env, apiKey, relyingPartyId, opts)
74
+ env = envOrApiKey;
75
+ apiKey = apiKeyOrRelyingPartyId;
76
+ relyingPartyId = relyingPartyIdOrOpts;
77
+ opts = optsArg;
78
+ }
79
+ env = ParaCore.resolveEnvironment(env, apiKey); // Ensure the environment is resolved before calling super
36
80
  super(env, apiKey, opts);
37
81
  this.isNativePasskey = true;
38
- // starting with non-prod to see what kind of errors we get and if sensitive data is tracked
39
- // will turn on in prod after monitoring
40
- if (env !== Environment.PROD && env !== Environment.DEV) {
41
- Sentry.init({
42
- environment: env.toLowerCase(),
43
- dsn: 'https://59cea0cfbbb30a646c4e9f2feea06da4@o4504568036720640.ingest.us.sentry.io/4508850922323968',
44
- });
45
- }
46
82
  setEnv(env);
47
83
  if (relyingPartyId) {
48
84
  this.relyingPartyId = relyingPartyId;
@@ -63,9 +99,19 @@ export class ParaMobile extends ParaCore {
63
99
  }
64
100
  }
65
101
  }
102
+ ready() {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ this.isReady = true;
105
+ });
106
+ }
66
107
  getPlatformUtils() {
67
108
  return new ReactNativeUtils();
68
109
  }
110
+ isPasskeySupported() {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ return Passkey.isSupported();
113
+ });
114
+ }
69
115
  /**
70
116
  * Registers a passkey for the user.
71
117
  * @param {Auth<'email'> | Auth<'phone'>} auth - The user's authentication details
@@ -134,7 +180,7 @@ export class ParaMobile extends ParaCore {
134
180
  sigDerivedPublicKey: publicKeyHex,
135
181
  cosePublicKey,
136
182
  clientDataJSON,
137
- status: PublicKeyStatus.COMPLETE,
183
+ status: AuthMethodStatus.COMPLETE,
138
184
  });
139
185
  yield this.ctx.client.uploadEncryptedWalletPrivateKey(userId, encryptedPrivateKeyHex, encryptionKeyHash, resultJson.id);
140
186
  });
@@ -48,4 +48,5 @@ export declare class ReactNativeUtils implements PlatformUtils {
48
48
  walletId: string;
49
49
  }>;
50
50
  ed25519Sign(ctx: Ctx, userId: string, walletId: string, share: string, base64Bytes: string, _sessionCookie: string): Promise<SignatureRes>;
51
+ initializeWorker(_ctx: Ctx): Promise<void>;
51
52
  }
@@ -168,4 +168,9 @@ export class ReactNativeUtils {
168
168
  return { signature: base64Sig };
169
169
  });
170
170
  }
171
+ initializeWorker(_ctx) {
172
+ return __awaiter(this, void 0, void 0, function* () {
173
+ return;
174
+ });
175
+ }
171
176
  }
package/dist/shim.d.ts CHANGED
@@ -1 +1,130 @@
1
- export {};
1
+ export function ensureParaCrypto(): {
2
+ baseCrypto: webcrypto.Crypto | {
3
+ getCiphers: () => string[];
4
+ getHashes: () => string[];
5
+ webcrypto: {
6
+ subtle: import("react-native-quick-crypto/lib/typescript/src/subtle").Subtle;
7
+ SubtleCrypto: typeof import("react-native-quick-crypto/lib/typescript/src/subtle").Subtle;
8
+ CryptoKey: typeof import("react-native-quick-crypto/lib/typescript/src/keys").CryptoKey;
9
+ };
10
+ randomFill<T extends import("react-native-quick-crypto/lib/typescript/src/Utils").ABV>(buffer: T, callback: (err: Error | null, buf: T) => void): void;
11
+ randomFill<T extends import("react-native-quick-crypto/lib/typescript/src/Utils").ABV>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void;
12
+ randomFill<T extends import("react-native-quick-crypto/lib/typescript/src/Utils").ABV>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void;
13
+ randomFillSync<T extends import("react-native-quick-crypto/lib/typescript/src/Utils").ABV>(buffer: T, offset?: number, size?: number): T;
14
+ randomBytes(size: number): Buffer;
15
+ randomBytes(size: number, callback: (err: Error | null, buf?: Buffer) => void): void;
16
+ randomInt(max: number, callback: (err: Error | null, value: number) => void): void;
17
+ randomInt(max: number): number;
18
+ randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
19
+ randomInt(min: number, max: number): number;
20
+ getRandomValues(data: import("react-native-quick-crypto/lib/typescript/src/random").RandomTypedArrays): import("react-native-quick-crypto/lib/typescript/src/random").RandomTypedArrays;
21
+ randomUUID(): string;
22
+ rng: typeof import("react-native-quick-crypto/lib/typescript/src/random").randomBytes;
23
+ pseudoRandomBytes: typeof import("react-native-quick-crypto/lib/typescript/src/random").randomBytes;
24
+ prng: typeof import("react-native-quick-crypto/lib/typescript/src/random").randomBytes;
25
+ pbkdf2(password: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, salt: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey?: Buffer) => void): void;
26
+ pbkdf2Sync(password: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, salt: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, iterations: number, keylen: number, digest?: string): ArrayBuffer;
27
+ pbkdf2DeriveBits(algorithm: import("react-native-quick-crypto/lib/typescript/src/keys").SubtleAlgorithm, baseKey: import("react-native-quick-crypto/lib/typescript/src/keys").CryptoKey, length: number): Promise<ArrayBuffer>;
28
+ createHmac: typeof import("react-native-quick-crypto/lib/typescript/src/Hmac").createHmac;
29
+ Hmac: typeof import("react-native-quick-crypto/lib/typescript/src/Hmac").createHmac;
30
+ Hash: typeof import("react-native-quick-crypto/lib/typescript/src/Hash").createHash;
31
+ createHash: typeof import("react-native-quick-crypto/lib/typescript/src/Hash").createHash;
32
+ createCipher: typeof import("react-native-quick-crypto/lib/typescript/src/Cipher").createCipher;
33
+ createCipheriv: typeof import("react-native-quick-crypto/lib/typescript/src/Cipher").createCipheriv;
34
+ createDecipher: typeof import("react-native-quick-crypto/lib/typescript/src/Cipher").createDecipher;
35
+ createDecipheriv: typeof import("react-native-quick-crypto/lib/typescript/src/Cipher").createDecipheriv;
36
+ createPublicKey: typeof import("react-native-quick-crypto/lib/typescript/src/keys").createPublicKey;
37
+ createPrivateKey: (key: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike | import("react-native-quick-crypto/lib/typescript/src/keys").EncodingOptions) => import("react-native-quick-crypto/lib/typescript/src/keys").PrivateKeyObject;
38
+ createSecretKey: typeof import("react-native-quick-crypto/lib/typescript/src/keys").createSecretKey;
39
+ publicEncrypt: (options: import("react-native-quick-crypto/lib/typescript/src/keys").EncodingOptions | import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, buffer: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike) => Buffer;
40
+ publicDecrypt: (options: import("react-native-quick-crypto/lib/typescript/src/keys").EncodingOptions | import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, buffer: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike) => Buffer;
41
+ privateDecrypt: (options: import("react-native-quick-crypto/lib/typescript/src/keys").EncodingOptions | import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike, buffer: import("react-native-quick-crypto/lib/typescript/src/Utils").BinaryLike) => Buffer;
42
+ generateKey: (type: import("react-native-quick-crypto/lib/typescript/src/keys").SecretKeyType, options: import("react-native-quick-crypto/lib/typescript/src/keys").AesKeyGenParams, callback: import("react-native-quick-crypto/lib/typescript/src/keygen").KeyGenCallback) => void;
43
+ generateKeyPair: (type: import("react-native-quick-crypto/lib/typescript/src/keys").KeyPairType, options: import("react-native-quick-crypto/lib/typescript/src/Cipher").GenerateKeyPairOptions, callback: import("react-native-quick-crypto/lib/typescript/src/Cipher").GenerateKeyPairCallback) => void;
44
+ generateKeyPairSync: typeof import("react-native-quick-crypto/lib/typescript/src/Cipher").generateKeyPairSync;
45
+ generateKeySync: (type: import("react-native-quick-crypto/lib/typescript/src/keys").SecretKeyType, options: import("react-native-quick-crypto/lib/typescript/src/keys").AesKeyGenParams) => import("react-native-quick-crypto/lib/typescript/src/keys").SecretKeyObject;
46
+ createSign: typeof import("react-native-quick-crypto/lib/typescript/src/sig").createSign;
47
+ createVerify: typeof import("react-native-quick-crypto/lib/typescript/src/sig").createVerify;
48
+ subtle: import("react-native-quick-crypto/lib/typescript/src/subtle").Subtle;
49
+ constants: {
50
+ OPENSSL_VERSION_NUMBER: number;
51
+ SSL_OP_ALL: number;
52
+ SSL_OP_ALLOW_NO_DHE_KEX: number;
53
+ SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
54
+ SSL_OP_CIPHER_SERVER_PREFERENCE: number;
55
+ SSL_OP_CISCO_ANYCONNECT: number;
56
+ SSL_OP_COOKIE_EXCHANGE: number;
57
+ SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
58
+ SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
59
+ SSL_OP_EPHEMERAL_RSA: number;
60
+ SSL_OP_LEGACY_SERVER_CONNECT: number;
61
+ SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
62
+ SSL_OP_MICROSOFT_SESS_ID_BUG: number;
63
+ SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
64
+ SSL_OP_NETSCAPE_CA_DN_BUG: number;
65
+ SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
66
+ SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
67
+ SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
68
+ SSL_OP_NO_COMPRESSION: number;
69
+ SSL_OP_NO_ENCRYPT_THEN_MAC: number;
70
+ SSL_OP_NO_QUERY_MTU: number;
71
+ SSL_OP_NO_RENEGOTIATION: number;
72
+ SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
73
+ SSL_OP_NO_SSLv2: number;
74
+ SSL_OP_NO_SSLv3: number;
75
+ SSL_OP_NO_TICKET: number;
76
+ SSL_OP_NO_TLSv1: number;
77
+ SSL_OP_NO_TLSv1_1: number;
78
+ SSL_OP_NO_TLSv1_2: number;
79
+ SSL_OP_NO_TLSv1_3: number;
80
+ SSL_OP_PKCS1_CHECK_1: number;
81
+ SSL_OP_PKCS1_CHECK_2: number;
82
+ SSL_OP_PRIORITIZE_CHACHA: number;
83
+ SSL_OP_SINGLE_DH_USE: number;
84
+ SSL_OP_SINGLE_ECDH_USE: number;
85
+ SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
86
+ SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
87
+ SSL_OP_TLS_BLOCK_PADDING_BUG: number;
88
+ SSL_OP_TLS_D5_BUG: number;
89
+ SSL_OP_TLS_ROLLBACK_BUG: number;
90
+ ENGINE_METHOD_RSA: number;
91
+ ENGINE_METHOD_DSA: number;
92
+ ENGINE_METHOD_DH: number;
93
+ ENGINE_METHOD_RAND: number;
94
+ ENGINE_METHOD_EC: number;
95
+ ENGINE_METHOD_CIPHERS: number;
96
+ ENGINE_METHOD_DIGESTS: number;
97
+ ENGINE_METHOD_PKEY_METHS: number;
98
+ ENGINE_METHOD_PKEY_ASN1_METHS: number;
99
+ ENGINE_METHOD_ALL: number;
100
+ ENGINE_METHOD_NONE: number;
101
+ DH_CHECK_P_NOT_SAFE_PRIME: number;
102
+ DH_CHECK_P_NOT_PRIME: number;
103
+ DH_UNABLE_TO_CHECK_GENERATOR: number;
104
+ DH_NOT_SUITABLE_GENERATOR: number;
105
+ ALPN_ENABLED: number;
106
+ RSA_PKCS1_PADDING: number;
107
+ RSA_SSLV23_PADDING: number;
108
+ RSA_NO_PADDING: number;
109
+ RSA_PKCS1_OAEP_PADDING: number;
110
+ RSA_X931_PADDING: number;
111
+ RSA_PKCS1_PSS_PADDING: number;
112
+ RSA_PSS_SALTLEN_DIGEST: number;
113
+ RSA_PSS_SALTLEN_MAX_SIGN: number;
114
+ RSA_PSS_SALTLEN_AUTO: number;
115
+ defaultCoreCipherList: string;
116
+ TLS1_VERSION: number;
117
+ TLS1_1_VERSION: number;
118
+ TLS1_2_VERSION: number;
119
+ TLS1_3_VERSION: number;
120
+ POINT_CONVERSION_COMPRESSED: number;
121
+ POINT_CONVERSION_UNCOMPRESSED: number;
122
+ POINT_CONVERSION_HYBRID: number;
123
+ };
124
+ };
125
+ peculiarCrypto: PeculiarCrypto;
126
+ };
127
+ export function ensureCreateECDH(): any;
128
+ import { webcrypto } from 'crypto';
129
+ import { Buffer } from '@craftzdog/react-native-buffer';
130
+ import { Crypto as PeculiarCrypto } from '@peculiar/webcrypto';
package/dist/shim.js CHANGED
@@ -1,6 +1,7 @@
1
- import crypto from 'react-native-quick-crypto';
1
+ import quickCrypto from 'react-native-quick-crypto';
2
2
  import { webcrypto } from 'crypto';
3
- import { Crypto } from '@peculiar/webcrypto';
3
+ import { Crypto as PeculiarCrypto } from '@peculiar/webcrypto';
4
+ import { ec as EllipticEC } from 'elliptic';
4
5
  import Forge from 'node-forge';
5
6
  import modPow from 'react-native-modpow';
6
7
  import { atob, btoa } from 'react-native-quick-base64';
@@ -8,7 +9,37 @@ import { Buffer } from '@craftzdog/react-native-buffer';
8
9
  import process from 'process';
9
10
  import 'react-native-url-polyfill/auto';
10
11
  import { TextEncoder, TextDecoder } from 'text-encoding';
11
- import structuredClone from '@ungap/structured-clone';
12
+ let cachedStructuredCloneImpl;
13
+ const resolveStructuredClone = () => {
14
+ if (typeof cachedStructuredCloneImpl !== 'undefined') {
15
+ return cachedStructuredCloneImpl;
16
+ }
17
+ if (typeof globalThis.structuredClone === 'function') {
18
+ cachedStructuredCloneImpl = globalThis.structuredClone.bind(globalThis);
19
+ return cachedStructuredCloneImpl;
20
+ }
21
+ const isHermes = typeof globalThis.HermesInternal === 'object' && globalThis.HermesInternal !== null;
22
+ if (isHermes) {
23
+ // Hermes crashes when @ungap/structured-clone rewires Reflect helpers.
24
+ cachedStructuredCloneImpl = null;
25
+ return cachedStructuredCloneImpl;
26
+ }
27
+ try {
28
+ const maybePolyfill = require('@ungap/structured-clone');
29
+ const polyfill = (maybePolyfill && maybePolyfill.default) || maybePolyfill;
30
+ if (typeof polyfill === 'function') {
31
+ cachedStructuredCloneImpl = polyfill;
32
+ return cachedStructuredCloneImpl;
33
+ }
34
+ }
35
+ catch (err) {
36
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
37
+ console.warn('[Para React Native shim] Failed to load structuredClone polyfill', err);
38
+ }
39
+ }
40
+ cachedStructuredCloneImpl = null;
41
+ return cachedStructuredCloneImpl;
42
+ };
12
43
  const setupProcessPolyfill = () => {
13
44
  if (typeof globalThis.process === 'undefined') {
14
45
  globalThis.process = process;
@@ -33,16 +64,191 @@ const setupBase64Polyfills = () => {
33
64
  throw new Error('Base64 polyfills failed to initialize');
34
65
  }
35
66
  };
36
- const setupCryptoPolyfills = () => {
37
- const peculiarCrypto = new Crypto();
38
- if (typeof globalThis.crypto === 'undefined') {
39
- globalThis.crypto = crypto;
67
+ const curveAliases = {
68
+ 'P-256': 'p256',
69
+ 'p-256': 'p256',
70
+ 'prime256v1': 'p256',
71
+ 'secp256r1': 'p256',
72
+ 'secp256k1': 'secp256k1',
73
+ };
74
+ const getBufferImpl = () => {
75
+ const BufferImpl = globalThis.Buffer;
76
+ if (!BufferImpl) {
77
+ // prettier-ignore
78
+ throw new Error("[Para React Native shim] Buffer global missing. Please import '@getpara/react-native-wallet/shim' before using cryptography helpers.");
79
+ }
80
+ return BufferImpl;
81
+ };
82
+ const bufferFrom = (data, encoding = 'binary') => {
83
+ const BufferImpl = getBufferImpl();
84
+ if (BufferImpl.isBuffer && BufferImpl.isBuffer(data)) {
85
+ return data;
86
+ }
87
+ if (typeof data === 'string') {
88
+ switch (encoding) {
89
+ case 'hex':
90
+ return BufferImpl.from(data, 'hex');
91
+ case 'base64':
92
+ return BufferImpl.from(data, 'base64');
93
+ default:
94
+ return BufferImpl.from(data, 'binary');
95
+ }
96
+ }
97
+ return BufferImpl.from(data);
98
+ };
99
+ const bufferTo = (buf, encoding = 'binary') => {
100
+ const BufferImpl = getBufferImpl();
101
+ switch (encoding) {
102
+ case 'hex':
103
+ return BufferImpl.from(buf).toString('hex');
104
+ case 'base64':
105
+ return BufferImpl.from(buf).toString('base64');
106
+ case 'binary':
107
+ default:
108
+ return BufferImpl.from(buf);
109
+ }
110
+ };
111
+ let cachedCreateECDH = null;
112
+ const ensureCreateECDH = () => {
113
+ if (!cachedCreateECDH) {
114
+ cachedCreateECDH = curveName => {
115
+ const BufferImpl = getBufferImpl();
116
+ const normalizedCurve = curveAliases[curveName] || curveName;
117
+ if (!normalizedCurve && typeof __DEV__ !== 'undefined' && __DEV__) {
118
+ console.warn('[Para React Native shim] Unknown curve alias', curveName);
119
+ }
120
+ const ec = new EllipticEC(normalizedCurve);
121
+ const secretByteLength = (() => {
122
+ const order = (ec && ec.curve && ec.curve.n) || (ec && ec.n);
123
+ if (!order) {
124
+ return null;
125
+ }
126
+ if (typeof order.byteLength === 'function') {
127
+ return order.byteLength();
128
+ }
129
+ if (typeof order.bitLength === 'function') {
130
+ return Math.ceil(order.bitLength() / 8);
131
+ }
132
+ return null;
133
+ })();
134
+ let keyPair = ec.genKeyPair();
135
+ return {
136
+ generateKeys: (encoding = 'binary', format = 'uncompressed') => {
137
+ keyPair = ec.genKeyPair();
138
+ const compressed = format === 'compressed' || format === 'comp';
139
+ const publicKey = keyPair.getPublic(compressed, 'array');
140
+ return bufferTo(BufferImpl.from(publicKey), encoding || 'binary');
141
+ },
142
+ computeSecret: (publicKey, inputEncoding = 'binary', outputEncoding = 'binary') => {
143
+ const publicKeyBuf = bufferFrom(publicKey, inputEncoding || 'binary');
144
+ const derived = keyPair.derive(ec.keyFromPublic(publicKeyBuf).getPublic());
145
+ const padded = secretByteLength ? derived.toArray('be', secretByteLength) : derived.toArray('be');
146
+ // Match Node's ECDH API: shared secret is always curve-size bytes.
147
+ const secret = BufferImpl.from(padded);
148
+ return bufferTo(secret, outputEncoding || 'binary');
149
+ },
150
+ getPrivateKey: (encoding = 'binary') => {
151
+ return bufferTo(keyPair.getPrivate().toArrayLike(BufferImpl, 'be', 32), encoding || 'binary');
152
+ },
153
+ getPublicKey: (encoding = 'binary', format = 'uncompressed') => {
154
+ const compressed = format === 'compressed' || format === 'comp';
155
+ const publicKey = keyPair.getPublic(compressed, 'array');
156
+ return bufferTo(BufferImpl.from(publicKey), encoding || 'binary');
157
+ },
158
+ setPrivateKey: (privateKey, encoding = 'binary') => {
159
+ keyPair = ec.keyFromPrivate(bufferFrom(privateKey, encoding));
160
+ },
161
+ setPublicKey: (publicKey, encoding = 'binary') => {
162
+ keyPair = ec.keyFromPublic(bufferFrom(publicKey, encoding));
163
+ },
164
+ };
165
+ };
166
+ }
167
+ const possibleTargets = [];
168
+ const globalCrypto = globalThis.crypto;
169
+ if (globalCrypto) {
170
+ possibleTargets.push(globalCrypto, globalCrypto.default);
40
171
  }
41
- if (!globalThis.crypto.subtle) {
42
- globalThis.crypto.subtle = peculiarCrypto.subtle;
43
- globalThis.crypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
172
+ possibleTargets.push(quickCrypto, quickCrypto && quickCrypto.default);
173
+ try {
174
+ const nodeCrypto = require('crypto');
175
+ possibleTargets.push(nodeCrypto, nodeCrypto && nodeCrypto.default);
176
+ // eslint-disable-next-line no-unused-vars
177
+ }
178
+ catch (_err) {
179
+ // The Node crypto module is not available in React Native; ignore failures.
180
+ }
181
+ const patchedTargets = new Set(possibleTargets.filter(Boolean));
182
+ let patched = false;
183
+ patchedTargets.forEach(target => {
184
+ if (target && typeof target === 'object' && target.createECDH !== cachedCreateECDH) {
185
+ try {
186
+ target.createECDH = cachedCreateECDH;
187
+ patched = true;
188
+ }
189
+ catch (err) {
190
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
191
+ console.warn('[Para React Native shim] Failed to patch createECDH', err);
192
+ }
193
+ }
194
+ }
195
+ });
196
+ if (patched && typeof __DEV__ !== 'undefined' && __DEV__) {
197
+ console.info('[Para React Native shim] createECDH patched function');
198
+ }
199
+ return cachedCreateECDH;
200
+ };
201
+ const syncWindowLikeGlobals = cryptoObj => {
202
+ const maybeWindow = globalThis.window;
203
+ if (maybeWindow && typeof maybeWindow === 'object' && maybeWindow.crypto !== cryptoObj) {
204
+ maybeWindow.crypto = cryptoObj;
205
+ }
206
+ const maybeSelf = globalThis.self;
207
+ if (maybeSelf && typeof maybeSelf === 'object' && maybeSelf.crypto !== cryptoObj) {
208
+ maybeSelf.crypto = cryptoObj;
209
+ }
210
+ };
211
+ const ensureParaCrypto = () => {
212
+ getBufferImpl();
213
+ const baseCrypto = (typeof globalThis.crypto === 'object' && globalThis.crypto) || quickCrypto;
214
+ if (!baseCrypto || typeof baseCrypto !== 'object') {
215
+ throw new Error('[Para React Native shim] No crypto object found to polyfill');
216
+ }
217
+ if (typeof baseCrypto.default === 'undefined') {
218
+ baseCrypto.default = baseCrypto;
219
+ }
220
+ const peculiarCrypto = new PeculiarCrypto();
221
+ baseCrypto.subtle = peculiarCrypto.subtle;
222
+ baseCrypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
223
+ if (baseCrypto.default && baseCrypto.default !== baseCrypto) {
224
+ baseCrypto.default.subtle = baseCrypto.subtle;
225
+ baseCrypto.default.getRandomValues = baseCrypto.getRandomValues;
226
+ }
227
+ globalThis.crypto = baseCrypto;
228
+ syncWindowLikeGlobals(baseCrypto);
229
+ try {
230
+ const brorand = require('brorand');
231
+ if (brorand && brorand.Rand) {
232
+ brorand.Rand.prototype._rand = function _rand(n) {
233
+ const arr = new Uint8Array(n);
234
+ baseCrypto.getRandomValues(arr);
235
+ return arr;
236
+ };
237
+ }
238
+ }
239
+ catch (err) {
240
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
241
+ console.warn('[Para React Native shim] Failed to patch brorand RNG', err);
242
+ }
243
+ }
244
+ ensureCreateECDH();
245
+ return { baseCrypto, peculiarCrypto };
246
+ };
247
+ const setupCryptoPolyfills = () => {
248
+ const { peculiarCrypto } = ensureParaCrypto();
249
+ if (webcrypto && typeof webcrypto === 'object') {
250
+ webcrypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
44
251
  }
45
- webcrypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
46
252
  if (typeof Forge === 'undefined') {
47
253
  throw new Error('node-forge not loaded');
48
254
  }
@@ -63,9 +269,37 @@ const setupTextEncodingPolyfills = () => {
63
269
  globalThis.TextDecoder = TextDecoder;
64
270
  };
65
271
  const setupStructuredClonePolyfill = () => {
66
- if (typeof globalThis.structuredClone === 'undefined') {
67
- globalThis.structuredClone = structuredClone;
272
+ if (typeof globalThis.structuredClone === 'function') {
273
+ return;
68
274
  }
275
+ const structuredCloneImpl = resolveStructuredClone();
276
+ const safeStructuredClone = (value, options) => {
277
+ if (typeof structuredCloneImpl === 'function') {
278
+ try {
279
+ return structuredCloneImpl(value, options);
280
+ }
281
+ catch (err) {
282
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
283
+ console.warn('[Para React Native shim] structuredClone polyfill failed, falling back to JSON clone', err);
284
+ }
285
+ }
286
+ }
287
+ try {
288
+ return JSON.parse(JSON.stringify(value));
289
+ }
290
+ catch (_err) {
291
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
292
+ console.warn('[Para React Native shim] JSON clone failed, returning original value', _err);
293
+ }
294
+ return value;
295
+ }
296
+ };
297
+ Object.defineProperty(globalThis, 'structuredClone', {
298
+ value: safeStructuredClone,
299
+ configurable: true,
300
+ enumerable: false,
301
+ writable: true,
302
+ });
69
303
  };
70
304
  setupProcessPolyfill();
71
305
  setupBufferPolyfill();
@@ -73,3 +307,4 @@ setupBase64Polyfills();
73
307
  setupCryptoPolyfills();
74
308
  setupTextEncodingPolyfills();
75
309
  setupStructuredClonePolyfill();
310
+ export { ensureParaCrypto, ensureCreateECDH };
package/package.json CHANGED
@@ -1,32 +1,14 @@
1
1
  {
2
2
  "name": "@getpara/react-native-wallet",
3
- "version": "2.0.0-alpha.7",
4
3
  "description": "Para Wallet for React Native",
5
- "homepage": "https://getpara.com",
4
+ "version": "2.0.0-alpha.71",
6
5
  "author": "Para Team <hello@getpara.com> (https://getpara.com)",
7
- "main": "dist/index.js",
8
- "module": "dist/index.js",
9
- "types": "dist/index.d.ts",
10
- "files": [
11
- "dist",
12
- "src",
13
- "ios",
14
- "android",
15
- "cpp",
16
- "*.podspec",
17
- "signer.xcframework",
18
- "signer.aar"
19
- ],
20
- "scripts": {
21
- "build": "rm -rf dist && tsc",
22
- "compile-signer": "bash ./scripts/compileSigner.sh"
23
- },
24
6
  "dependencies": {
25
- "@getpara/core-sdk": "2.0.0-alpha.7",
26
- "@getpara/user-management-client": "2.0.0-alpha.7",
27
- "@getpara/web-sdk": "2.0.0-alpha.7",
7
+ "@getpara/core-sdk": "2.0.0-alpha.71",
8
+ "@getpara/user-management-client": "2.0.0-alpha.71",
9
+ "@getpara/web-sdk": "2.0.0-alpha.71",
28
10
  "@peculiar/webcrypto": "^1.5.0",
29
- "@sentry/react-native": "^6.10.0",
11
+ "@ungap/structured-clone": "1.3.0",
30
12
  "node-forge": "1.3.1",
31
13
  "react-native-url-polyfill": "2.0.0",
32
14
  "text-encoding": "0.7.0"
@@ -43,8 +25,32 @@
43
25
  "react-native-passkey": "3.1.0",
44
26
  "react-native-quick-base64": "2.1.2",
45
27
  "react-native-quick-crypto": "0.7.12",
46
- "typescript": "^5.4.3"
28
+ "typescript": "^5.8.3"
47
29
  },
30
+ "exports": {
31
+ ".": {
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./shim": {
35
+ "default": "./dist/shim.js"
36
+ },
37
+ "./dist/shim.js": {
38
+ "default": "./dist/shim.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "src",
44
+ "ios",
45
+ "android",
46
+ "cpp",
47
+ "*.podspec",
48
+ "signer.xcframework",
49
+ "signer.aar"
50
+ ],
51
+ "homepage": "https://getpara.com",
52
+ "main": "./dist/index.js",
53
+ "module": "./dist/index.js",
48
54
  "peerDependencies": {
49
55
  "@craftzdog/react-native-buffer": "*",
50
56
  "@react-native-async-storage/async-storage": "*",
@@ -60,5 +66,32 @@
60
66
  "publishConfig": {
61
67
  "access": "public"
62
68
  },
63
- "gitHead": "0a6b297b70c7f9b7b93381944e3f5314252ad6a5"
69
+ "react-native": {
70
+ ".": "./dist/index.js",
71
+ "./shim": "./dist/shim.js",
72
+ "./dist/shim.js": "./dist/shim.js"
73
+ },
74
+ "scripts": {
75
+ "build": "rm -rf dist && tsc",
76
+ "compile-signer": "bash ./scripts/compileSigner.sh",
77
+ "test": "vitest run --coverage"
78
+ },
79
+ "sideEffects": [
80
+ "./dist/shim.js"
81
+ ],
82
+ "types": "./dist/index.d.ts",
83
+ "typesVersions": {
84
+ "*": {
85
+ "shim": [
86
+ "./dist/shim.d.ts"
87
+ ],
88
+ "dist/shim.js": [
89
+ "./dist/shim.d.ts"
90
+ ],
91
+ "*": [
92
+ "./dist/index.d.ts"
93
+ ]
94
+ }
95
+ },
96
+ "gitHead": "30e5bad6a141f1b56959432f11aaf1536b84dece"
64
97
  }
@@ -2,6 +2,7 @@ require "json"
2
2
 
3
3
  package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
4
  folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
5
+ new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1'
5
6
 
6
7
  Pod::Spec.new do |s|
7
8
  s.name = "para-react-native-wallet"
@@ -19,8 +20,9 @@ Pod::Spec.new do |s|
19
20
 
20
21
  s.dependency "React-Core"
21
22
 
22
- # Don't install the dependencies when we run `pod install` in the old architecture.
23
- if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
23
+ if respond_to?(:install_modules_dependencies, true)
24
+ install_modules_dependencies(s)
25
+ elsif new_arch_enabled
24
26
  s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
25
27
  s.pod_target_xcconfig = {
26
28
  "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
@@ -33,4 +35,4 @@ Pod::Spec.new do |s|
33
35
  s.dependency "RCTTypeSafety"
34
36
  s.dependency "ReactCommon/turbomodule/core"
35
37
  end
36
- end
38
+ end
package/src/config.ts CHANGED
@@ -66,3 +66,5 @@ function init() {
66
66
  }
67
67
 
68
68
  init();
69
+
70
+ export { getBaseUrl, getPortalBaseURL };
@@ -13,7 +13,6 @@ import {
13
13
  getSHA256HashHex,
14
14
  parseCredentialCreationRes,
15
15
  } from '@getpara/web-sdk';
16
- import * as Sentry from '@sentry/react-native';
17
16
 
18
17
  import { ReactNativeUtils } from './ReactNativeUtils.js';
19
18
  import {
@@ -23,7 +22,7 @@ import {
23
22
  PasskeyGetRequest,
24
23
  PasskeyGetResult,
25
24
  } from 'react-native-passkey';
26
- import { CurrentWalletIds, PublicKeyStatus, TWalletScheme } from '@getpara/user-management-client';
25
+ import { CurrentWalletIds, AuthMethodStatus, TWalletScheme } from '@getpara/user-management-client';
27
26
  import { setEnv } from '../config.js';
28
27
  import base64url from 'base64url';
29
28
  import { webcrypto } from 'crypto';
@@ -44,23 +43,72 @@ export class ParaMobile extends ParaCore {
44
43
  private relyingPartyId: string;
45
44
  /**
46
45
  * Creates an instance of ParaMobile.
47
- * @param {Environment} env - The environment to use (DEV, SANDBOX, BETA, or PROD).
46
+ * @param {Environment} env - The environment to use (DEV, SANDBOX, BETA, or PROD). Optional if the apiKey contains an environment prefix (e.g., "prod_your_api_key"). Updated API keys can be found at https://developer.getpara.com.
48
47
  * @param {string} [apiKey] - The API key for authentication.
49
48
  * @param {string} [relyingPartyId] - The relying party ID for WebAuthn.
50
49
  * @param {ConstructorOpts} [opts] - Additional constructor options.
51
50
  */
52
- constructor(env: Environment, apiKey: string, relyingPartyId?: string, opts?: ConstructorOpts) {
53
- super(env, apiKey, opts);
51
+ constructor(env: Environment | undefined, apiKey: string, relyingPartyId?: string, opts?: ConstructorOpts);
52
+ constructor(apiKey: string, relyingPartyId?: string, opts?: ConstructorOpts);
53
+ constructor(
54
+ envOrApiKey: Environment | undefined | string,
55
+ apiKeyOrRelyingPartyId?: string,
56
+ relyingPartyIdOrOpts?: string | ConstructorOpts,
57
+ optsArg?: ConstructorOpts,
58
+ ) {
59
+ let env: Environment | undefined, apiKey: string, relyingPartyId: string | undefined, opts: ConstructorOpts | undefined;
60
+
61
+ // Helper function to check if value is a valid Environment
62
+ const isEnvironment = (value: any): value is Environment => {
63
+ return Object.values(Environment).includes(value);
64
+ };
54
65
 
55
- // starting with non-prod to see what kind of errors we get and if sensitive data is tracked
56
- // will turn on in prod after monitoring
57
- if (env !== Environment.PROD && env !== Environment.DEV) {
58
- Sentry.init({
59
- environment: env.toLowerCase(),
60
- dsn: 'https://59cea0cfbbb30a646c4e9f2feea06da4@o4504568036720640.ingest.us.sentry.io/4508850922323968',
61
- });
66
+ if (arguments.length === 1) {
67
+ // 1-parameter case: (apiKey)
68
+ env = undefined;
69
+ apiKey = envOrApiKey as string;
70
+ relyingPartyId = undefined;
71
+ opts = undefined;
72
+ } else if (arguments.length === 2) {
73
+ if (isEnvironment(envOrApiKey)) {
74
+ // 2-parameter case: (env, apiKey)
75
+ env = envOrApiKey;
76
+ apiKey = apiKeyOrRelyingPartyId as string;
77
+ relyingPartyId = undefined;
78
+ opts = undefined;
79
+ } else {
80
+ // 2-parameter case: (apiKey, relyingPartyId)
81
+ env = undefined;
82
+ apiKey = envOrApiKey as string;
83
+ relyingPartyId = apiKeyOrRelyingPartyId;
84
+ opts = undefined;
85
+ }
86
+ } else if (arguments.length === 3) {
87
+ if (isEnvironment(envOrApiKey)) {
88
+ // 3-parameter case: (env, apiKey, relyingPartyId)
89
+ env = envOrApiKey;
90
+ apiKey = apiKeyOrRelyingPartyId as string;
91
+ relyingPartyId = relyingPartyIdOrOpts as string;
92
+ opts = undefined;
93
+ } else {
94
+ // 3-parameter case: (apiKey, relyingPartyId, opts)
95
+ env = undefined;
96
+ apiKey = envOrApiKey as string;
97
+ relyingPartyId = apiKeyOrRelyingPartyId;
98
+ opts = relyingPartyIdOrOpts as ConstructorOpts;
99
+ }
100
+ } else {
101
+ // 4-parameter case: (env, apiKey, relyingPartyId, opts)
102
+ env = envOrApiKey as Environment | undefined;
103
+ apiKey = apiKeyOrRelyingPartyId as string;
104
+ relyingPartyId = relyingPartyIdOrOpts as string | undefined;
105
+ opts = optsArg;
62
106
  }
63
107
 
108
+ env = ParaCore.resolveEnvironment(env, apiKey); // Ensure the environment is resolved before calling super
109
+
110
+ super(env, apiKey, opts);
111
+
64
112
  setEnv(env);
65
113
 
66
114
  if (relyingPartyId) {
@@ -82,10 +130,18 @@ export class ParaMobile extends ParaCore {
82
130
  }
83
131
  }
84
132
 
133
+ async ready() {
134
+ this.isReady = true;
135
+ }
136
+
85
137
  protected getPlatformUtils(): PlatformUtils {
86
138
  return new ReactNativeUtils();
87
139
  }
88
140
 
141
+ async isPasskeySupported(): Promise<boolean> {
142
+ return Passkey.isSupported();
143
+ }
144
+
89
145
  /**
90
146
  * Registers a passkey for the user.
91
147
  * @param {Auth<'email'> | Auth<'phone'>} auth - The user's authentication details
@@ -161,7 +217,7 @@ export class ParaMobile extends ParaCore {
161
217
  sigDerivedPublicKey: publicKeyHex,
162
218
  cosePublicKey,
163
219
  clientDataJSON,
164
- status: PublicKeyStatus.COMPLETE,
220
+ status: AuthMethodStatus.COMPLETE,
165
221
  });
166
222
 
167
223
  await this.ctx.client.uploadEncryptedWalletPrivateKey(userId, encryptedPrivateKeyHex, encryptionKeyHash, resultJson.id);
@@ -234,7 +290,7 @@ export class ParaMobile extends ParaCore {
234
290
  decryptedShares = await decryptPrivateKeyAndDecryptShare(
235
291
  resultJson.response.userHandle,
236
292
  encryptedSharesResult.data.keyShares,
237
- encryptedPrivateKeys[0].encryptedPrivateKey,
293
+ encryptedPrivateKeys[0]!.encryptedPrivateKey,
238
294
  );
239
295
  }
240
296
 
@@ -262,4 +262,8 @@ export class ReactNativeUtils implements PlatformUtils {
262
262
  const base64Sig = await ParaSignerModule.ed25519Sign(protocolId, share, base64Bytes);
263
263
  return { signature: base64Sig };
264
264
  }
265
+
266
+ async initializeWorker(_ctx: Ctx): Promise<void> {
267
+ return;
268
+ }
265
269
  }
package/src/shim.js CHANGED
@@ -1,6 +1,7 @@
1
- import crypto from 'react-native-quick-crypto';
1
+ import quickCrypto from 'react-native-quick-crypto';
2
2
  import { webcrypto } from 'crypto';
3
- import { Crypto } from '@peculiar/webcrypto';
3
+ import { Crypto as PeculiarCrypto } from '@peculiar/webcrypto';
4
+ import { ec as EllipticEC } from 'elliptic';
4
5
  import Forge from 'node-forge';
5
6
  import modPow from 'react-native-modpow';
6
7
  import { atob, btoa } from 'react-native-quick-base64';
@@ -8,7 +9,42 @@ import { Buffer } from '@craftzdog/react-native-buffer';
8
9
  import process from 'process';
9
10
  import 'react-native-url-polyfill/auto';
10
11
  import { TextEncoder, TextDecoder } from 'text-encoding';
11
- import structuredClone from '@ungap/structured-clone';
12
+
13
+ let cachedStructuredCloneImpl;
14
+
15
+ const resolveStructuredClone = () => {
16
+ if (typeof cachedStructuredCloneImpl !== 'undefined') {
17
+ return cachedStructuredCloneImpl;
18
+ }
19
+
20
+ if (typeof globalThis.structuredClone === 'function') {
21
+ cachedStructuredCloneImpl = globalThis.structuredClone.bind(globalThis);
22
+ return cachedStructuredCloneImpl;
23
+ }
24
+
25
+ const isHermes = typeof globalThis.HermesInternal === 'object' && globalThis.HermesInternal !== null;
26
+ if (isHermes) {
27
+ // Hermes crashes when @ungap/structured-clone rewires Reflect helpers.
28
+ cachedStructuredCloneImpl = null;
29
+ return cachedStructuredCloneImpl;
30
+ }
31
+
32
+ try {
33
+ const maybePolyfill = require('@ungap/structured-clone');
34
+ const polyfill = (maybePolyfill && maybePolyfill.default) || maybePolyfill;
35
+ if (typeof polyfill === 'function') {
36
+ cachedStructuredCloneImpl = polyfill;
37
+ return cachedStructuredCloneImpl;
38
+ }
39
+ } catch (err) {
40
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
41
+ console.warn('[Para React Native shim] Failed to load structuredClone polyfill', err);
42
+ }
43
+ }
44
+
45
+ cachedStructuredCloneImpl = null;
46
+ return cachedStructuredCloneImpl;
47
+ };
12
48
 
13
49
  const setupProcessPolyfill = () => {
14
50
  if (typeof globalThis.process === 'undefined') {
@@ -37,16 +73,218 @@ const setupBase64Polyfills = () => {
37
73
  }
38
74
  };
39
75
 
40
- const setupCryptoPolyfills = () => {
41
- const peculiarCrypto = new Crypto();
42
- if (typeof globalThis.crypto === 'undefined') {
43
- globalThis.crypto = crypto;
76
+ const curveAliases = {
77
+ 'P-256': 'p256',
78
+ 'p-256': 'p256',
79
+ 'prime256v1': 'p256',
80
+ 'secp256r1': 'p256',
81
+ 'secp256k1': 'secp256k1',
82
+ };
83
+
84
+ const getBufferImpl = () => {
85
+ const BufferImpl = globalThis.Buffer;
86
+ if (!BufferImpl) {
87
+ // prettier-ignore
88
+ throw new Error(
89
+ "[Para React Native shim] Buffer global missing. Please import '@getpara/react-native-wallet/shim' before using cryptography helpers."
90
+ );
91
+ }
92
+ return BufferImpl;
93
+ };
94
+
95
+ const bufferFrom = (data, encoding = 'binary') => {
96
+ const BufferImpl = getBufferImpl();
97
+ if (BufferImpl.isBuffer && BufferImpl.isBuffer(data)) {
98
+ return data;
99
+ }
100
+
101
+ if (typeof data === 'string') {
102
+ switch (encoding) {
103
+ case 'hex':
104
+ return BufferImpl.from(data, 'hex');
105
+ case 'base64':
106
+ return BufferImpl.from(data, 'base64');
107
+ default:
108
+ return BufferImpl.from(data, 'binary');
109
+ }
110
+ }
111
+
112
+ return BufferImpl.from(data);
113
+ };
114
+
115
+ const bufferTo = (buf, encoding = 'binary') => {
116
+ const BufferImpl = getBufferImpl();
117
+ switch (encoding) {
118
+ case 'hex':
119
+ return BufferImpl.from(buf).toString('hex');
120
+ case 'base64':
121
+ return BufferImpl.from(buf).toString('base64');
122
+ case 'binary':
123
+ default:
124
+ return BufferImpl.from(buf);
125
+ }
126
+ };
127
+
128
+ let cachedCreateECDH = null;
129
+
130
+ const ensureCreateECDH = () => {
131
+ if (!cachedCreateECDH) {
132
+ cachedCreateECDH = curveName => {
133
+ const BufferImpl = getBufferImpl();
134
+ const normalizedCurve = curveAliases[curveName] || curveName;
135
+ if (!normalizedCurve && typeof __DEV__ !== 'undefined' && __DEV__) {
136
+ console.warn('[Para React Native shim] Unknown curve alias', curveName);
137
+ }
138
+
139
+ const ec = new EllipticEC(normalizedCurve);
140
+ const secretByteLength = (() => {
141
+ const order = (ec && ec.curve && ec.curve.n) || (ec && ec.n);
142
+ if (!order) {
143
+ return null;
144
+ }
145
+ if (typeof order.byteLength === 'function') {
146
+ return order.byteLength();
147
+ }
148
+ if (typeof order.bitLength === 'function') {
149
+ return Math.ceil(order.bitLength() / 8);
150
+ }
151
+ return null;
152
+ })();
153
+ let keyPair = ec.genKeyPair();
154
+
155
+ return {
156
+ generateKeys: (encoding = 'binary', format = 'uncompressed') => {
157
+ keyPair = ec.genKeyPair();
158
+ const compressed = format === 'compressed' || format === 'comp';
159
+ const publicKey = keyPair.getPublic(compressed, 'array');
160
+ return bufferTo(BufferImpl.from(publicKey), encoding || 'binary');
161
+ },
162
+ computeSecret: (publicKey, inputEncoding = 'binary', outputEncoding = 'binary') => {
163
+ const publicKeyBuf = bufferFrom(publicKey, inputEncoding || 'binary');
164
+ const derived = keyPair.derive(ec.keyFromPublic(publicKeyBuf).getPublic());
165
+ const padded = secretByteLength ? derived.toArray('be', secretByteLength) : derived.toArray('be');
166
+ // Match Node's ECDH API: shared secret is always curve-size bytes.
167
+ const secret = BufferImpl.from(padded);
168
+ return bufferTo(secret, outputEncoding || 'binary');
169
+ },
170
+ getPrivateKey: (encoding = 'binary') => {
171
+ return bufferTo(keyPair.getPrivate().toArrayLike(BufferImpl, 'be', 32), encoding || 'binary');
172
+ },
173
+ getPublicKey: (encoding = 'binary', format = 'uncompressed') => {
174
+ const compressed = format === 'compressed' || format === 'comp';
175
+ const publicKey = keyPair.getPublic(compressed, 'array');
176
+ return bufferTo(BufferImpl.from(publicKey), encoding || 'binary');
177
+ },
178
+ setPrivateKey: (privateKey, encoding = 'binary') => {
179
+ keyPair = ec.keyFromPrivate(bufferFrom(privateKey, encoding));
180
+ },
181
+ setPublicKey: (publicKey, encoding = 'binary') => {
182
+ keyPair = ec.keyFromPublic(bufferFrom(publicKey, encoding));
183
+ },
184
+ };
185
+ };
186
+ }
187
+
188
+ const possibleTargets = [];
189
+ const globalCrypto = globalThis.crypto;
190
+ if (globalCrypto) {
191
+ possibleTargets.push(globalCrypto, globalCrypto.default);
192
+ }
193
+ possibleTargets.push(quickCrypto, quickCrypto && quickCrypto.default);
194
+
195
+ try {
196
+ const nodeCrypto = require('crypto');
197
+ possibleTargets.push(nodeCrypto, nodeCrypto && nodeCrypto.default);
198
+ // eslint-disable-next-line no-unused-vars
199
+ } catch (_err) {
200
+ // The Node crypto module is not available in React Native; ignore failures.
44
201
  }
45
- if (!globalThis.crypto.subtle) {
46
- globalThis.crypto.subtle = peculiarCrypto.subtle;
47
- globalThis.crypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
202
+
203
+ const patchedTargets = new Set(possibleTargets.filter(Boolean));
204
+ let patched = false;
205
+
206
+ patchedTargets.forEach(target => {
207
+ if (target && typeof target === 'object' && target.createECDH !== cachedCreateECDH) {
208
+ try {
209
+ target.createECDH = cachedCreateECDH;
210
+ patched = true;
211
+ } catch (err) {
212
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
213
+ console.warn('[Para React Native shim] Failed to patch createECDH', err);
214
+ }
215
+ }
216
+ }
217
+ });
218
+
219
+ if (patched && typeof __DEV__ !== 'undefined' && __DEV__) {
220
+ console.info('[Para React Native shim] createECDH patched function');
221
+ }
222
+
223
+ return cachedCreateECDH;
224
+ };
225
+
226
+ const syncWindowLikeGlobals = cryptoObj => {
227
+ const maybeWindow = globalThis.window;
228
+ if (maybeWindow && typeof maybeWindow === 'object' && maybeWindow.crypto !== cryptoObj) {
229
+ maybeWindow.crypto = cryptoObj;
230
+ }
231
+
232
+ const maybeSelf = globalThis.self;
233
+ if (maybeSelf && typeof maybeSelf === 'object' && maybeSelf.crypto !== cryptoObj) {
234
+ maybeSelf.crypto = cryptoObj;
48
235
  }
49
- webcrypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
236
+ };
237
+
238
+ const ensureParaCrypto = () => {
239
+ getBufferImpl();
240
+ const baseCrypto = (typeof globalThis.crypto === 'object' && globalThis.crypto) || quickCrypto;
241
+
242
+ if (!baseCrypto || typeof baseCrypto !== 'object') {
243
+ throw new Error('[Para React Native shim] No crypto object found to polyfill');
244
+ }
245
+
246
+ if (typeof baseCrypto.default === 'undefined') {
247
+ baseCrypto.default = baseCrypto;
248
+ }
249
+
250
+ const peculiarCrypto = new PeculiarCrypto();
251
+
252
+ baseCrypto.subtle = peculiarCrypto.subtle;
253
+ baseCrypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
254
+
255
+ if (baseCrypto.default && baseCrypto.default !== baseCrypto) {
256
+ baseCrypto.default.subtle = baseCrypto.subtle;
257
+ baseCrypto.default.getRandomValues = baseCrypto.getRandomValues;
258
+ }
259
+
260
+ globalThis.crypto = baseCrypto;
261
+ syncWindowLikeGlobals(baseCrypto);
262
+ try {
263
+ const brorand = require('brorand');
264
+ if (brorand && brorand.Rand) {
265
+ brorand.Rand.prototype._rand = function _rand(n) {
266
+ const arr = new Uint8Array(n);
267
+ baseCrypto.getRandomValues(arr);
268
+ return arr;
269
+ };
270
+ }
271
+ } catch (err) {
272
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
273
+ console.warn('[Para React Native shim] Failed to patch brorand RNG', err);
274
+ }
275
+ }
276
+ ensureCreateECDH();
277
+
278
+ return { baseCrypto, peculiarCrypto };
279
+ };
280
+
281
+ const setupCryptoPolyfills = () => {
282
+ const { peculiarCrypto } = ensureParaCrypto();
283
+
284
+ if (webcrypto && typeof webcrypto === 'object') {
285
+ webcrypto.getRandomValues = peculiarCrypto.getRandomValues.bind(peculiarCrypto);
286
+ }
287
+
50
288
  if (typeof Forge === 'undefined') {
51
289
  throw new Error('node-forge not loaded');
52
290
  }
@@ -69,9 +307,37 @@ const setupTextEncodingPolyfills = () => {
69
307
  };
70
308
 
71
309
  const setupStructuredClonePolyfill = () => {
72
- if (typeof globalThis.structuredClone === 'undefined') {
73
- globalThis.structuredClone = structuredClone;
310
+ if (typeof globalThis.structuredClone === 'function') {
311
+ return;
74
312
  }
313
+
314
+ const structuredCloneImpl = resolveStructuredClone();
315
+ const safeStructuredClone = (value, options) => {
316
+ if (typeof structuredCloneImpl === 'function') {
317
+ try {
318
+ return structuredCloneImpl(value, options);
319
+ } catch (err) {
320
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
321
+ console.warn('[Para React Native shim] structuredClone polyfill failed, falling back to JSON clone', err);
322
+ }
323
+ }
324
+ }
325
+ try {
326
+ return JSON.parse(JSON.stringify(value));
327
+ } catch (_err) {
328
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
329
+ console.warn('[Para React Native shim] JSON clone failed, returning original value', _err);
330
+ }
331
+ return value;
332
+ }
333
+ };
334
+
335
+ Object.defineProperty(globalThis, 'structuredClone', {
336
+ value: safeStructuredClone,
337
+ configurable: true,
338
+ enumerable: false,
339
+ writable: true,
340
+ });
75
341
  };
76
342
 
77
343
  setupProcessPolyfill();
@@ -80,3 +346,5 @@ setupBase64Polyfills();
80
346
  setupCryptoPolyfills();
81
347
  setupTextEncodingPolyfills();
82
348
  setupStructuredClonePolyfill();
349
+
350
+ export { ensureParaCrypto, ensureCreateECDH };
File without changes