403 ) ); } if ( ! McpPermissionLevel::isValid( $level ) ) { return new WP_Error( 'aipt_mcp_invalid_permission_level', __( 'That permission level is not recognized.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $label = self::sanitizeLabel( $label ); return ConnectionCap::withSlot( function () use ( $user_id, $label, $level ) { return self::createConnectionAndKey( $user_id, $label, $level ); } ); } catch ( \Throwable $e ) { return new WP_Error( 'aipt_mcp_internal_error', __( 'The API key could not be created. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } } /** * Create the connection row and its first token together. Runs only * while {@see ConnectionCap::withSlot()} has confirmed a free slot. * * @param int $user_id Owner. * @param string $label Already-sanitized label. * @param string $level Already-validated permission level. * @return array{connection_id:int,key:string,label:string,permission_level:string,created_at:string}|WP_Error */ private static function createConnectionAndKey( int $user_id, string $label, string $level ) { $now = gmdate( 'Y-m-d H:i:s' ); $connection_store = new ConnectionStore(); $connection_id = $connection_store->create( array( 'auth_type' => ConnectionStore::AUTH_TYPE_API_KEY, 'user_id' => $user_id, 'label' => $label, 'permission_level' => $level, 'created_by_ip_hash' => self::clientIpHash(), 'now' => $now, ) ); if ( null === $connection_id ) { return new WP_Error( 'aipt_mcp_storage_failed', __( 'The API key could not be saved. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } $raw_key = TokenHasher::generate( McpOAuthConstants::API_KEY_PREFIX ); $token_store = new TokenStore(); $token_id = $token_store->insert( array( 'connection_id' => $connection_id, 'token_hash' => TokenHasher::hash( $raw_key ), 'token_type' => TokenStore::TOKEN_TYPE_API_KEY, 'permission_level' => $level, 'expires_at' => null, 'now' => $now, ) ); if ( null === $token_id ) { $connection_store->revoke( $connection_id, ConnectionStore::REVOKED_REASON_ISSUANCE_FAILED, 0, $now ); return new WP_Error( 'aipt_mcp_storage_failed', __( 'The API key could not be saved. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } self::writeAuditTrail( $connection_id, $user_id, $now ); return array( 'connection_id' => $connection_id, 'key' => $raw_key, 'label' => $label, 'permission_level' => $level, 'created_at' => $now, ); } /** * @param int $connection_id New connection's id. * @param int $user_id Owner. * @param string $now UTC datetime. * @return void */ private static function writeAuditTrail( int $connection_id, int $user_id, string $now ): void { $audit_store = new AuditLogStore(); $audit_store->write( array( 'connection_id' => $connection_id, 'user_id' => $user_id, 'event_type' => AuditLogStore::EVENT_CONNECTION_CREATED, 'outcome' => AuditLogStore::OUTCOME_SUCCESS, 'now' => $now, ) ); $audit_store->write( array( 'connection_id' => $connection_id, 'user_id' => $user_id, 'event_type' => AuditLogStore::EVENT_TOKEN_ISSUED, 'outcome' => AuditLogStore::OUTCOME_SUCCESS, 'now' => $now, ) ); } /** * Sanitize a merchant-supplied label: trimmed, capped, defaulted when empty. * * @param string $label Raw label. * @return string */ private static function sanitizeLabel( string $label ): string { $label = trim( sanitize_text_field( $label ) ); if ( '' === $label ) { return self::DEFAULT_LABEL; } return function_exists( 'mb_substr' ) ? mb_substr( $label, 0, self::MAX_LABEL_LENGTH ) : substr( $label, 0, self::MAX_LABEL_LENGTH ); } /** * Hash the requester's IP for `created_by_ip_hash`, matching the * `hash_hmac( 'sha256', $ip, wp_salt( 'auth' ) )` convention * {@see \AIPT\Api\Chatbot\RateLimiter::hashIp()} already uses. Returns * '' (the column default) rather than hashing an unverifiable value when * no valid REMOTE_ADDR is present. * * @return string */ private static function clientIpHash(): string { if ( empty( $_SERVER['REMOTE_ADDR'] ) ) { return ''; } $ip = sanitize_text_field( wp_unslash( (string) $_SERVER['REMOTE_ADDR'] ) ); if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return ''; } return hash_hmac( 'sha256', $ip, (string) wp_salt( 'auth' ) ); } }