Skip to content
Open
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
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
*.html diff=html
*.md diff=markdown
*.php diff=php

resources/api/openapi.json linguist-generated=true
7 changes: 7 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,13 @@ 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 groups of the reference under `reference` and `openapi.json` under `elsewhere`, 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` and a bordered Search control with its `⌘K` cap.

- **Guides:** read like the site's other long pages, never a card per section: one Feed White sheet on the Cool Shell, as wide as the reference (1160px) so moving between them never changes the page's width, 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 the reference and commits, highlighted on the server, its language above it. Signing a request shows its helpers under the same example tabs as the endpoints, in step with them.
- **Endpoints:** one panel each, folded to a row: a mono method chip, the mono path with its `{parameters}` muted, the truncated summary, and a bordered mono `public` or `signed` chip, the signed one with a lock. Being the console's, the docs use its status colors, by what a request does rather than by state: GET reads in `success`, POST, PUT and PATCH write in `warning`, DELETE in Rm Red, and a `signed` chip is `warning` while a `public` one stays muted. Each is a 10% wash with its text mixed 70% with the ink, so 12px stays readable; never blue, which only means "act here". Unfolded, it splits from lg into the endpoint on the left (parameters, body and answers, fields as rows with a mono name and type, a `required` chip tinted `warning` like a signed one, as something the caller has to give, enum values as mono chips, and the fields inside folded behind a Commit Blue "Show N fields") and its examples on the right, sticky, under page tabs with the sliding Commit Blue underline, in the commits' code blocks. An error every endpoint shares carries a Commit Blue "see Errors" link instead of its fields. A bordered mono `fields | schema` pair on each part, the picked one on the Blue Wash, swaps that part's body, responses or errors for its JSON schema in a code block, scrolling past 32rem, loaded only then: the fields stay in place until it arrives, dimmed under a mono "Loading the schema…" once it takes more than 300ms, and a failure lies over them, a one-line mono `fatal: no schema` with a Try again that keeps keyboard focus on the endpoint, while a screen reader hears once per endpoint that its schema could not be loaded. Picking a client picks it everywhere; a view is picked for its part alone. In the sticky examples column, only the example shown takes room, so the column follows the endpoint to its end.
- **Search:** the People Search palette's shell and keys, listing guides with their book icon and endpoints with their method chip, path and summary, the group in mono on the right; nothing found reads mono `fatal: nothing matches '…'`.

### 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 @@ -574,7 +574,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, and the reference lists every endpoint but those only the apps need to work (signing in, the Mac app's update check, live updates, the web session, signed media URLs) by group, listed alphabetically (Commits, Headlines, Issues, Me, Notifications, Organizations, Remotes, Scheduled commits, Search, Users): its path and query parameters, the body it takes, what it answers and its errors apart, with the fields of a successful answer and of an error only it answers with, and how to call it with curl, Laravel's HTTP client or fetch. A signed example calls a signing helper that Authentication shows once for each client: `devnull_sign` for the shell, `devnullHeaders()` for Laravel and Node.js. An endpoint's body, responses and errors each read as fields or, on request for that part, as its JSON schema, each schema it refers to written once in its `$defs`; a schema is only loaded when shown. A request with images takes its fields as JSON, or as a signed multipart upload of that JSON beside the images. The client picked is shown on every endpoint, and kept in the browser. ⌘K, Ctrl+K or `/` searches the guides and endpoints. The reference is read from the API's OpenAPI 3.1 spec, generated from the code by Scramble in development and committed as `resources/api/openapi.json`; a test fails when the code and the committed spec disagree, and `composer generate:openapi` writes it again from a migrated database. Anyone can fetch it at `/api/v1/openapi.json`, unsigned, cached for an hour, to import it into Postman, Bruno or Insomnia, or generate a client.

Sources: [API routes](routes/api.php), [API controllers](app/Http/Controllers/Api), [feed generation](app/Actions/CreateUserFeed.php), [rate limits](app/Providers/AppServiceProvider.php), [OpenAPI configuration](app/Providers/ApiDocumentationServiceProvider.php), [spec](resources/api/openapi.json), [docs page](app/Http/Controllers/ApiDocsController.php), [reference](app/Queries/ApiDocsQuery.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
99 changes: 99 additions & 0 deletions app/Enums/ApiDocsSection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

declare(strict_types=1);

namespace App\Enums;

/**
* A page of the API docs: a guide to how the API works, or a group of its reference, named after the first segment of
* the paths it lists, as the OpenAPI spec groups them.
*/
enum ApiDocsSection: string
{
case Introduction = 'introduction';
case Authentication = 'authentication';
case RateLimits = 'rate-limits';
case Pagination = 'pagination';
case Errors = 'errors';
case Users = 'users';
case Commits = 'commits';
case Organizations = 'organizations';
case Me = 'me';
case Search = 'search';
case ScheduledCommits = 'scheduled-commits';
case Remotes = 'remotes';
case Notifications = 'notifications';
case Headlines = 'headlines';
case Issues = 'issues';

/**
* The guides in reading order, then the groups of the reference.
*
* @return list<self>
*/
public static function ordered(): array
{
return [...array_values(array_filter(self::cases(), fn (self $section): bool => $section->isGuide())), ...self::reference()];
}

/**
* The groups of the reference alphabetically, so a reader finds one by its name, wherever they are listed.
*
* @return list<self>
*/
public static function reference(): array
{
$groups = array_values(array_filter(self::cases(), fn (self $section): bool => ! $section->isGuide()));
usort($groups, fn (self $a, self $b): int => strcmp($a->title(), $b->title()));

return $groups;
}

public function isGuide(): bool
{
return in_array($this, [self::Introduction, self::Authentication, self::RateLimits, self::Pagination, self::Errors], true);
}

public function title(): string
{
return match ($this) {
self::RateLimits => 'Rate limits',
self::ScheduledCommits => 'Scheduled commits',
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',
self::Users => 'Profiles, what they committed, and who follows whom',
self::Commits => 'Reading, writing, starring and replying to commits',
self::Organizations => 'GitHub organizations, their commits and their mentions',
self::Me => 'The signed-in user: their account, settings and devices',
self::Search => 'People, organizations and commits, by name or meaning',
self::ScheduledCommits => 'Commits waiting for their time to be posted',
self::Remotes => 'Conversations, orgs, messages and calls',
self::Notifications => 'What happened to the user, grouped as the inbox shows it',
self::Headlines => 'Hot topics: the headlines the aside shows, each with its recap',
self::Issues => 'Feature requests and bug reports, opened on GitHub',
};
}

/**
* @return array{slug: string, title: string, description: string, kind: 'guide'|'reference'}
*/
public function toArray(): array
{
return [
'slug' => $this->value,
'title' => $this->title(),
'description' => $this->description(),
'kind' => $this->isGuide() ? 'guide' : 'reference',
];
}
}
24 changes: 24 additions & 0 deletions app/Enums/ApiErrorCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,28 @@ 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.',
};
}
}
20 changes: 20 additions & 0 deletions app/Http/Controllers/Api/OpenApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\File;

final readonly class OpenApiController
{
/**
* The OpenAPI spec of this API, as committed from what the code describes, for anyone building on it. Public and
* unsigned, like the docs page that reads it. It is sent whole rather than streamed, so its ETag can be computed.
*/
public function show(): Response
{
return response(File::get(resource_path('api/openapi.json')), headers: ['Content-Type' => 'application/json']);
}
}
40 changes: 40 additions & 0 deletions app/Http/Controllers/ApiDocsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Enums\ApiDocsSection;
use App\Enums\ApiErrorCode;
use App\Queries\ApiDocsQuery;
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, and the endpoints of a group
* of the reference. The search's index of every endpoint is sent once, and kept by the page across the visit.
*/
public function show(ApiDocsSection $section, PageMetadata $metadata, ApiDocsQuery $endpoints, ApiExamples $examples, ApiGuideSnippets $snippets, ApiRateLimitsQuery $rateLimits): Response
{
return Inertia::render('api-docs/show', [
'sections' => array_map(fn (ApiDocsSection $section): array => $section->toArray(), ApiDocsSection::ordered()),
'current' => $section->value,
'endpoints' => $section->isGuide() ? [] : $endpoints->get($section),
'index' => Inertia::once(fn (): array => $endpoints->index()),
'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),
)]);
}
}
26 changes: 26 additions & 0 deletions app/Http/Controllers/ApiDocsSchemaController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Enums\ApiDocsSection;
use App\Queries\ApiDocsQuery;
use Illuminate\Http\JsonResponse;

final readonly class ApiDocsSchemaController
{
/**
* The JSON schemas of an endpoint of the API docs, which the page asks for when a reader picks the schema view, so
* they never weigh on the page itself. The route only lets a section through, unbound since the route skips the
* web group.
*/
public function show(string $section, string $endpoint, ApiDocsQuery $query): JsonResponse
{
$schemas = $query->schemas(ApiDocsSection::from($section), $endpoint);

return $schemas === null
? response()->json(['message' => 'Not found.'], 404)
: response()->json($schemas);
}
}
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)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved the limit to CreateIssue::MAX_PER_DAY so the rate limits guide shows the number the middleware actually uses.

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
Loading