|
| 1 | +import * as AuthSession from 'expo-auth-session'; |
| 2 | +import * as WebBrowser from 'expo-web-browser'; |
| 3 | +import * as Crypto from 'expo-crypto'; |
| 4 | +import { |
| 5 | + getCloudUrlFromRegion, |
| 6 | + getOauthClientIdFromRegion, |
| 7 | + OAUTH_SCOPES, |
| 8 | +} from '../constants/oauth'; |
| 9 | +import type { CloudRegion, OAuthTokenResponse, OAuthConfig } from '../types/oauth'; |
| 10 | + |
| 11 | +// Required for web browser auth session to work properly |
| 12 | +WebBrowser.maybeCompleteAuthSession(); |
| 13 | + |
| 14 | +// Generate PKCE code verifier and challenge |
| 15 | +async function generateCodeVerifier(): Promise<string> { |
| 16 | + const randomBytes = await Crypto.getRandomBytesAsync(32); |
| 17 | + return btoa(String.fromCharCode(...randomBytes)) |
| 18 | + .replace(/\+/g, '-') |
| 19 | + .replace(/\//g, '_') |
| 20 | + .replace(/=/g, ''); |
| 21 | +} |
| 22 | + |
| 23 | +async function generateCodeChallenge(verifier: string): Promise<string> { |
| 24 | + const encoder = new TextEncoder(); |
| 25 | + const data = encoder.encode(verifier); |
| 26 | + const digest = await Crypto.digest(Crypto.CryptoDigestAlgorithm.SHA256, data); |
| 27 | + |
| 28 | + return btoa(String.fromCharCode(...new Uint8Array(digest))) |
| 29 | + .replace(/\+/g, '-') |
| 30 | + .replace(/\//g, '_') |
| 31 | + .replace(/=/g, ''); |
| 32 | +} |
| 33 | + |
| 34 | +export function getRedirectUri(): string { |
| 35 | + return AuthSession.makeRedirectUri({ |
| 36 | + scheme: 'posthog-mobile', |
| 37 | + path: 'callback', |
| 38 | + }); |
| 39 | +} |
| 40 | + |
| 41 | +export function getAuthorizationEndpoint(region: CloudRegion): string { |
| 42 | + return `${getCloudUrlFromRegion(region)}/oauth/authorize`; |
| 43 | +} |
| 44 | + |
| 45 | +export function getTokenEndpoint(region: CloudRegion): string { |
| 46 | + return `${getCloudUrlFromRegion(region)}/oauth/token`; |
| 47 | +} |
| 48 | + |
| 49 | +export async function exchangeCodeForToken( |
| 50 | + code: string, |
| 51 | + codeVerifier: string, |
| 52 | + config: OAuthConfig |
| 53 | +): Promise<OAuthTokenResponse> { |
| 54 | + const cloudUrl = getCloudUrlFromRegion(config.cloudRegion); |
| 55 | + const redirectUri = getRedirectUri(); |
| 56 | + |
| 57 | + const response = await fetch(`${cloudUrl}/oauth/token`, { |
| 58 | + method: 'POST', |
| 59 | + headers: { |
| 60 | + 'Content-Type': 'application/json', |
| 61 | + }, |
| 62 | + body: JSON.stringify({ |
| 63 | + grant_type: 'authorization_code', |
| 64 | + code, |
| 65 | + redirect_uri: redirectUri, |
| 66 | + client_id: getOauthClientIdFromRegion(config.cloudRegion), |
| 67 | + code_verifier: codeVerifier, |
| 68 | + }), |
| 69 | + }); |
| 70 | + |
| 71 | + if (!response.ok) { |
| 72 | + const errorText = await response.text(); |
| 73 | + throw new Error(`Token exchange failed: ${response.statusText} - ${errorText}`); |
| 74 | + } |
| 75 | + |
| 76 | + return response.json(); |
| 77 | +} |
| 78 | + |
| 79 | +export async function refreshAccessToken( |
| 80 | + refreshToken: string, |
| 81 | + region: CloudRegion |
| 82 | +): Promise<OAuthTokenResponse> { |
| 83 | + const cloudUrl = getCloudUrlFromRegion(region); |
| 84 | + |
| 85 | + const response = await fetch(`${cloudUrl}/oauth/token`, { |
| 86 | + method: 'POST', |
| 87 | + headers: { |
| 88 | + 'Content-Type': 'application/json', |
| 89 | + }, |
| 90 | + body: JSON.stringify({ |
| 91 | + grant_type: 'refresh_token', |
| 92 | + refresh_token: refreshToken, |
| 93 | + client_id: getOauthClientIdFromRegion(region), |
| 94 | + }), |
| 95 | + }); |
| 96 | + |
| 97 | + if (!response.ok) { |
| 98 | + throw new Error(`Token refresh failed: ${response.statusText}`); |
| 99 | + } |
| 100 | + |
| 101 | + return response.json(); |
| 102 | +} |
| 103 | + |
| 104 | +export interface OAuthFlowResult { |
| 105 | + success: boolean; |
| 106 | + data?: OAuthTokenResponse; |
| 107 | + error?: string; |
| 108 | +} |
| 109 | + |
| 110 | +export async function performOAuthFlow(config: OAuthConfig): Promise<OAuthFlowResult> { |
| 111 | + try { |
| 112 | + const codeVerifier = await generateCodeVerifier(); |
| 113 | + const codeChallenge = await generateCodeChallenge(codeVerifier); |
| 114 | + const redirectUri = getRedirectUri(); |
| 115 | + const clientId = getOauthClientIdFromRegion(config.cloudRegion); |
| 116 | + |
| 117 | + const discovery: AuthSession.DiscoveryDocument = { |
| 118 | + authorizationEndpoint: getAuthorizationEndpoint(config.cloudRegion), |
| 119 | + tokenEndpoint: getTokenEndpoint(config.cloudRegion), |
| 120 | + }; |
| 121 | + |
| 122 | + const authRequest = new AuthSession.AuthRequest({ |
| 123 | + clientId, |
| 124 | + scopes: config.scopes, |
| 125 | + redirectUri, |
| 126 | + codeChallenge, |
| 127 | + codeChallengeMethod: AuthSession.CodeChallengeMethod.S256, |
| 128 | + extraParams: { |
| 129 | + required_access_level: 'project', |
| 130 | + }, |
| 131 | + }); |
| 132 | + |
| 133 | + const authResult = await authRequest.promptAsync(discovery); |
| 134 | + |
| 135 | + if (authResult.type === 'cancel' || authResult.type === 'dismiss') { |
| 136 | + return { |
| 137 | + success: false, |
| 138 | + error: 'Authorization cancelled', |
| 139 | + }; |
| 140 | + } |
| 141 | + |
| 142 | + if (authResult.type === 'error') { |
| 143 | + return { |
| 144 | + success: false, |
| 145 | + error: authResult.error?.message || 'Authorization failed', |
| 146 | + }; |
| 147 | + } |
| 148 | + |
| 149 | + if (authResult.type !== 'success' || !authResult.params.code) { |
| 150 | + return { |
| 151 | + success: false, |
| 152 | + error: 'No authorization code received', |
| 153 | + }; |
| 154 | + } |
| 155 | + |
| 156 | + const tokenResponse = await exchangeCodeForToken( |
| 157 | + authResult.params.code, |
| 158 | + codeVerifier, |
| 159 | + config |
| 160 | + ); |
| 161 | + |
| 162 | + return { |
| 163 | + success: true, |
| 164 | + data: tokenResponse, |
| 165 | + }; |
| 166 | + } catch (error) { |
| 167 | + return { |
| 168 | + success: false, |
| 169 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 170 | + }; |
| 171 | + } |
| 172 | +} |
0 commit comments