@kivacore/api-client 0.0.0 → 0.3.8

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.
@@ -0,0 +1,128 @@
1
+ import { type OAuth2Tokens, type OAuth2TokenStorage, type PKCEState } from './oauth2-types';
2
+ import { type TokenManager } from '../core/types';
3
+
4
+ /**
5
+ * In-memory OAuth2 token storage
6
+ */
7
+ export class MemoryOAuth2TokenStorage implements OAuth2TokenStorage {
8
+ private tokens: OAuth2Tokens | null = null;
9
+ private pkceState: PKCEState | null = null;
10
+ getTokens(): OAuth2Tokens | null {
11
+ return this.tokens;
12
+ }
13
+ setTokens(tokens: OAuth2Tokens): void {
14
+ this.tokens = tokens;
15
+ }
16
+ clearTokens(): void {
17
+ this.tokens = null;
18
+ }
19
+ getPKCEState(): PKCEState | null {
20
+ return this.pkceState;
21
+ }
22
+ setPKCEState(state: PKCEState): void {
23
+ this.pkceState = state;
24
+ }
25
+ clearPKCEState(): void {
26
+ this.pkceState = null;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Browser storage (localStorage/sessionStorage) OAuth2 token storage
32
+ */
33
+ export class BrowserOAuth2TokenStorage implements OAuth2TokenStorage {
34
+ private readonly tokensKey: string;
35
+ private readonly pkceKey: string;
36
+ private storage: Storage | null;
37
+ constructor(
38
+ storage?: Storage,
39
+ keyPrefix: string = 'docyrus_oauth2'
40
+ ) {
41
+ this.storage = storage ?? (typeof window !== 'undefined' ? window.localStorage : null);
42
+ this.tokensKey = `${keyPrefix}_tokens`;
43
+ this.pkceKey = `${keyPrefix}_pkce`;
44
+ }
45
+ getTokens(): OAuth2Tokens | null {
46
+ if (!this.storage) return null;
47
+ const data = this.storage.getItem(this.tokensKey);
48
+
49
+ return data ? JSON.parse(data) : null;
50
+ }
51
+ setTokens(tokens: OAuth2Tokens): void {
52
+ if (!this.storage) return;
53
+ this.storage.setItem(this.tokensKey, JSON.stringify(tokens));
54
+ }
55
+ clearTokens(): void {
56
+ if (!this.storage) return;
57
+ this.storage.removeItem(this.tokensKey);
58
+ }
59
+ getPKCEState(): PKCEState | null {
60
+ if (!this.storage) return null;
61
+ const data = this.storage.getItem(this.pkceKey);
62
+
63
+ return data ? JSON.parse(data) : null;
64
+ }
65
+ setPKCEState(state: PKCEState): void {
66
+ if (!this.storage) return;
67
+ this.storage.setItem(this.pkceKey, JSON.stringify(state));
68
+ }
69
+ clearPKCEState(): void {
70
+ if (!this.storage) return;
71
+ this.storage.removeItem(this.pkceKey);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Adapter to bridge OAuth2TokenStorage to the existing TokenManager interface
77
+ * This allows using OAuth2 tokens with RestApiClient
78
+ */
79
+ export class OAuth2TokenManagerAdapter implements TokenManager {
80
+ constructor(
81
+ private oauth2Storage: OAuth2TokenStorage,
82
+ private onTokenExpired?: () => Promise<string>
83
+ ) {}
84
+ getToken(): string | null | Promise<string | null> {
85
+ const tokens = this.oauth2Storage.getTokens();
86
+
87
+ if (tokens instanceof Promise) {
88
+ return tokens.then(t => this.extractToken(t));
89
+ }
90
+
91
+ return this.extractToken(tokens);
92
+ }
93
+ private extractToken(tokens: OAuth2Tokens | null): string | null {
94
+ if (!tokens) return null;
95
+
96
+ // Check if token is expired (with 60s buffer)
97
+ if (tokens.expiresAt && Date.now() >= (tokens.expiresAt - 60) * 1000) {
98
+ return null; // Token expired, needs refresh
99
+ }
100
+
101
+ return tokens.accessToken;
102
+ }
103
+ setToken(token: string): void | Promise<void> {
104
+ /*
105
+ * This is a simplified implementation
106
+ * Full OAuth2 flow should use setTokens with full response
107
+ */
108
+ const result = this.oauth2Storage.setTokens({
109
+ accessToken: token,
110
+ expiresAt: Math.floor(Date.now() / 1000) + 3600, // Default 1 hour
111
+ scope: ''
112
+ });
113
+
114
+ if (result instanceof Promise) {
115
+ return result;
116
+ }
117
+ }
118
+ clearToken(): void | Promise<void> {
119
+ return this.oauth2Storage.clearTokens();
120
+ }
121
+ refreshToken(): Promise<string> {
122
+ if (!this.onTokenExpired) {
123
+ return Promise.reject(new Error('Token refresh not configured'));
124
+ }
125
+
126
+ return this.onTokenExpired();
127
+ }
128
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * OAuth2 TypeScript type definitions for Docyrus API
3
+ */
4
+
5
+ import { type CryptoProvider } from '../core/crypto';
6
+
7
+ // Grant types supported by Docyrus OAuth2
8
+ export type OAuth2GrantType
9
+ = | 'authorization_code'
10
+ | 'refresh_token'
11
+ | 'client_credentials'
12
+ | 'urn:ietf:params:oauth:grant-type:device_code';
13
+
14
+ // Client authentication methods
15
+ export type ClientAssertionType = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
16
+
17
+ // Token type hints for introspection
18
+ export type TokenTypeHint = 'access_token' | 'refresh_token';
19
+
20
+ // ===== Authorization Endpoint =====
21
+
22
+ export interface AuthorizationParams {
23
+ client_id: string;
24
+ redirect_uri: string;
25
+ response_type: 'code';
26
+ state: string;
27
+ scope: string;
28
+ code_challenge?: string;
29
+ code_challenge_method?: 'S256';
30
+ nonce?: string;
31
+ }
32
+
33
+ // ===== Token Endpoint =====
34
+
35
+ // Base token request (common fields)
36
+ export interface BaseTokenRequest {
37
+ grant_type: OAuth2GrantType;
38
+ client_id: string;
39
+ client_secret?: string;
40
+ client_assertion_type?: ClientAssertionType;
41
+ client_assertion?: string;
42
+ }
43
+
44
+ // Authorization Code grant
45
+ export interface AuthorizationCodeTokenRequest extends BaseTokenRequest {
46
+ grant_type: 'authorization_code';
47
+ code: string;
48
+ code_verifier?: string;
49
+ redirect_uri?: string;
50
+ }
51
+
52
+ // Refresh Token grant
53
+ export interface RefreshTokenRequest extends BaseTokenRequest {
54
+ grant_type: 'refresh_token';
55
+ refresh_token: string;
56
+ }
57
+
58
+ // Client Credentials grant
59
+ export interface ClientCredentialsRequest extends BaseTokenRequest {
60
+ grant_type: 'client_credentials';
61
+ scope: string;
62
+ delegated_user_id: string;
63
+ }
64
+
65
+ // Device Code grant
66
+ export interface DeviceCodeTokenRequest extends BaseTokenRequest {
67
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code';
68
+ device_code: string;
69
+ }
70
+
71
+ export type TokenRequest
72
+ = | AuthorizationCodeTokenRequest
73
+ | RefreshTokenRequest
74
+ | ClientCredentialsRequest
75
+ | DeviceCodeTokenRequest;
76
+
77
+ // Token response from /oauth2/token
78
+ export interface TokenResponse {
79
+ access_token: string;
80
+ token_type: 'Bearer';
81
+ expires_in: number;
82
+ scope: string;
83
+ refresh_token?: string;
84
+ id_token?: string;
85
+ }
86
+
87
+ // ===== Revoke Endpoint =====
88
+
89
+ export interface RevokeTokenRequest {
90
+ client_id: string;
91
+ client_secret?: string;
92
+ refresh_token: string;
93
+ client_assertion_type?: ClientAssertionType;
94
+ client_assertion?: string;
95
+ }
96
+
97
+ // ===== Introspect Endpoint =====
98
+
99
+ export interface IntrospectTokenRequest {
100
+ token: string;
101
+ token_type_hint?: TokenTypeHint;
102
+ client_id: string;
103
+ client_secret?: string;
104
+ client_assertion_type?: ClientAssertionType;
105
+ client_assertion?: string;
106
+ }
107
+
108
+ export interface IntrospectTokenResponse {
109
+ active: boolean;
110
+ scope?: string;
111
+ client_id?: string;
112
+ username?: string;
113
+ token_type?: string;
114
+ exp?: number;
115
+ iat?: number;
116
+ nbf?: number;
117
+ sub?: string;
118
+ aud?: string | string[];
119
+ iss?: string;
120
+ jti?: string;
121
+ }
122
+
123
+ // ===== Device Authorization Endpoint =====
124
+
125
+ export interface DeviceAuthorizationRequest {
126
+ client_id: string;
127
+ scope?: string;
128
+ }
129
+
130
+ export interface DeviceAuthorizationResponse {
131
+ device_code: string;
132
+ user_code: string;
133
+ verification_uri: string;
134
+ verification_uri_complete?: string;
135
+ expires_in: number;
136
+ interval: number;
137
+ }
138
+
139
+ // ===== Device Verify Endpoint =====
140
+
141
+ export interface DeviceVerifyRequest {
142
+ user_code: string;
143
+ }
144
+
145
+ export interface DeviceVerifyResponse {
146
+ userCode: string;
147
+ scopes: string[];
148
+ clientId: string;
149
+ }
150
+
151
+ // ===== Rate Limit Response =====
152
+
153
+ export interface RateLimitInfo {
154
+ policy: string;
155
+ reset: number;
156
+ remaining: number;
157
+ limit: number;
158
+ }
159
+
160
+ // ===== OAuth2 Client Configuration =====
161
+
162
+ export interface OAuth2ClientConfig {
163
+ /** OAuth2 server base URL (e.g., 'https://api.docyrus.com') */
164
+ baseURL: string;
165
+
166
+ /** Client ID */
167
+ clientId: string;
168
+
169
+ /** Client Secret (optional for public clients using PKCE) */
170
+ clientSecret?: string;
171
+
172
+ /** Redirect URI for authorization code flow */
173
+ redirectUri?: string;
174
+
175
+ /** Default scopes to request */
176
+ defaultScopes?: string[];
177
+
178
+ /** Token storage implementation */
179
+ tokenStorage?: OAuth2TokenStorage;
180
+
181
+ /** Enable automatic PKCE for authorization code flow (default: true) */
182
+ usePKCE?: boolean;
183
+
184
+ /** Custom fetch implementation */
185
+ fetch?: typeof fetch;
186
+
187
+ /** Request timeout in milliseconds */
188
+ timeout?: number;
189
+
190
+ /** Custom crypto provider for PKCE operations (default: browser Web Crypto API) */
191
+ cryptoProvider?: CryptoProvider;
192
+ }
193
+
194
+ // ===== Token Storage Interface =====
195
+
196
+ export interface OAuth2TokenStorage {
197
+ getTokens(): OAuth2Tokens | Promise<OAuth2Tokens | null> | null;
198
+ setTokens(tokens: OAuth2Tokens): void | Promise<void>;
199
+ clearTokens(): void | Promise<void>;
200
+
201
+ // PKCE state management
202
+ getPKCEState?(): PKCEState | Promise<PKCEState | null> | null;
203
+ setPKCEState?(state: PKCEState): void | Promise<void>;
204
+ clearPKCEState?(): void | Promise<void>;
205
+ }
206
+
207
+ export interface OAuth2Tokens {
208
+ accessToken: string;
209
+ refreshToken?: string;
210
+ idToken?: string;
211
+ expiresAt: number; // Unix timestamp in seconds
212
+ scope: string;
213
+ }
214
+
215
+ export interface PKCEState {
216
+ codeVerifier: string;
217
+ state: string;
218
+ nonce?: string;
219
+ }
220
+
221
+ // ===== Callback Result =====
222
+
223
+ export interface AuthorizationCallbackResult {
224
+ code: string;
225
+ state: string;
226
+ }
227
+
228
+ // ===== Device Polling Options =====
229
+
230
+ export interface DevicePollingOptions {
231
+ onUserCode?: (response: DeviceAuthorizationResponse) => void;
232
+ onExpired?: () => void;
233
+ signal?: AbortSignal;
234
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * PKCE (Proof Key for Code Exchange) utilities for OAuth2
3
+ * Implements RFC 7636
4
+ *
5
+ * All functions accept an optional CryptoProvider parameter.
6
+ * When omitted, the default BrowserCryptoProvider is used (browser/Node.js globals).
7
+ */
8
+
9
+ import { type CryptoProvider, getDefaultCryptoProvider } from '../core/crypto';
10
+
11
+ export interface PKCEChallenge {
12
+ codeVerifier: string;
13
+ codeChallenge: string;
14
+ codeChallengeMethod: 'S256';
15
+ }
16
+
17
+ /**
18
+ * Generate a cryptographically random code verifier
19
+ * RFC 7636 requires 43-128 characters from unreserved URI characters
20
+ */
21
+ export function generateCodeVerifier(length: number = 64, cryptoProvider?: CryptoProvider): string {
22
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
23
+ const unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
24
+ const randomValues = new Uint8Array(length);
25
+
26
+ provider.getRandomValues(randomValues);
27
+
28
+ let verifier = '';
29
+
30
+ for (let i = 0; i < length; i++) {
31
+ verifier += unreserved[randomValues[i] % unreserved.length];
32
+ }
33
+
34
+ return verifier;
35
+ }
36
+
37
+ /**
38
+ * Base64URL encode (RFC 4648)
39
+ */
40
+ export function base64UrlEncode(buffer: Uint8Array, cryptoProvider?: CryptoProvider): string {
41
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
42
+ let base64 = '';
43
+ const bytes = new Uint8Array(buffer);
44
+ const len = bytes.byteLength;
45
+
46
+ for (let i = 0; i < len; i++) {
47
+ base64 += String.fromCharCode(bytes[i]);
48
+ }
49
+
50
+ return provider.btoa(base64)
51
+ .replace(/\+/g, '-')
52
+ .replace(/\//g, '_')
53
+ .replace(/=+$/, '');
54
+ }
55
+
56
+ /**
57
+ * Base64URL decode
58
+ */
59
+ export function base64UrlDecode(input: string, cryptoProvider?: CryptoProvider): Uint8Array {
60
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
61
+
62
+ // Add padding if needed
63
+ let base64 = input.replace(/-/g, '+').replace(/_/g, '/');
64
+
65
+ while (base64.length % 4) {
66
+ base64 += '=';
67
+ }
68
+
69
+ const binary = provider.atob(base64);
70
+ const bytes = new Uint8Array(binary.length);
71
+
72
+ for (let i = 0; i < binary.length; i++) {
73
+ bytes[i] = binary.charCodeAt(i);
74
+ }
75
+
76
+ return bytes;
77
+ }
78
+
79
+ /**
80
+ * Generate code challenge from code verifier using SHA-256
81
+ * Returns Base64URL encoded hash
82
+ */
83
+ export async function generateCodeChallenge(codeVerifier: string, cryptoProvider?: CryptoProvider): Promise<string> {
84
+ const provider = cryptoProvider ?? getDefaultCryptoProvider();
85
+ const encoder = new TextEncoder();
86
+ const data = encoder.encode(codeVerifier);
87
+
88
+ // Use CryptoProvider for SHA-256
89
+ const digest = await provider.sha256(data);
90
+
91
+ // Convert to Base64URL (RFC 4648)
92
+ return base64UrlEncode(new Uint8Array(digest), provider);
93
+ }
94
+
95
+ /**
96
+ * Generate both code verifier and code challenge
97
+ */
98
+ export async function generatePKCEChallenge(cryptoProvider?: CryptoProvider): Promise<PKCEChallenge> {
99
+ const codeVerifier = generateCodeVerifier(64, cryptoProvider);
100
+ const codeChallenge = await generateCodeChallenge(codeVerifier, cryptoProvider);
101
+
102
+ return {
103
+ codeVerifier,
104
+ codeChallenge,
105
+ codeChallengeMethod: 'S256'
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Generate a cryptographically random state parameter
111
+ */
112
+ export function generateState(length: number = 32, cryptoProvider?: CryptoProvider): string {
113
+ return generateCodeVerifier(length, cryptoProvider);
114
+ }
115
+
116
+ /**
117
+ * Generate a cryptographically random nonce for ID token validation
118
+ */
119
+ export function generateNonce(length: number = 32, cryptoProvider?: CryptoProvider): string {
120
+ return generateCodeVerifier(length, cryptoProvider);
121
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @kivacore/api-client/react-native
3
+ *
4
+ * React Native entrypoint — provides platform-specific implementations
5
+ * for crypto and token storage, plus re-exports all RN-compatible APIs.
6
+ */
7
+
8
+ // React Native specific exports
9
+ export { ReactNativeCryptoProvider } from './rn-crypto';
10
+ export { createTokenStorage, type StorageAdapter } from './rn-helpers';
11
+
12
+ // Re-export everything from the main package (all RN-compatible)
13
+ export {
14
+ // Clients
15
+ BaseApiClient,
16
+ RestApiClient,
17
+ EdgeFunctionClient,
18
+ CloudflareWorkerClient,
19
+
20
+ // Token managers
21
+ MemoryTokenManager,
22
+ AsyncTokenManager,
23
+
24
+ // Crypto
25
+ BrowserCryptoProvider,
26
+ getDefaultCryptoProvider,
27
+
28
+ // OAuth2
29
+ OAuth2Client,
30
+ MemoryOAuth2TokenStorage,
31
+ OAuth2TokenManagerAdapter,
32
+ generatePKCEChallenge,
33
+ generateCodeVerifier,
34
+ generateCodeChallenge,
35
+ generateState,
36
+ generateNonce,
37
+ base64UrlEncode,
38
+ base64UrlDecode,
39
+
40
+ // Errors
41
+ ApiError,
42
+ NetworkError,
43
+ TimeoutError,
44
+ AbortError,
45
+ ValidationError,
46
+ AuthenticationError,
47
+ AuthorizationError,
48
+ NotFoundError,
49
+ ConflictError,
50
+ RateLimitError,
51
+ ServerError,
52
+ GenericError,
53
+ OAuth2Error,
54
+ InvalidGrantError,
55
+ InvalidClientError,
56
+ InvalidScopeError,
57
+ AuthorizationPendingError,
58
+ SlowDownError,
59
+ ExpiredTokenError,
60
+ AccessDeniedError,
61
+
62
+ // Utilities
63
+ withRetry,
64
+ isAbortError,
65
+ parseContentDisposition,
66
+ buildUrl,
67
+ isFormData,
68
+ isBlob,
69
+ isStream,
70
+ prepareFilterQueryForApi,
71
+ createAbortSignal,
72
+ jsonToQueryString
73
+ } from '../index';
74
+
75
+ // Re-export types
76
+ export type {
77
+ CryptoProvider,
78
+ HttpMethod,
79
+ ApiBackend,
80
+ QueryParamPrimitive,
81
+ QueryParamValue,
82
+ RequestConfig,
83
+ ApiResponse,
84
+ ApiClientConfig,
85
+ TokenManager,
86
+ Interceptor,
87
+ SSEOptions,
88
+ StreamOptions,
89
+ Html2PdfMargin,
90
+ Html2PdfOptions,
91
+ SimpleRule,
92
+ GroupRule,
93
+ FilterRule,
94
+ FilterQuery,
95
+ EnvironmentConfig,
96
+ OAuth2ClientConfig,
97
+ OAuth2Tokens,
98
+ OAuth2TokenStorage,
99
+ PKCEState,
100
+ TokenResponse,
101
+ DeviceAuthorizationResponse,
102
+ DeviceVerifyResponse,
103
+ IntrospectTokenResponse,
104
+ RateLimitInfo,
105
+ AuthorizationCallbackResult,
106
+ DevicePollingOptions,
107
+ OAuth2GrantType,
108
+ TokenTypeHint
109
+ } from '../index';
110
+
111
+ // Default export
112
+ export { RestApiClient as default } from '../index';
@@ -0,0 +1,115 @@
1
+ /**
2
+ * React Native CryptoProvider using expo-crypto.
3
+ *
4
+ * Requires `expo-crypto` to be installed in the consuming app.
5
+ * Provides SHA-256 hashing, random bytes, and base64 encoding
6
+ * without relying on browser globals (btoa/atob/crypto.subtle).
7
+ */
8
+
9
+ import { type CryptoProvider } from '../core/crypto';
10
+
11
+ // Pure-JS base64 lookup table
12
+ const BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
13
+
14
+ function uint8ToBase64(bytes: Uint8Array): string {
15
+ let result = '';
16
+ const len = bytes.length;
17
+
18
+ for (let i = 0; i < len; i += 3) {
19
+ const b0 = bytes[i];
20
+ const b1 = i + 1 < len ? bytes[i + 1] : 0;
21
+ const b2 = i + 2 < len ? bytes[i + 2] : 0;
22
+
23
+ result += BASE64_CHARS[(b0 >> 2) & 0x3f];
24
+ result += BASE64_CHARS[((b0 << 4) | (b1 >> 4)) & 0x3f];
25
+ result += i + 1 < len ? BASE64_CHARS[((b1 << 2) | (b2 >> 6)) & 0x3f] : '=';
26
+ result += i + 2 < len ? BASE64_CHARS[b2 & 0x3f] : '=';
27
+ }
28
+
29
+ return result;
30
+ }
31
+
32
+ function base64ToUint8(base64: string): Uint8Array {
33
+ // Build reverse lookup
34
+ const lookup = new Uint8Array(128);
35
+
36
+ for (let i = 0; i < BASE64_CHARS.length; i++) {
37
+ lookup[BASE64_CHARS.charCodeAt(i)] = i;
38
+ }
39
+
40
+ // Remove padding
41
+ let len = base64.length;
42
+
43
+ while (len > 0 && base64[len - 1] === '=') len--;
44
+
45
+ const bytes = new Uint8Array(Math.floor(len * 3 / 4));
46
+ let j = 0;
47
+
48
+ for (let i = 0; i < len; i += 4) {
49
+ const b0 = lookup[base64.charCodeAt(i)];
50
+ const b1 = i + 1 < len ? lookup[base64.charCodeAt(i + 1)] : 0;
51
+ const b2 = i + 2 < len ? lookup[base64.charCodeAt(i + 2)] : 0;
52
+ const b3 = i + 3 < len ? lookup[base64.charCodeAt(i + 3)] : 0;
53
+
54
+ bytes[j++] = (b0 << 2) | (b1 >> 4);
55
+
56
+ if (i + 2 < len) bytes[j++] = ((b1 << 4) | (b2 >> 2)) & 0xff;
57
+
58
+ if (i + 3 < len) bytes[j++] = ((b2 << 6) | b3) & 0xff;
59
+ }
60
+
61
+ return bytes;
62
+ }
63
+
64
+ /**
65
+ * CryptoProvider implementation for React Native using expo-crypto.
66
+ *
67
+ * Usage:
68
+ * ```ts
69
+ * import { ReactNativeCryptoProvider } from '@kivacore/api-client/react-native';
70
+ * import * as ExpoCrypto from 'expo-crypto';
71
+ *
72
+ * const cryptoProvider = new ReactNativeCryptoProvider(ExpoCrypto);
73
+ * ```
74
+ */
75
+ export class ReactNativeCryptoProvider implements CryptoProvider {
76
+ private expoCrypto: {
77
+ getRandomBytes: (byteCount: number) => Uint8Array;
78
+ digest: (algorithm: any, data: BufferSource) => Promise<ArrayBuffer>;
79
+ };
80
+ constructor(expoCrypto: {
81
+ getRandomBytes: (byteCount: number) => Uint8Array;
82
+ digest: (algorithm: any, data: BufferSource) => Promise<ArrayBuffer>;
83
+ }) {
84
+ this.expoCrypto = expoCrypto;
85
+ }
86
+ getRandomValues(buffer: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer> {
87
+ const random = this.expoCrypto.getRandomBytes(buffer.length);
88
+
89
+ buffer.set(random);
90
+
91
+ return buffer;
92
+ }
93
+ async sha256(data: Uint8Array<ArrayBuffer>): Promise<ArrayBuffer> {
94
+ return this.expoCrypto.digest('SHA-256', data);
95
+ }
96
+ btoa(input: string): string {
97
+ const bytes = new Uint8Array(input.length);
98
+
99
+ for (let i = 0; i < input.length; i++) {
100
+ bytes[i] = input.charCodeAt(i);
101
+ }
102
+
103
+ return uint8ToBase64(bytes);
104
+ }
105
+ atob(input: string): string {
106
+ const bytes = base64ToUint8(input);
107
+ let result = '';
108
+
109
+ for (let i = 0; i < bytes.length; i++) {
110
+ result += String.fromCharCode(bytes[i]);
111
+ }
112
+
113
+ return result;
114
+ }
115
+ }