|
| 1 | +import { requireNativeModule } from 'expo-modules-core' |
| 2 | +import type { SecureEnvironment } from './SecureEnvironment' |
| 3 | + |
| 4 | +type UnwrapPromiseReturnTypes<T, ExcludedKey extends keyof T = never> = { |
| 5 | + [K in keyof T]: K extends ExcludedKey |
| 6 | + ? T[K] |
| 7 | + : T[K] extends (...args: infer A) => Promise<infer R> | infer S |
| 8 | + ? (...args: A) => Promise<R> extends Promise<infer U> ? U : Promise<R> | S |
| 9 | + : T[K] |
| 10 | +} |
| 11 | + |
| 12 | +const nativeExpoSecureEnvironment = requireNativeModule< |
| 13 | + UnwrapPromiseReturnTypes<Omit<SecureEnvironment, 'batchGenerateKeyPair'>, 'sign'> & { |
| 14 | + supportsSecureEnvironment: () => boolean |
| 15 | + } |
| 16 | +>('ExpoSecureEnvironment') |
| 17 | + |
| 18 | +export const expoSecureEnvironment = { |
| 19 | + generateKeypair: (keyId: string, biometricsBacked?: boolean): Uint8Array => { |
| 20 | + nativeExpoSecureEnvironment.generateKeypair(keyId, biometricsBacked) |
| 21 | + const publicKey = expoSecureEnvironment.getPublicBytesForKeyId(keyId) |
| 22 | + return publicKey |
| 23 | + }, |
| 24 | + |
| 25 | + batchGenerateKeyPair: (keyIds: Array<string>): Record<string, Uint8Array> => { |
| 26 | + for (const keyId of keyIds) { |
| 27 | + expoSecureEnvironment.generateKeypair(keyId) |
| 28 | + } |
| 29 | + |
| 30 | + return keyIds |
| 31 | + .map((keyId) => ({ |
| 32 | + keyId, |
| 33 | + publicKey: expoSecureEnvironment.getPublicBytesForKeyId(keyId), |
| 34 | + })) |
| 35 | + .reduce((prev, curr) => ({ ...prev, [curr.keyId]: curr.publicKey }), {}) |
| 36 | + }, |
| 37 | + |
| 38 | + getPublicBytesForKeyId: (keyId: string): Uint8Array => { |
| 39 | + return nativeExpoSecureEnvironment.getPublicBytesForKeyId(keyId) |
| 40 | + }, |
| 41 | + |
| 42 | + sign: (keyId: string, message: Uint8Array, biometricsBacked?: boolean): Promise<Uint8Array> => { |
| 43 | + return nativeExpoSecureEnvironment.sign(keyId, message, biometricsBacked) |
| 44 | + }, |
| 45 | + |
| 46 | + supportsSecureEnvironment: () => { |
| 47 | + return nativeExpoSecureEnvironment.supportsSecureEnvironment() |
| 48 | + }, |
| 49 | +} |
0 commit comments