0 ) ? $lifetime : self::DEFAULT_COOKIE_LIFETIME; } /** * ワンタイムトークンの有効期間(秒)。 * * @return int */ public function get_token_lifetime() { /** * ワンタイムアクセスリンクの有効期間(秒)。 * * @since 3.0.0 * * @param int $lifetime 既定 86400(24時間)。 */ $lifetime = (int) apply_filters( 'acscw_access_token_lifetime', self::DEFAULT_TOKEN_LIFETIME ); return ( $lifetime > 0 ) ? $lifetime : self::DEFAULT_TOKEN_LIFETIME; } /* * ----------------------------------------------------------------------- * 署名付き Cookie * ----------------------------------------------------------------------- */ /** * Cookie の値を組み立てる。 * * 形式: base64url( email|expires ) . '.' . hmac * * @param string $email メールアドレス。 * @param int $expires 失効 Unix 時刻。 * @return string 失敗時は空文字。 */ public function build_cookie_value( $email, $expires ) { $email = ACSCW_Access::normalize_email( $email ); if ( '' === $email ) { return ''; } $payload = $email . '|' . (int) $expires; $encoded = self::base64url_encode( $payload ); $signature = hash_hmac( self::ALGO, $encoded, $this->get_signing_key() ); return $encoded . '.' . $signature; } /** * Cookie の値を検証する。 * * @param string $raw Cookie の生値。 * @return array|false array{email:string,expires:int}。不正・期限切れなら false。 */ public function verify_cookie_value( $raw ) { $raw = (string) $raw; if ( '' === $raw || substr_count( $raw, '.' ) !== 1 ) { return false; } list( $encoded, $signature ) = explode( '.', $raw, 2 ); if ( '' === $encoded || '' === $signature ) { return false; } $expected = hash_hmac( self::ALGO, $encoded, $this->get_signing_key() ); // タイミング攻撃を避けるため hash_equals で比較する。 if ( ! hash_equals( $expected, $signature ) ) { return false; } $payload = self::base64url_decode( $encoded ); if ( false === $payload || false === strpos( $payload, '|' ) ) { return false; } $parts = explode( '|', $payload ); $expires = (int) array_pop( $parts ); $email = ACSCW_Access::normalize_email( implode( '|', $parts ) ); if ( '' === $email || $expires <= time() ) { return false; } return array( 'email' => $email, 'expires' => $expires, ); } /** * 署名付き Cookie を発行する。 * * @param string $email メールアドレス。 * @param int $lifetime 有効期間(秒)。0 で既定値。 * @return bool 発行できたかどうか。 */ public function issue_cookie( $email, $lifetime = 0 ) { $email = ACSCW_Access::normalize_email( $email ); if ( '' === $email ) { return false; } $lifetime = ( $lifetime > 0 ) ? (int) $lifetime : $this->get_cookie_lifetime(); $expires = time() + $lifetime; $value = $this->build_cookie_value( $email, $expires ); if ( '' === $value ) { return false; } // 同一リクエスト内の後続処理が読めるようにしておく。 $this->resolved_email = $email; $_COOKIE[ self::get_cookie_name() ] = $value; if ( headers_sent() ) { // ヘッダ送出後は Cookie を出せない。値の橋渡しだけ済ませて false を返す。 return false; } self::set_cookie( self::get_cookie_name(), $value, $expires ); /** * アクセス Cookie を発行した後に発火する。 * * @since 3.0.0 * * @param string $email メールアドレス。 * @param int $expires 失効 Unix 時刻。 */ do_action( 'acscw_access_cookie_issued', $email, $expires ); return true; } /** * Cookie を破棄する(読者側の「別のメールアドレスを使う」導線用)。 * * @return void */ public function clear_cookie() { $this->resolved_email = ''; $this->resolved_order_ids = array(); unset( $_COOKIE[ self::get_cookie_name() ], $_COOKIE[ self::get_order_cookie_name() ] ); if ( headers_sent() ) { return; } self::set_cookie( self::get_cookie_name(), '', time() - DAY_IN_SECONDS ); self::set_cookie( self::get_order_cookie_name(), '', time() - DAY_IN_SECONDS ); } /** * 注文単位 Cookie の値を組み立てる。 * * 形式: base64url( 注文ID,注文ID|expires ) . '.' . hmac * 署名対象の先頭に 'orders.' を付け、メールアドレス単位 Cookie の値を * こちらに流用できない(逆も同じ)ようにする。 * * @param int[] $order_ids 注文ID。 * @param int $expires 失効 Unix 時刻。 * @return string 失敗時は空文字。 */ public function build_order_cookie_value( $order_ids, $expires ) { $order_ids = array_values( array_unique( array_filter( array_map( 'absint', (array) $order_ids ) ) ) ); if ( empty( $order_ids ) ) { return ''; } $encoded = self::base64url_encode( implode( ',', $order_ids ) . '|' . (int) $expires ); $signature = hash_hmac( self::ALGO, 'orders.' . $encoded, $this->get_signing_key() ); return $encoded . '.' . $signature; } /** * 注文単位 Cookie の値を検証する。 * * @param string $raw Cookie の生値。 * @return int[] 注文ID。不正・期限切れなら空配列。 */ public function verify_order_cookie_value( $raw ) { $raw = (string) $raw; if ( '' === $raw || substr_count( $raw, '.' ) !== 1 ) { return array(); } list( $encoded, $signature ) = explode( '.', $raw, 2 ); if ( '' === $encoded || '' === $signature ) { return array(); } $expected = hash_hmac( self::ALGO, 'orders.' . $encoded, $this->get_signing_key() ); if ( ! hash_equals( $expected, $signature ) ) { return array(); } $payload = self::base64url_decode( $encoded ); if ( false === $payload || 1 !== substr_count( $payload, '|' ) ) { return array(); } list( $ids, $expires ) = explode( '|', $payload, 2 ); if ( (int) $expires <= time() ) { return array(); } return array_values( array_unique( array_filter( array_map( 'absint', explode( ',', $ids ) ) ) ) ); } /** * 注文単位 Cookie に注文を1件足して発行する。 * * 読めるのは、その注文で付与されたコンテンツだけ(ACSCW_Access::has_access_for_orders())。 * * @param int $order_id 注文ID。 * @param int $lifetime 有効期間(秒)。0 で既定値。 * @return bool 発行できたかどうか。 */ public function issue_order_cookie( $order_id, $lifetime = 0 ) { $order_id = absint( $order_id ); if ( 0 === $order_id ) { return false; } $order_ids = $this->get_verified_order_ids(); $order_ids[] = $order_id; $order_ids = array_values( array_unique( $order_ids ) ); $order_ids = array_slice( $order_ids, -self::MAX_ORDER_IDS ); $lifetime = ( $lifetime > 0 ) ? (int) $lifetime : $this->get_cookie_lifetime(); $expires = time() + $lifetime; $value = $this->build_order_cookie_value( $order_ids, $expires ); if ( '' === $value ) { return false; } $this->resolved_order_ids = $order_ids; $_COOKIE[ self::get_order_cookie_name() ] = $value; if ( headers_sent() ) { return false; } self::set_cookie( self::get_order_cookie_name(), $value, $expires ); return true; } /** * 現在のリクエストで検証済みの、注文単位 Cookie の注文ID。 * * @return int[] */ public function get_verified_order_ids() { if ( null !== $this->resolved_order_ids ) { return $this->resolved_order_ids; } $name = self::get_order_cookie_name(); if ( empty( $_COOKIE[ $name ] ) ) { $this->resolved_order_ids = array(); return array(); } // phpcs:ignore WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___COOKIE, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The raw cookie is only ever fed to verify_order_cookie_value(), which rejects it unless the HMAC signature matches and casts every id with absint(). $this->resolved_order_ids = $this->verify_order_cookie_value( wp_unslash( $_COOKIE[ $name ] ) ); return $this->resolved_order_ids; } /** * 現在のリクエストで検証済みのメールアドレスを返す。 * * @return string 未検証・不正なら空文字。 */ public function get_verified_email() { if ( null !== $this->resolved_email ) { return $this->resolved_email; } $name = self::get_cookie_name(); if ( empty( $_COOKIE[ $name ] ) ) { $this->resolved_email = ''; return ''; } // Cookie 値は署名検証を通るまで信用しない。sanitize は検証後に normalize_email が行う。 // phpcs:ignore WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___COOKIE, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The raw cookie is only ever fed to verify_cookie_value(), which rejects it unless the HMAC signature matches; the payload is normalized there and never used as text before that. $verified = $this->verify_cookie_value( wp_unslash( $_COOKIE[ $name ] ) ); $this->resolved_email = $verified ? $verified['email'] : ''; return $this->resolved_email; } /** * 現在の読者がこのコンテンツを読めるかどうか。 * * フェーズ4の Paywall はこのメソッドだけを見ればよい。 * * @param int $post_id コンテンツID。 * @return bool */ public function current_reader_has_access( $post_id ) { $email = $this->get_verified_email(); $order_ids = $this->get_verified_order_ids(); if ( '' === $email && empty( $order_ids ) ) { return false; } $access = ACSCW_Plugin::instance()->get( 'access' ); if ( ! $access instanceof ACSCW_Access ) { return false; } if ( '' !== $email && $access->has_access( $post_id, $email ) ) { return true; } return ! empty( $order_ids ) && $access->has_access_for_orders( $post_id, $order_ids ); } /* * ----------------------------------------------------------------------- * ワンタイムリンク * ----------------------------------------------------------------------- */ /** * ワンタイムトークンを発行して保存する。 * * 保存するのはトークンのハッシュだけ。生の値はメール本文にしか存在しない。 * * @param string $email メールアドレス。 * @param int $post_id 戻り先のコンテンツID。0 で指定なし。 * @return string|WP_Error 生トークン。 */ public function create_one_time_token( $email, $post_id = 0 ) { $email = ACSCW_Access::normalize_email( $email ); if ( '' === $email ) { return new WP_Error( 'acscw_invalid_email', __( 'That email address is not valid.', 'acs-content-for-woocommerce' ) ); } $token = wp_generate_password( 48, false, false ); $stored = set_transient( self::TOKEN_TRANSIENT_PREFIX . self::hash_token( $token ), array( 'email' => $email, 'post_id' => absint( $post_id ), ), $this->get_token_lifetime() ); if ( ! $stored ) { return new WP_Error( 'acscw_token_store_failed', __( 'The access link could not be issued. Please try again later.', 'acs-content-for-woocommerce' ) ); } return $token; } /** * ワンタイムトークンを使い切る。 * * @param string $token 生トークン。 * @return array|false array{email:string,post_id:int}。無効なら false。 */ public function consume_one_time_token( $token ) { $token = preg_replace( '/[^A-Za-z0-9]/', '', (string) $token ); if ( '' === $token ) { return false; } $key = self::TOKEN_TRANSIENT_PREFIX . self::hash_token( $token ); $value = get_transient( $key ); // 使い捨て。読めた時点で必ず消す。 delete_transient( $key ); if ( ! is_array( $value ) || empty( $value['email'] ) ) { return false; } $email = ACSCW_Access::normalize_email( $value['email'] ); if ( '' === $email ) { return false; } return array( 'email' => $email, 'post_id' => isset( $value['post_id'] ) ? absint( $value['post_id'] ) : 0, ); } /** * ワンタイムリンクの URL を組み立てる。 * * @param string $token 生トークン。 * @param int $post_id 戻り先のコンテンツID。0 でトップページ。 * @return string */ public function build_access_url( $token, $post_id = 0 ) { $post_id = absint( $post_id ); $base = ( $post_id > 0 ) ? get_permalink( $post_id ) : home_url( '/' ); if ( ! $base ) { $base = home_url( '/' ); } return add_query_arg( self::QUERY_VAR, rawurlencode( $token ), $base ); } /** * ワンタイムリンクを開いたときの処理。 * * template_redirect(フロントの通常リクエスト)で動く。 * 検証に成功したら Cookie を発行し、クエリ変数を落として同じ URL へ戻す。 * URL にトークンを残さないことで、共有・ブラウザ履歴からの再利用を防ぐ。 * * ここに nonce は置かない(置けない)。このリンクはメールで届き、 * 受け取った人がどのセッションで開くか分からないため、送信時点で * 有効な nonce を作れない。代わりに 48 桁の使い捨てトークンそのものが * 資格情報になっている。第三者は値を知らないので発火させられず、 * 一度使えば無効になる(consume_one_time_token)。 * * @return void */ public function maybe_consume_access_link() { // 参照だけの読み取り。状態を変えるのはトークンが有効だったときのみ。 // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( empty( $_GET[ self::QUERY_VAR ] ) ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended $token = sanitize_text_field( wp_unslash( $_GET[ self::QUERY_VAR ] ) ); $result = $this->consume_one_time_token( $token ); if ( $result ) { $this->issue_cookie( $result['email'] ); } $redirect = remove_query_arg( self::QUERY_VAR ); /** * ワンタイムリンク処理後のリダイレクト先。 * * @since 3.0.0 * * @param string $redirect リダイレクト先 URL。 * @param bool $success トークンが有効だったかどうか。 */ $redirect = apply_filters( 'acscw_access_link_redirect', $redirect, (bool) $result ); if ( ! $result ) { // 失敗理由は URL に載せる(メールアドレスは載せない)。 $redirect = add_query_arg( 'acscw_notice', 'link_expired', $redirect ); } wp_safe_redirect( $redirect ); exit; } /* * ----------------------------------------------------------------------- * アクセス復旧リクエスト(フェーズ4のモーダルから呼ばれる想定) * ----------------------------------------------------------------------- */ /** * アクセス復旧リンクの送信を要求する。 * * 購入が無いメールアドレスでも同じ結果を返す(メールアドレスの存在推測を防ぐ)。 * 実際に送るのは購入があった場合だけ。 * * @param string $email メールアドレス。 * @param int $post_id 戻り先のコンテンツID。0 で指定なし。 * @return true|WP_Error 形式不正・レート超過のときだけ WP_Error。 */ public function request_access_link( $email, $post_id = 0 ) { $email = ACSCW_Access::normalize_email( $email ); if ( '' === $email ) { return new WP_Error( 'acscw_invalid_email', __( 'That email address is not valid.', 'acs-content-for-woocommerce' ) ); } $rate = $this->check_rate_limit( $email ); if ( is_wp_error( $rate ) ) { return $rate; } $this->mark_rate_limit( $email ); $plugin = ACSCW_Plugin::instance(); $access = $plugin->get( 'access' ); $mailer = $plugin->get( 'mailer' ); if ( ! $access instanceof ACSCW_Access || ! $mailer instanceof ACSCW_Mailer ) { return new WP_Error( 'acscw_not_ready', __( 'This action cannot be accepted right now.', 'acs-content-for-woocommerce' ) ); } // 購入が無い場合も true を返す。ここで分岐を漏らすとメール存在確認器になる。 if ( ! $access->has_any_access( $email ) ) { return true; } $token = $this->create_one_time_token( $email, $post_id ); if ( is_wp_error( $token ) ) { return $token; } $mailer->send_access_link( $email, $this->build_access_url( $token, $post_id ), time() + $this->get_token_lifetime() ); return true; } /* * ----------------------------------------------------------------------- * レートリミット * ----------------------------------------------------------------------- */ /** * メールアドレスと IP の送信間隔・回数を確認する。 * * transient のキーにはメールアドレスも IP も生では入れない(ハッシュ化する)。 * * @param string $email メールアドレス。 * @return true|WP_Error */ public function check_rate_limit( $email ) { /** * 同一メールアドレスへの再送を許すまでの秒数。 * * @since 3.0.0 * * @param int $interval 既定 180秒。 */ $interval = max( 0, (int) apply_filters( 'acscw_access_link_interval', 180 ) ); /** * 同一 IP から1時間に送れる回数の上限。 * * @since 3.0.0 * * @param int $max 既定 10回。 */ $ip_max = max( 1, (int) apply_filters( 'acscw_access_link_ip_hourly_max', 10 ) ); if ( $interval > 0 && get_transient( $this->get_rate_key( 'e', $email ) ) ) { return new WP_Error( 'acscw_rate_limited', __( 'An access link was sent a moment ago. If the email has not arrived, check your spam folder and try again in a little while.', 'acs-content-for-woocommerce' ) ); } $ip_count = (int) get_transient( $this->get_rate_key( 'i', $this->get_client_ip() ) ); if ( $ip_count >= $ip_max ) { return new WP_Error( 'acscw_rate_limited', __( 'You have reached the sending limit. Please wait a while and try again.', 'acs-content-for-woocommerce' ) ); } return true; } /** * 送信したことを記録する。 * * @param string $email メールアドレス。 * @return void */ public function mark_rate_limit( $email ) { $interval = max( 0, (int) apply_filters( 'acscw_access_link_interval', 180 ) ); if ( $interval > 0 ) { set_transient( $this->get_rate_key( 'e', $email ), 1, $interval ); } $ip_key = $this->get_rate_key( 'i', $this->get_client_ip() ); $ip_count = (int) get_transient( $ip_key ); set_transient( $ip_key, $ip_count + 1, HOUR_IN_SECONDS ); } /** * レートリミット用の transient キーを作る。 * * @param string $scope 'e'(メール)または 'i'(IP)。 * @param string $value 生の値。 * @return string */ private function get_rate_key( $scope, $value ) { return self::RATE_TRANSIENT_PREFIX . $scope . '_' . substr( hash_hmac( self::ALGO, (string) $value, $this->get_signing_key() ), 0, 32 ); } /** * クライアント IP を取得する。 * * WooCommerce が入っている前提なので WC_Geolocation を優先する * (プロキシ配慮を WooCommerce と同じ基準にそろえる)。 * * @return string */ private function get_client_ip() { if ( class_exists( 'WC_Geolocation' ) ) { return (string) WC_Geolocation::get_ip_address(); } if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { return (string) sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); } return ''; } /* * ----------------------------------------------------------------------- * 低レベルユーティリティ * ----------------------------------------------------------------------- */ /** * Cookie を送出する。 * * @param string $name Cookie 名。 * @param string $value 値。 * @param int $expires 失効 Unix 時刻。 * @return void */ private static function set_cookie( $name, $value, $expires ) { $options = array( 'expires' => (int) $expires, 'path' => defined( 'COOKIEPATH' ) && COOKIEPATH ? COOKIEPATH : '/', 'domain' => defined( 'COOKIE_DOMAIN' ) ? COOKIE_DOMAIN : '', 'secure' => is_ssl(), 'httponly' => true, 'samesite' => 'Lax', ); /** * アクセス Cookie の送出オプション。 * * @since 3.0.0 * * @param array $options setcookie() のオプション配列。 * @param string $name Cookie 名。 */ $options = apply_filters( 'acscw_access_cookie_options', $options, $name ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.cookies_setcookie setcookie( $name, $value, $options ); } /** * トークンのハッシュ値を返す。 * * @param string $token 生トークン。 * @return string 64文字の16進文字列。 */ private static function hash_token( $token ) { return hash( self::ALGO, (string) $token ); } /** * URL 安全な base64 エンコード。 * * @param string $value 対象文字列。 * @return string */ private static function base64url_encode( $value ) { return rtrim( strtr( base64_encode( $value ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64url encoding of a signed token, not obfuscation. } /** * URL 安全な base64 デコード。 * * @param string $value 対象文字列。 * @return string|false */ private static function base64url_decode( $value ) { $value = strtr( (string) $value, '-_', '+/' ); $pad = strlen( $value ) % 4; if ( $pad > 0 ) { $value .= str_repeat( '=', 4 - $pad ); } return base64_decode( $value, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- base64url decoding of a signed token, not obfuscation. } }