Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,11 @@ Content sits on the Cool Shell in a grid of panels: Feed White, 8px, hairline-bo
- **Status:** the console is the one place with status colors, `success` (lane-1's green) and `warning` (lane-5's ochre) beside Rm Red. They only ever mark state (healthy, watch, failing; event levels; better or worse than the period before) and always come with an icon, a sign or a word. They are not lanes and never mark a person.
- **Charts:** drawn in SVG at their real size, one y-axis, hairline gridlines, mono 11px ticks. History is a 2px ink line; a forecast continues it as a dashed Muted Ink line over a 15% Muted Ink wash for its range, after a dashed Rail Gray "today" rule. Columns are at most 24px wide with a 2px surface gap between stacked segments. Hovering shows the inverted tooltip; every chart carries a screen-reader table.

### API Docs
The API docs use the Operations Console's shell (`ConsoleLayout`), for everyone, guests included: the wordmark with a bordered mono `api` chip, a sidebar grouping the guides under `guide`, the theme switch and "Back to /dev/null" (without an avatar for a guest). The header names the section and says in one line what it holds; on the right a mono `v1`.

- **Guides:** read like the site's other long pages, never a card per section: one Feed White sheet on the Cool Shell, 1160px wide, 8px and hairline-bordered, whose sections follow one another with a hairline between them, each under a Section heading that links to itself, a mono meta beside it when it has one. Prose at 15px, named values in a hairline list with mono keys like the settings, and code in the same code blocks as commits, highlighted on the server, its language above it. Signing a request shows its helpers under page tabs with the sliding Commit Blue underline, the client picked kept in the browser.

### Error Pages
403, 404, 429, 500 (outside debug), and 503 render one standalone `error` page, with no app shell, for guests and signed-in users alike. A broken rail: the wordmark sits on a node in the viewer's lane (Rail Gray for guests) whose segment fades out before reaching a hollow, dangling node. Beside it, a mono git-style line (`fatal: path '/x' does not exist in 'HEAD'`), a Headline sentence saying what happened, one muted sentence saying what to do, and a single primary button ("Back to your log", "Go to the home page", or "Try again" during maintenance). A 419 is not a page: it redirects back with an error toast.

Expand Down
4 changes: 3 additions & 1 deletion KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,9 @@ The read-only JSON API at `/api/v1` requires no authentication or token, except

Subscribe in a feed reader to `/@{handle}/feed.atom` for a profile's latest **50 approved top-level commits**, including image enclosures. Feeds are public and can be cached for five minutes.

Sources: [API routes](routes/api.php), [API controllers](app/Http/Controllers/Api), [feed generation](app/Actions/CreateUserFeed.php), [rate limits](app/Providers/AppServiceProvider.php).
The **API docs** at `/docs/api`, linked as **API** from the aside and the user menu, are readable by everyone. Five guides (Introduction, Authentication, Rate limits, Pagination, Errors) explain how the API works, including how to get a key approved and sign a request, with the rate limits and error codes read from the code. Authentication shows a signing helper once for each client: `devnull_sign` for the shell, `devnullHeaders()` for Laravel and Node.js.

Sources: [API routes](routes/api.php), [API controllers](app/Http/Controllers/Api), [feed generation](app/Actions/CreateUserFeed.php), [rate limits](app/Providers/AppServiceProvider.php), [docs page](app/Http/Controllers/ApiDocsController.php), [rate limits listed](app/Queries/ApiRateLimitsQuery.php), [error codes](app/Enums/ApiErrorCode.php), [examples](app/Services/ApiExamples.php), [guides](resources/js/pages/api-docs/guides).

### Signed API and devices

Expand Down
5 changes: 5 additions & 0 deletions app/Actions/CreateIssue.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@

final readonly class CreateIssue
{
/**
* How many issues someone may open on GitHub a day, however they open them.
*/
public const int MAX_PER_DAY = 10;

public function __construct(private GitHubProvider $github)
{
//
Expand Down
48 changes: 48 additions & 0 deletions app/Enums/ApiDocsSection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace App\Enums;

/**
* A page of the API docs: a guide to how the API works, in reading order.
*/
enum ApiDocsSection: string
{
case Introduction = 'introduction';
case Authentication = 'authentication';
case RateLimits = 'rate-limits';
case Pagination = 'pagination';
case Errors = 'errors';

public function title(): string
{
return match ($this) {
self::RateLimits => 'Rate limits',
default => $this->name,
};
}

public function description(): string
{
return match ($this) {
self::Introduction => 'What the API is for, and where it lives',
self::Authentication => 'Reading as anyone, or signing requests as someone',
self::RateLimits => 'How many requests a minute, and what happens past that',
self::Pagination => 'Following a list from one page to the next',
self::Errors => 'What went wrong, and the code that says which error it is',
};
}

/**
* @return array{slug: string, title: string, description: string}
*/
public function toArray(): array
{
return [
'slug' => $this->value,
'title' => $this->title(),
'description' => $this->description(),
];
}
}
25 changes: 25 additions & 0 deletions app/Enums/ApiErrorCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,29 @@ public function status(): int
self::GitHubSyncFailed => 503,
};
}

/**
* What the code means to someone building on the API, as the API docs list it.
*/
public function meaning(): string
{
return match ($this) {
self::InvalidSignature => 'The signature is missing, stale, already used, or does not match the request.',
self::DeviceNotApproved => 'The signature is right, but its key is not an approved device, or not any more.',
self::InvalidGrant => 'The sign-in code is unknown, expired or already used, was issued for another key, does not match the verifier, or its account was deleted since.',
self::UserBlocked => 'You blocked this person. The answer also has their profile, as user.',
self::UserUnavailable => 'This profile is not available to you.',
self::OwnCommit => 'You cannot report your own commit.',
self::CommitUnavailable => 'The commit you report does not exist, was deleted, is not published, or is not yours to see. Elsewhere, such a commit is a plain 404.',
self::PasteisExhausted => 'No pastéis left today.',
self::RateLimited => 'Too many requests. Wait the seconds Retry-After says.',
self::GitHubSyncFailed => 'GitHub did not answer. Try again in a minute.',
self::GitHubIssueRefused => 'GitHub did not create the issue, so trying again is safe.',
self::GitHubIssueUnanswered => 'GitHub did not answer, so the issue may exist: check the upstream issues before trying again.',
self::TimedOut => 'Moderators paused posting for this account for a while.',
self::Banned => 'The account is banned. All it can do is delete itself.',
self::CommitRulesRequired => 'The commit rules have to be accepted once, in the web composer.',
self::GuildPaused => 'The guild the commit posts to is paused until it has a moderator.',
};
}
}
36 changes: 36 additions & 0 deletions app/Http/Controllers/ApiDocsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Enums\ApiDocsSection;
use App\Enums\ApiErrorCode;
use App\Queries\ApiRateLimitsQuery;
use App\Services\ApiExamples;
use App\Services\ApiGuideSnippets;
use App\Services\PageMetadata;
use Inertia\Inertia;
use Inertia\Response;

final readonly class ApiDocsController
{
/**
* A page of the API docs, readable by everyone, with every section for the sidebar.
*/
public function show(ApiDocsSection $section, PageMetadata $metadata, ApiExamples $examples, ApiGuideSnippets $snippets, ApiRateLimitsQuery $rateLimits): Response
{
return Inertia::render('api-docs/show', [
'sections' => array_map(fn (ApiDocsSection $section): array => $section->toArray(), ApiDocsSection::cases()),
'current' => $section->value,
'signing' => $section === ApiDocsSection::Authentication ? $examples->signing() : [],
'rateLimits' => $section === ApiDocsSection::RateLimits ? $rateLimits->get() : [],
'snippets' => $snippets->for($section),
'errorCodes' => $section !== ApiDocsSection::Errors ? [] : array_map(fn (ApiErrorCode $code): array => ['code' => $code->value, 'status' => $code->status(), 'meaning' => $code->meaning()], ApiErrorCode::cases()),
])->withViewData(['preview' => $metadata->page(
$section->title().' - API docs - /dev/null',
$section->description().'. The JSON API the /dev/null apps use, open to anything you build.',
route('api-docs.show', $section),
)]);
}
}
4 changes: 1 addition & 3 deletions app/Http/Middleware/AuthenticateSignedRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
*/
final readonly class AuthenticateSignedRequest
{
private const int FailuresPerAddressPerMinute = 60;

public function __construct(private SignedRequests $signedRequests)
{
//
Expand All @@ -50,7 +48,7 @@ public function handle(Request $request, Closure $next, ?string $mode = null): R
// a ceiling on failures, so a key nobody approved can't make the API check signatures and spend nonces freely...
$failures = 'api-signature-failures:'.$request->ip();

throw_if(RateLimiter::tooManyAttempts($failures, self::FailuresPerAddressPerMinute), fn (): ApiException => new ApiException(ApiErrorCode::RateLimited, 'Too Many Attempts.', [
throw_if(RateLimiter::tooManyAttempts($failures, SignedRequests::FailuresPerAddressPerMinute), fn (): ApiException => new ApiException(ApiErrorCode::RateLimited, 'Too Many Attempts.', [
'Retry-After' => RateLimiter::availableIn($failures),
]));

Expand Down
5 changes: 2 additions & 3 deletions app/Http/Middleware/ThrottleCommits.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Enums\ApiErrorCode;
use App\Exceptions\ApiException;
use App\Models\Commit;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
Expand All @@ -15,8 +16,6 @@

final readonly class ThrottleCommits
{
private const int PER_MINUTE = 10;

/**
* One budget of commits a minute, however they are posted.
*
Expand All @@ -29,7 +28,7 @@ public function handle(Request $request, Closure $next): Response

$key = "commits:{$user->id}";

if (RateLimiter::tooManyAttempts($key, self::PER_MINUTE)) {
if (RateLimiter::tooManyAttempts($key, Commit::MAX_PER_MINUTE)) {
return $this->slowDown($request, RateLimiter::availableIn($key));
}

Expand Down
7 changes: 3 additions & 4 deletions app/Http/Middleware/ThrottleIssues.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Http\Middleware;

use App\Actions\CreateIssue;
use App\Enums\ApiErrorCode;
use App\Exceptions\ApiException;
use App\Models\User;
Expand All @@ -14,8 +15,6 @@

final readonly class ThrottleIssues
{
private const int PER_DAY = 10;

private const int DECAY_SECONDS = 86400;

/**
Expand All @@ -31,7 +30,7 @@ public function handle(Request $request, Closure $next): Response

$key = "issues:{$user->id}";

if (RateLimiter::tooManyAttempts($key, self::PER_DAY)) {
if (RateLimiter::tooManyAttempts($key, CreateIssue::MAX_PER_DAY)) {
return $this->tooMany($request, RateLimiter::availableIn($key));
}

Expand All @@ -46,7 +45,7 @@ public function handle(Request $request, Closure $next): Response

private function tooMany(Request $request, int $retryAfter): Response
{
$message = 'Issue limit reached: '.self::PER_DAY.' a day. Try again tomorrow.';
$message = 'Issue limit reached: '.CreateIssue::MAX_PER_DAY.' a day. Try again tomorrow.';

// The apps read JSON with a code...
if ($request->routeIs('api-issue.store')) {
Expand Down
5 changes: 5 additions & 0 deletions app/Models/Commit.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ final class Commit extends Model

public const int MAX_BODY_LENGTH = 4000;

/**
* How many commits someone may post a minute, however they post them.
*/
public const int MAX_PER_MINUTE = 10;

/**
* Lists show a longer body folded to its first characters and lines, the rest one click away.
*/
Expand Down
107 changes: 107 additions & 0 deletions app/Queries/ApiRateLimitsQuery.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

declare(strict_types=1);

namespace App\Queries;

use App\Actions\CreateIssue;
use App\Models\Commit;
use App\Models\User;
use App\Services\SignedRequests;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use LogicException;

/**
* Every budget an API request counts toward, for the Rate limits guide, read from the limiters and routes that set
* them rather than copied, so the guide changes when they do.
*/
final readonly class ApiRateLimitsQuery
{
private const array Units = [60 => 'minute', 3600 => 'hour', 86400 => 'day'];

/**
* @return list<array{what: string, limit: int, per: string}>
*/
public function get(): array
{
return [
...$this->limiter('Unsigned requests', 'api', signed: false, scope: 'per IP'),
...$this->limiter('Signed requests', 'api', scope: 'per person'),
$this->row('Signatures that fail to check out', SignedRequests::FailuresPerAddressPerMinute, 60, 'per IP'),
$this->row('Commits, replies and quotes, now or scheduled', Commit::MAX_PER_MINUTE, 60, 'shared with the web and the terminal'),
...$this->limiter('Commit searches', 'search'),
...$this->limiter('People searches, mention suggestions and profile cards', 'people'),
...$this->limiter('Issue suggestions', 'issue-suggestions'),
...$this->limiter('Stars', 'stars'),
...$this->limiter('Pins', 'pins'),
...$this->limiter('Follows', 'follows'),
$this->route('Pastéis', 'api-commit-pastel.store'),
$this->route('Translations', 'api-commit-translation.store'),
...$this->limiter('Reports', 'commit-reports'),
$this->route('Organization claims', 'api-organization-admin.store'),
...$this->limiter('Syncs from GitHub', 'profile-syncs'),
$this->route('Feature requests and bug reports', 'api-issue.store'),
$this->row('Feature requests and bug reports opened on GitHub', CreateIssue::MAX_PER_DAY, 86400, 'shared with the web'),
...$this->limiter('Reading and polling remotes', 'conversations'),
...$this->limiter('Messages', 'messages'),
...$this->limiter('Pings', 'pings'),
];
}

/**
* A named limiter's budgets, as it sets them for a signed request, or an unsigned one.
*
* @return list<array{what: string, limit: int, per: string}>
*/
private function limiter(string $what, string $name, bool $signed = true, ?string $scope = null): array
{
$limiter = RateLimiter::limiter($name);

throw_unless($limiter, fn (): LogicException => new LogicException("No rate limiter is named {$name}."));

$limits = array_filter(Arr::wrap($limiter($this->request($signed))), fn (mixed $limit): bool => $limit instanceof Limit);

return array_values(array_map(fn (Limit $limit): array => $this->row($what, $limit->maxAttempts, $limit->decaySeconds, $scope), $limits));
}

/**
* The budget a route sets itself, as `throttle:attempts,minutes`.
*
* @return array{what: string, limit: int, per: string}
*/
private function route(string $what, string $name): array
{
$throttle = collect(Route::getRoutes()->getByName($name)?->gatherMiddleware() ?? [])
->map(fn (mixed $middleware): array => is_string($middleware) && preg_match('/^throttle:(\d+),(\d+)/', $middleware, $match) === 1 ? [(int) $match[1], (int) $match[2]] : [])
->first(fn (array $throttle): bool => $throttle !== []);

throw_unless($throttle, fn (): LogicException => new LogicException("The route {$name} sets no budget of its own."));

return $this->row($what, $throttle[0], $throttle[1] * 60);
}

/**
* @return array{what: string, limit: int, per: string}
*/
private function row(string $what, int $limit, int $seconds, ?string $scope = null): array
{
$per = self::Units[$seconds] ?? "{$seconds} seconds";

return ['what' => $what, 'limit' => $limit, 'per' => $scope === null ? $per : "{$per}, {$scope}"];
}

private function request(bool $signed): Request
{
$request = Request::create('/api/v1', server: ['REMOTE_ADDR' => '192.0.2.1']);

if ($signed) {
$request->setUserResolver(fn (): User => new User()->forceFill(['id' => '00000000-0000-7000-8000-000000000000']));
}

return $request;
}
}
Loading