(
tokens: OAuthTokens,
{ mode = 'auto' }: { mode?: OAuthInstallMode } = {},
)
| 101 | } |
| 102 | |
| 103 | export async function installOAuthTokens( |
| 104 | tokens: OAuthTokens, |
| 105 | { mode = 'auto' }: { mode?: OAuthInstallMode } = {}, |
| 106 | ): Promise<void> { |
| 107 | // Clear old state before saving new credentials |
| 108 | await performLogout({ clearOnboarding: false }) |
| 109 | |
| 110 | // Reuse pre-fetched profile if available, otherwise fetch fresh |
| 111 | const profile = |
| 112 | tokens.profile ?? |
| 113 | (tokens.tokenAccount |
| 114 | ? undefined |
| 115 | : await getOauthProfileFromOauthToken(tokens.accessToken)) |
| 116 | const managedIdentityError = getManagedIdentityValidationError( |
| 117 | tokens, |
| 118 | profile, |
| 119 | mode, |
| 120 | ) |
| 121 | if (managedIdentityError) { |
| 122 | throw new Error(managedIdentityError) |
| 123 | } |
| 124 | if (profile) { |
| 125 | storeOAuthAccountInfo({ |
| 126 | accountUuid: profile.account.uuid, |
| 127 | emailAddress: profile.account.email, |
| 128 | organizationUuid: profile.organization.uuid, |
| 129 | displayName: profile.account.display_name || undefined, |
| 130 | hasExtraUsageEnabled: |
| 131 | profile.organization.has_extra_usage_enabled ?? undefined, |
| 132 | billingType: profile.organization.billing_type ?? undefined, |
| 133 | subscriptionCreatedAt: |
| 134 | profile.organization.subscription_created_at ?? undefined, |
| 135 | accountCreatedAt: profile.account.created_at, |
| 136 | }) |
| 137 | } else if (tokens.tokenAccount) { |
| 138 | // Fallback to token exchange account data when profile endpoint fails |
| 139 | storeOAuthAccountInfo({ |
| 140 | accountUuid: tokens.tokenAccount.uuid, |
| 141 | emailAddress: tokens.tokenAccount.emailAddress, |
| 142 | organizationUuid: tokens.tokenAccount.organizationUuid, |
| 143 | }) |
| 144 | } |
| 145 | |
| 146 | const authRuntime = getAuthRuntime() |
| 147 | const storageResult = authRuntime.persistOAuthTokensIfNeeded(tokens) |
| 148 | authRuntime.clearManagedTokenCache() |
| 149 | |
| 150 | if (storageResult.warning) { |
| 151 | logEvent('ncode_oauth_storage_warning', { |
| 152 | warning: |
| 153 | storageResult.warning as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, |
| 154 | }) |
| 155 | } |
| 156 | |
| 157 | if (usesManagedInstallMode(tokens, mode)) { |
| 158 | // Roles and first-token-date enrich UI state only; they are not required |
| 159 | // for a usable managed OAuth session and must not block login. |
| 160 | logForDebugging( |
no test coverage detected