>, rate_limit?: bool}> */ abstract public function routes(): array; public function register(): void { foreach ($this->routes() as $route) { $callback = $route['callback']; if (!empty($route['rate_limit'])) { $callback = $this->rateLimited($callback); } register_rest_route(self::NAMESPACE, $route['path'], [ 'methods' => $route['methods'], 'callback' => $callback, 'permission_callback' => $this->permission(self::routeKey($route['path']), $route['capability']), 'args' => $route['args'] ?? [], ]); } } /** * Hands this controller the Settings › Access rows its routes resolve tokens against. * Plugin::controllers() calls it on everything the `alpaca_bot/rest/controllers` filter hands * back, a third party's subclass included, so a route registered through that filter may * declare self::CHAT and get the row this site saved. A controller nobody called this on (a * test, a site registering one by hand) resolves the token to Access::defaults() instead — * the shipped default, never an unresolved literal. * * @since 0.6.0 */ public function useAccess(Access $access): void { $this->access = $access; } /** * The permission callback for a route whose declared capability is `$capability` — a * capability name, self::CHAT for a route that follows the Chat row of Settings › Access, or * whatever token an overriding subclass declares. capability() resolves that per request, and * the filter it applies sees the request, so a site can tighten (or, for a route it exposes to * subscribers, loosen) per request. * * Only a capability name is honoured, and Capability::filtered() is where that rule lives: * a filter returning a bool or a number would otherwise cast to a legacy user-level check * and open the route rather than close it. The admin menu's filter goes through the same * guard. */ public function permission(string $route, string $capability): \Closure { return function (\WP_REST_Request $request) use ($route, $capability): bool|\WP_Error { return current_user_can($this->capability($route, $capability, $request)) ? true : Errors::forbidden(); }; } /** * What one row of Settings › Access resolves to here, for a controller that may not have been * handed an Access: the row through its own filter, or the row's shipped default when nothing * handed this controller one. Access::effective() fires no filter for self::CHAT — that row's * hooks are the menu's and each route's, and Access owns that rule — so a chat route's only * filter is still the one capability() applies. * * This is the seam a subclass overriding capability() resolves its rows through, rather than * reaching for the Access object: the null case is answered once, here, so an override never * null-checks, and nothing has to build a second Access over the same Store — Plugin::register() * keeps one per request on purpose, and a second would read the settings option again. * * `$args` are the row's own, passed straight through. Access::expectedArgs() fixes how many * each row fires with and effective() throws when handed fewer, which is a programming error * and stays loud. A row Access::defaults() does not list falls back to `manage_options`, * so a row nobody declared fails closed rather than open. * * @param mixed ...$args the arguments this row's filter fires with, Access::expectedArgs() of them * @throws \InvalidArgumentException when fewer than Access::expectedArgs($row) arguments are passed * @since 0.6.0 */ protected function accessRow(string $row, mixed ...$args): string { return $this->access?->effective($row, ...$args) ?? (Access::defaults()[$row] ?? 'manage_options'); } /** * The capability this route's permission callback checks for this request: the route's * declared capability — or, for self::CHAT, the Chat row of Settings › Access — through the * route's own filter. Overridable, so a subclass can resolve a route of its own some other * way — accessRow() is how it reaches another row — and fall back here for the rest. * * The row is read here rather than in routes(): routes() is called from register(), on * `rest_api_init`, which fires for every REST request the site serves, `/wp/v2/*` included, * while this runs only for a request that has reached one of these routes — and then through * the memoised Store, which reads the settings option at most once per request however many * rows are asked. */ protected function capability(string $route, string $declared, \WP_REST_Request $request): string { $default = $declared === self::CHAT ? $this->accessRow(self::CHAT) : $declared; return RouteCapability::filtered($route, $default, $request); } /** * The filter key for a route path: leading slash off, regex groups out, so `/conversations` * and `/conversations/(?P\d+)` share `conversations` (one filter covers the collection and * the item) while `/chat/(?P\d+)/stream` is `chat/stream`. Only simple named groups * (no nested parentheses) are recognised, which is all the plugin's routes use. */ public static function routeKey(string $path): string { return trim((string) preg_replace('#/\(\?P<[^)]+\)[^/]*#', '', $path), '/'); } protected function userId(): int { return (int) get_current_user_id(); } /** * Wraps `$callback` so an exhausted bucket answers 429 without running it. Routes are * limited together under the 'chat' bucket: the limiter guards model spend, and calls out to * other hosts, per person, and one person opening two such routes is still one person. * * The refusal is a WP_REST_Response built from Errors::tooMany() rather than the WP_Error * itself: core renders a WP_Error's status and body but has nowhere to carry a header, and * Retry-After is the one thing a well-behaved client needs from a 429. */ private function rateLimited(callable $callback): \Closure { return function (\WP_REST_Request $request) use ($callback): mixed { $hit = (new RateLimit())->hit($this->userId(), 'chat'); if (!$hit['allowed']) { $response = rest_convert_error_to_response(Errors::tooMany($hit['retry_after'])); $response->header('Retry-After', (string) $hit['retry_after']); return $response; } return $callback($request); }; } }