UNPKG

2.33 kBJavaScriptView Raw
1// @flow
2
3import { NativeModules } from 'react-native';
4
5const { ExponentSecureStore } = NativeModules;
6
7export /*opaque*/ type KeychainAccessibilityConstant = number;
8
9export const AFTER_FIRST_UNLOCK: KeychainAccessibilityConstant =
10 ExponentSecureStore.AFTER_FIRST_UNLOCK;
11export const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
12 ExponentSecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY;
13export const ALWAYS: KeychainAccessibilityConstant = ExponentSecureStore.ALWAYS;
14export const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
15 ExponentSecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY;
16export const ALWAYS_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
17 ExponentSecureStore.ALWAYS_THIS_DEVICE_ONLY;
18export const WHEN_UNLOCKED: KeychainAccessibilityConstant = ExponentSecureStore.WHEN_UNLOCKED;
19export const WHEN_UNLOCKED_THIS_DEVICE_ONLY: KeychainAccessibilityConstant =
20 ExponentSecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY;
21
22export type SecureStoreOptions = {
23 keychainService?: string,
24 keychainAccessible?: KeychainAccessibilityConstant,
25};
26
27export async function deleteItemAsync(
28 key: string,
29 options: SecureStoreOptions = {}
30): Promise<void> {
31 _ensureValidKey(key);
32 await ExponentSecureStore.deleteValueWithKeyAsync(key, options);
33}
34
35export async function getItemAsync(
36 key: string,
37 options: SecureStoreOptions = {}
38): Promise<?string> {
39 _ensureValidKey(key);
40 return await ExponentSecureStore.getValueWithKeyAsync(key, options);
41}
42
43export async function setItemAsync(
44 key: string,
45 value: string,
46 options: SecureStoreOptions = {}
47): Promise<void> {
48 _ensureValidKey(key);
49 if (!_isValidValue(value)) {
50 throw new Error(
51 `Invalid value provided to SecureStore. Values must be strings; consider JSON-encoding your values if they are serializable.`
52 );
53 }
54 await ExponentSecureStore.setValueWithKeyAsync(value, key, options);
55}
56
57function _ensureValidKey(key: string) {
58 if (!_isValidKey(key)) {
59 throw new Error(
60 `Invalid key provided to SecureStore. Keys must not be empty and contain only alphanumeric characters, ".", "-", and "_".`
61 );
62 }
63}
64
65function _isValidKey(key: string) {
66 return typeof key === 'string' && /^[\w.-]+$/.test(key);
67}
68
69function _isValidValue(value: string) {
70 return typeof value === 'string';
71}