All files / src/oauth gitlab-device-flow.ts

10% Statements 8/80
0% Branches 0/29
0% Functions 0/8
10.12% Lines 8/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326                    21x     21x                                                               21x                                                                                               21x                                                                                                                                               21x                                                                                                         21x                                                                                               21x                                                                       21x                                              
/**
 * GitLab Device Flow Client
 *
 * Implements the OAuth 2.0 Device Authorization Grant (RFC 8628) for GitLab.
 * This allows authentication on devices without browser access by having
 * users authenticate on a separate device.
 *
 * GitLab Device Flow documentation: https://docs.gitlab.com/api/oauth2/#device-authorization-grant
 */
 
import { GITLAB_BASE_URL } from "../config";
import { OAuthConfig } from "./config";
import { GitLabDeviceResponse, GitLabTokenResponse, GitLabUserInfo } from "./types";
import { logger } from "../logger";
 
/**
 * Device flow error types from GitLab
 */
type DeviceFlowError =
  | "authorization_pending"
  | "slow_down"
  | "expired_token"
  | "access_denied"
  | "invalid_grant"
  | "invalid_request";
 
/**
 * Device flow error response from GitLab
 */
interface DeviceFlowErrorResponse {
  error: DeviceFlowError;
  error_description?: string;
}
 
/**
 * Initiate the device authorization flow with GitLab
 *
 * This starts the device flow by requesting a device code and user code
 * from GitLab. The user must then visit the verification URI and enter
 * the user code to authorize the application.
 *
 * @param config - OAuth configuration
 * @returns Device authorization response with codes and URIs
 * @throws Error if the request fails
 */
export async function initiateDeviceFlow(config: OAuthConfig): Promise<GitLabDeviceResponse> {
  const url = `${GITLAB_BASE_URL}/oauth/authorize_device`;
 
  logger.debug({ url, clientId: config.gitlabClientId }, "Initiating GitLab device flow");
 
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    body: new URLSearchParams({
      client_id: config.gitlabClientId,
      scope: config.gitlabScopes,
    }),
  });
 
  if (!response.ok) {
    const errorText = await response.text();
    logger.error({ status: response.status, error: errorText }, "Failed to initiate device flow");
    throw new Error(`Failed to initiate device flow: ${response.status} ${errorText}`);
  }
 
  const data = (await response.json()) as GitLabDeviceResponse;
 
  logger.info(
    {
      userCode: data.user_code,
      verificationUri: data.verification_uri,
      expiresIn: data.expires_in,
    },
    "Device flow initiated"
  );
 
  return data;
}
 
/**
 * Poll GitLab for device authorization completion (single attempt)
 *
 * Makes a single poll request to check if the user has completed authorization.
 * Returns the token response if authorized, null if still pending.
 *
 * @param deviceCode - Device code from initiateDeviceFlow
 * @param config - OAuth configuration
 * @returns Token response if authorized, null if pending
 * @throws Error for terminal errors (expired, denied, etc.)
 */
export async function pollDeviceFlowOnce(
  deviceCode: string,
  config: OAuthConfig
): Promise<GitLabTokenResponse | null> {
  const url = `${GITLAB_BASE_URL}/oauth/token`;
 
  const params: Record<string, string> = {
    client_id: config.gitlabClientId,
    device_code: deviceCode,
    grant_type: "urn:ietf:params:oauth:grant-type:device_code",
  };
 
  // Add client secret if configured (for confidential apps)
  if (config.gitlabClientSecret) {
    params.client_secret = config.gitlabClientSecret;
  }
 
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    body: new URLSearchParams(params),
  });
 
  if (response.ok) {
    const data = (await response.json()) as GitLabTokenResponse;
    logger.info("Device flow authorization completed successfully");
    return data;
  }
 
  // Handle error responses
  const error = (await response.json()) as DeviceFlowErrorResponse;
 
  switch (error.error) {
    case "authorization_pending":
      // User hasn't completed authorization yet - this is normal
      return null;
 
    case "slow_down":
      // GitLab is asking us to slow down - we should increase the interval
      // The caller should handle this by increasing poll interval
      logger.debug("Device flow: slow_down received, should increase poll interval");
      return null;
 
    case "expired_token":
      throw new Error("Device code expired. Please start a new authorization.");
 
    case "access_denied":
      throw new Error("User denied the authorization request.");
 
    case "invalid_grant":
      throw new Error("Invalid device code or grant.");
 
    default:
      throw new Error(`Device flow error: ${error.error_description ?? error.error}`);
  }
}
 
/**
 * Poll GitLab for device authorization completion (with retries)
 *
 * Continuously polls GitLab until the user completes authorization,
 * the device code expires, or the user denies the request.
 *
 * @param deviceCode - Device code from initiateDeviceFlow
 * @param config - OAuth configuration
 * @param onPending - Optional callback called on each pending poll
 * @returns Token response when authorized
 * @throws Error on timeout, expiration, or denial
 */
export async function pollForToken(
  deviceCode: string,
  config: OAuthConfig,
  onPending?: () => void
): Promise<GitLabTokenResponse> {
  const startTime = Date.now();
  const timeout = config.deviceTimeout * 1000;
  let interval = config.devicePollInterval * 1000;
 
  while (Date.now() - startTime < timeout) {
    // Wait before polling
    await sleep(interval);
 
    try {
      const result = await pollDeviceFlowOnce(deviceCode, config);
 
      if (result) {
        return result;
      }
 
      // Still pending
      onPending?.();
    } catch (error) {
      // Re-throw terminal errors
      if (error instanceof Error) {
        if (
          error.message.includes("expired") ||
          error.message.includes("denied") ||
          error.message.includes("invalid")
        ) {
          throw error;
        }
      }
 
      // Log but continue for transient errors
      logger.warn({ err: error as Error }, "Device flow poll error, will retry");
    }
  }
 
  throw new Error(`Device flow timeout after ${config.deviceTimeout} seconds`);
}
 
/**
 * Refresh a GitLab OAuth token
 *
 * Uses the refresh token to obtain a new access token when the current
 * one is expired or about to expire.
 *
 * @param refreshToken - GitLab refresh token
 * @param config - OAuth configuration
 * @returns New token response
 * @throws Error if refresh fails
 */
export async function refreshGitLabToken(
  refreshToken: string,
  config: OAuthConfig
): Promise<GitLabTokenResponse> {
  const url = `${GITLAB_BASE_URL}/oauth/token`;
 
  const params: Record<string, string> = {
    client_id: config.gitlabClientId,
    refresh_token: refreshToken,
    grant_type: "refresh_token",
  };
 
  // Add client secret if configured
  if (config.gitlabClientSecret) {
    params.client_secret = config.gitlabClientSecret;
  }
 
  logger.debug("Refreshing GitLab token");
 
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    body: new URLSearchParams(params),
  });
 
  if (!response.ok) {
    const errorText = await response.text();
    logger.error({ status: response.status, error: errorText }, "Failed to refresh GitLab token");
    throw new Error(`Failed to refresh token: ${response.status} ${errorText}`);
  }
 
  const data = (await response.json()) as GitLabTokenResponse;
  logger.info("GitLab token refreshed successfully");
  return data;
}
 
/**
 * Get the current GitLab user's information
 *
 * Uses the access token to fetch the authenticated user's profile.
 *
 * @param accessToken - GitLab access token
 * @returns User information (id and username)
 * @throws Error if the request fails
 */
export async function getGitLabUser(accessToken: string): Promise<GitLabUserInfo> {
  const url = `${GITLAB_BASE_URL}/api/v4/user`;
 
  const response = await fetch(url, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      Accept: "application/json",
    },
  });
 
  if (!response.ok) {
    const errorText = await response.text();
    logger.error({ status: response.status, error: errorText }, "Failed to get GitLab user info");
    throw new Error(`Failed to get GitLab user info: ${response.status}`);
  }
 
  const user = (await response.json()) as GitLabUserInfo;
 
  logger.debug({ userId: user.id, username: user.username }, "Retrieved GitLab user info");
 
  return {
    id: user.id,
    username: user.username,
    name: user.name,
    email: user.email,
  };
}
 
/**
 * Validate a GitLab access token
 *
 * Checks if the token is still valid by making a lightweight API call.
 *
 * @param accessToken - GitLab access token to validate
 * @returns true if the token is valid, false otherwise
 */
export async function validateGitLabToken(accessToken: string): Promise<boolean> {
  try {
    const url = `${GITLAB_BASE_URL}/api/v4/user`;
 
    const response = await fetch(url, {
      method: "HEAD",
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
 
    return response.ok;
  } catch {
    return false;
  }
}
 
/**
 * Helper function to sleep for a specified duration
 */
function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}