All files / src/handlers oauth.ts

96.77% Statements 60/62
91.66% Branches 33/36
100% Functions 6/6
96.77% Lines 60/62

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                                1x 4x 4x       4x 4x 1x     3x 1x       2x   4x 4x   4x     4x 1x         1x 1x 1x 1x                               1x     10x 1x       9x 9x     9x 9x   1x         8x 1x     7x                     1x           10x   10x             5x 4x 1x   3x   3x 3x 3x   1x                         1x   14x 14x 14x     14x 1x 1x     13x   13x 13x     13x 1x         12x 1x           11x 10x 4x     1x   9x 9x      
import { HttpFunction } from "@google-cloud/functions-framework";
import { Buffer } from "buffer";
 
import { exchangeCodeForTokens } from "../services/fitbitService.js";
import {
  handleError,
  MethodNotAllowedError,
  ValidationError,
} from "../utils/errors.js";
 
/**
 * リダイレクトURIが許可リストに含まれているか検証する
 *
 * @param uri 検証対象のURI
 * @returns 許可されている場合は true
 */
const isValidRedirectUri = (uri: string): boolean => {
  try {
    const url = new URL(uri);
 
    // プロトコルチェック (localhost以外はhttps必須)
    const isLocalhost =
      url.hostname === "localhost" || url.hostname === "127.0.0.1";
    if (url.protocol !== "https:" && !isLocalhost) {
      return false;
    }
    // localhostは常に許可する (開発環境での動作確認のため)
    if (isLocalhost) {
      return true;
    }
 
    // 環境変数から設定を読み込む
    const allowedOrigins = (process.env.ALLOWED_REDIRECT_ORIGINS || "")
      .split(";")
      .map((origin) => origin.trim())
      .filter((origin) => origin.length > 0);
 
    const allowedPattern = process.env.ALLOWED_REDIRECT_PATTERN;
 
    // 1. 完全一致チェック (オリジンベース)
    if (allowedOrigins.includes(url.origin)) {
      return true;
    }
 
    // 2. 正規表現チェック (必要な場合)
    // セキュリティのため、URL全体ではなくオリジンに対して検証を行う
    Eif (allowedPattern) {
      const regex = new RegExp(allowedPattern);
      Eif (regex.test(url.origin)) {
        return true;
      }
    }
 
    return false;
  } catch {
    return false; // URLパースエラー等は無効とみなす
  }
};
 
/**
 * Stateパラメータをデコードし、Firebase UIDとリダイレクトURIを取得するヘルパー関数
 *
 * @param state クエリパラメータから取得したstate文字列
 * @returns デコードされたオブジェクト { firebaseUid, redirectUri }
 */
const decodeState = (
  state: string,
): { firebaseUid: string; redirectUri: string } => {
  if (!state) {
    throw new ValidationError("Invalid request: state parameter is missing.");
  }
 
  let firebaseUid, redirectUri;
  try {
    const decodedState = JSON.parse(
      Buffer.from(state, "base64").toString("utf8"),
    );
    firebaseUid = decodedState.firebaseUid;
    redirectUri = decodedState.redirectUri;
  } catch (e: any) {
    throw new ValidationError(
      `Invalid state: could not decode state parameter. Error: ${e.message}`,
    );
  }
 
  if (!firebaseUid) {
    throw new ValidationError("Invalid state: Firebase UID is missing.");
  }
 
  return { firebaseUid, redirectUri };
};
 
/**
 * OAuth認証リクエストを処理する関数
 *
 * @param req リクエストオブジェクト
 * @param res レスポンスオブジェクト
 * @param clientId FitbitクライアントID
 * @param clientSecret Fitbitクライアントシークレット
 */
const handleOAuthRequest = async (
  req: any,
  res: any,
  clientId: string,
  clientSecret: string,
) => {
  const { firebaseUid, redirectUri } = decodeState(req.query.state as string);
 
  await exchangeCodeForTokens(
    clientId,
    clientSecret,
    req.query.code as string,
    firebaseUid,
  );
 
  if (redirectUri) {
    if (!isValidRedirectUri(redirectUri)) {
      throw new ValidationError("Invalid redirect URI.");
    }
    const redirectUrl = new URL(redirectUri);
    // クエリパラメータでFitbitユーザーIDの代わりにFirebase UIDを使用
    redirectUrl.searchParams.set("uid", firebaseUid);
    res.redirect(302, redirectUrl.toString());
    return;
  }
  res
    .status(200)
    .send(
      `Authorization successful! User UID: ${firebaseUid}. You can close this page.`,
    );
};
 
/**
 * Fitbit OAuth 2.0 認証のコールバック処理を行う Cloud Function。
 *
 * @param req Express互換のリクエストオブジェクト
 * @param res Express互換のレスポンスオブジェクト
 */
export const oauthHandler: HttpFunction = async (req, res) => {
  // CORSプリフライトリクエストに対応するためのヘッダーを設定
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  res.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
 
  // OPTIONSメソッドはCORSプリフライトリクエスト。ヘッダーを付与して204で即時終了する。
  if (req.method === "OPTIONS") {
    res.status(204).send("");
    return;
  }
 
  try {
    // 環境変数からFitbit認証情報を取得
    const clientId = process.env.FITBIT_CLIENT_ID;
    const clientSecret = process.env.FITBIT_CLIENT_SECRET;
 
    // 必要な環境変数のチェック
    if (!process.env.OAUTH_FITBIT_REDIRECT_URI) {
      throw new Error(
        "OAUTH_FITBIT_REDIRECT_URI 環境変数が設定されていません。",
      );
    }
 
    if (!clientId || !clientSecret) {
      throw new Error(
        "FITBIT_CLIENT_ID and FITBIT_CLIENT_SECRET environment variables must be set",
      );
    }
 
    // OAuthコールバック: 認証コードをトークンと交換
    if (req.method === "GET" && req.query.code) {
      await handleOAuthRequest(req, res, clientId, clientSecret);
      return;
    }
 
    throw new MethodNotAllowedError("Method Not Allowed");
  } catch (error: any) {
    handleError(res, error);
    return;
  }
};