Add "scope" option to connect command
[shpub.git] / src / shpub / Command / Connect.php
1 <?php
2 namespace shpub;
3
4 /**
5  * @link http://micropub.net/draft/
6  * @link http://indieweb.org/authorization-endpoint
7  */
8 class Command_Connect
9 {
10     public static $client_id = 'http://cweiske.de/shpub.htm';
11
12     public function __construct(Config $cfg)
13     {
14         $this->cfg = $cfg;
15     }
16
17     public static function opts(\Console_CommandLine $optParser)
18     {
19         $cmd = $optParser->addCommand('connect');
20         $cmd->description = 'Obtain access token from a micropub server';
21         $cmd->addOption(
22             'force',
23             array(
24                 'short_name'  => '-f',
25                 'long_name'   => '--force-update',
26                 'description' => 'Force token update if token already available',
27                 'action'      => 'StoreTrue',
28                 'default'     => false,
29             )
30         );
31         $cmd->addOption(
32             'scope',
33             array(
34                 'short_name'  => '-s',
35                 'long_name'   => '--scope',
36                 'description' => 'Space-separated list of scopes to request (default create)',
37                 'action'      => 'StoreString',
38                 'default'     => 'create',
39             )
40         );
41         $cmd->addArgument(
42             'server',
43             [
44                 'optional'    => false,
45                 'description' => 'Server URL',
46             ]
47         );
48         $cmd->addArgument(
49             'user',
50             [
51                 'optional'    => true,
52                 'description' => 'User URL',
53             ]
54         );
55         $cmd->addArgument(
56             'key',
57             [
58                 'optional'    => true,
59                 'description' => 'Short name (key)',
60             ]
61         );
62     }
63
64     public function run($server, $user, $newKey, $force, $scope)
65     {
66         $server = Validator::url($server, 'server');
67         if ($user === null) {
68             //indieweb: homepage is your identity
69             $user = $server;
70         } else {
71             $user = Validator::url($user, 'user');
72         }
73
74         $host = $this->getHost($newKey != '' ? $newKey : $server, $force);
75         if ($host === null) {
76             //already taken
77             return;
78         }
79         if ($host->endpoints->incomplete()) {
80             $host->server = $server;
81             $host->loadEndpoints();
82         }
83
84         list($redirect_uri, $socketStr) = $this->getHttpServerData();
85         $state = time();
86         Log::msg(
87             "To authenticate, open the following URL:\n"
88             . $this->getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
89         );
90
91         $authParams = $this->startHttpServer($socketStr);
92         if ($authParams['state'] != $state) {
93             Log::err('Wrong "state" parameter value: ' . $authParams['state']);
94             exit(2);
95         }
96         $code    = $authParams['code'];
97         $userUrl = $authParams['me'];
98
99         $accessToken = $this->fetchAccessToken(
100             $host, $userUrl, $code, $redirect_uri, $state
101         );
102
103         //all fine. update config
104         $host->user  = $userUrl;
105         $host->token = $accessToken;
106
107         if ($newKey != '') {
108             $hostKey = $newKey;
109         } else {
110             $hostKey = $this->cfg->getHostByName($server);
111             if ($hostKey === null) {
112                 $keyBase = parse_url($host->server, PHP_URL_HOST);
113                 $newKey  = $keyBase;
114                 $count = 0;
115                 while (isset($this->cfg->hosts[$newKey])) {
116                     $newKey = $keyBase . ++$count;
117                 }
118                 $hostKey = $newKey;
119             }
120         }
121         $this->cfg->hosts[$hostKey] = $host;
122         $this->cfg->save();
123         Log::info("Server configuration $hostKey saved successfully.");
124     }
125
126     protected function fetchAccessToken(
127         $host, $userUrl, $code, $redirect_uri, $state
128     ) {
129         $req = new \HTTP_Request2($host->endpoints->token, 'POST');
130         if (version_compare(PHP_VERSION, '5.6.0', '<')) {
131             //correct ssl validation on php 5.5 is a pain, so disable
132             $req->setConfig('ssl_verify_host', false);
133             $req->setConfig('ssl_verify_peer', false);
134         }
135         $req->setHeader('Content-Type: application/x-www-form-urlencoded');
136         $req->setBody(
137             http_build_query(
138                 [
139                     'grant_type'   => 'authorization_code',
140                     'me'           => $userUrl,
141                     'code'         => $code,
142                     'redirect_uri' => $redirect_uri,
143                     'client_id'    => static::$client_id,
144                     'state'        => $state,
145                 ]
146             )
147         );
148         $res = $req->send();
149         if (intval($res->getStatus() / 100) !== 2) {
150             Log::err('Failed to fetch access token');
151             Log::err('Server responded with HTTP status code ' . $res->getStatus());
152             Log::err($res->getBody());
153             exit(2);
154         }
155         if ($res->getHeader('content-type') == 'application/x-www-form-urlencoded') {
156             parse_str($res->getBody(), $tokenParams);
157         } elseif ($res->getHeader('content-type') == 'application/json') {
158             $tokenParams = json_decode($res->getBody(), true);
159         } else {
160             Log::err('Wrong content type in auth verification response');
161             exit(2);
162         }
163         if (!isset($tokenParams['access_token'])) {
164             Log::err('"access_token" missing');
165             exit(2);
166         }
167
168         $accessToken = $tokenParams['access_token'];
169         return $accessToken;
170     }
171
172     protected function getBrowserAuthUrl($host, $user, $redirect_uri, $state, $scope)
173     {
174         return $host->endpoints->authorization
175             . '?me=' . urlencode($user)
176             . '&client_id=' . urlencode(static::$client_id)
177             . '&redirect_uri=' . urlencode($redirect_uri)
178             . '&state=' . $state
179             . '&scope=' . urlencode($scope)
180             . '&response_type=code';
181     }
182
183     protected function getHost($keyOrServer, $force)
184     {
185         $host = new Config_Host();
186         $key = $this->cfg->getHostByName($keyOrServer);
187         if ($key !== null) {
188             $host = $this->cfg->hosts[$key];
189             if (!$force && $host->token != '') {
190                 Log::err('Token already available');
191                 return;
192             }
193         }
194         return $host;
195     }
196
197     protected function getHttpServerData()
198     {
199         $ip   = '127.0.0.1';
200         $port = 12345;
201
202         if (isset($_SERVER['SSH_CONNECTION'])) {
203             $parts = explode(' ', $_SERVER['SSH_CONNECTION']);
204             if (count($parts) >= 3) {
205                 $ip = $parts[2];
206             }
207         }
208         if (strpos($ip, ':') !== false) {
209             //ipv6
210             $ip = '[' . $ip . ']';
211         }
212
213         $redirect_uri = 'http://' . $ip . ':' . $port . '/callback';
214         $socketStr    = 'tcp://' . $ip . ':' . $port;
215         return [$redirect_uri, $socketStr];
216     }
217
218     protected function startHttpServer($socketStr)
219     {
220         $responseOk = "HTTP/1.0 200 OK\r\n"
221             . "Content-Type: text/plain\r\n"
222             . "\r\n"
223             . "Ok. You may close this tab and return to the shell.\r\n";
224         $responseErr = "HTTP/1.0 400 Bad Request\r\n"
225             . "Content-Type: text/plain\r\n"
226             . "\r\n"
227             . "Bad Request\r\n";
228
229         //5 minutes should be enough for the user to confirm
230         ini_set('default_socket_timeout', 60 * 5);
231         $server = stream_socket_server($socketStr, $errno, $errstr);
232         if (!$server) {
233             Log::err('Error starting HTTP server');
234             return false;
235         }
236
237         do {
238             $sock = stream_socket_accept($server);
239             if (!$sock) {
240                 Log::err('Error accepting socket connection');
241                 exit(1);
242             }
243
244             $headers = [];
245             $body    = null;
246             $content_length = 0;
247             //read request headers
248             while (false !== ($line = trim(fgets($sock)))) {
249                 if ('' === $line) {
250                     break;
251                 }
252                 $regex = '#^Content-Length:\s*([[:digit:]]+)\s*$#i';
253                 if (preg_match($regex, $line, $matches)) {
254                     $content_length = (int) $matches[1];
255                 }
256                 $headers[] = $line;
257             }
258
259             // read content/body
260             if ($content_length > 0) {
261                 $body = fread($sock, $content_length);
262             }
263
264             // send response
265             list($method, $url, $httpver) = explode(' ', $headers[0]);
266             if ($method == 'GET') {
267                 $parts = parse_url($url);
268                 if (isset($parts['path']) && $parts['path'] == '/callback'
269                     && isset($parts['query'])
270                 ) {
271                     parse_str($parts['query'], $query);
272                     if (isset($query['code'])
273                         && isset($query['state'])
274                         && isset($query['me'])
275                     ) {
276                         fwrite($sock, $responseOk);
277                         fclose($sock);
278                         return $query;
279                     }
280                 }
281             }
282
283             fwrite($sock, $responseErr);
284             fclose($sock);
285         } while (true);
286     }
287 }
288 ?>