diff --git a/DESIGN.md b/DESIGN.md index 1cb2aab6e5..1d6192fe55 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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. diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 1756750c87..72c1e6a878 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -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 diff --git a/app/Actions/CreateIssue.php b/app/Actions/CreateIssue.php index 21cb278e23..1bb9add020 100644 --- a/app/Actions/CreateIssue.php +++ b/app/Actions/CreateIssue.php @@ -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) { // diff --git a/app/Enums/ApiDocsSection.php b/app/Enums/ApiDocsSection.php new file mode 100644 index 0000000000..2a2364eb64 --- /dev/null +++ b/app/Enums/ApiDocsSection.php @@ -0,0 +1,48 @@ + '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(), + ]; + } +} diff --git a/app/Enums/ApiErrorCode.php b/app/Enums/ApiErrorCode.php index 8febaf9801..9cfa868185 100644 --- a/app/Enums/ApiErrorCode.php +++ b/app/Enums/ApiErrorCode.php @@ -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.', + }; + } } diff --git a/app/Http/Controllers/ApiDocsController.php b/app/Http/Controllers/ApiDocsController.php new file mode 100644 index 0000000000..1f059bece5 --- /dev/null +++ b/app/Http/Controllers/ApiDocsController.php @@ -0,0 +1,36 @@ + 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), + )]); + } +} diff --git a/app/Http/Middleware/AuthenticateSignedRequest.php b/app/Http/Middleware/AuthenticateSignedRequest.php index cd23e2d492..9e4e89d031 100644 --- a/app/Http/Middleware/AuthenticateSignedRequest.php +++ b/app/Http/Middleware/AuthenticateSignedRequest.php @@ -25,8 +25,6 @@ */ final readonly class AuthenticateSignedRequest { - private const int FailuresPerAddressPerMinute = 60; - public function __construct(private SignedRequests $signedRequests) { // @@ -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), ])); diff --git a/app/Http/Middleware/ThrottleCommits.php b/app/Http/Middleware/ThrottleCommits.php index ddaed07333..a29723f7fd 100644 --- a/app/Http/Middleware/ThrottleCommits.php +++ b/app/Http/Middleware/ThrottleCommits.php @@ -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; @@ -15,8 +16,6 @@ final readonly class ThrottleCommits { - private const int PER_MINUTE = 10; - /** * One budget of commits a minute, however they are posted. * @@ -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)); } diff --git a/app/Http/Middleware/ThrottleIssues.php b/app/Http/Middleware/ThrottleIssues.php index 49138d87f3..5d4a756010 100644 --- a/app/Http/Middleware/ThrottleIssues.php +++ b/app/Http/Middleware/ThrottleIssues.php @@ -4,6 +4,7 @@ namespace App\Http\Middleware; +use App\Actions\CreateIssue; use App\Enums\ApiErrorCode; use App\Exceptions\ApiException; use App\Models\User; @@ -14,8 +15,6 @@ final readonly class ThrottleIssues { - private const int PER_DAY = 10; - private const int DECAY_SECONDS = 86400; /** @@ -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)); } @@ -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')) { diff --git a/app/Models/Commit.php b/app/Models/Commit.php index 93adc3ffd7..f348486daa 100644 --- a/app/Models/Commit.php +++ b/app/Models/Commit.php @@ -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. */ diff --git a/app/Queries/ApiRateLimitsQuery.php b/app/Queries/ApiRateLimitsQuery.php new file mode 100644 index 0000000000..180ab48a5c --- /dev/null +++ b/app/Queries/ApiRateLimitsQuery.php @@ -0,0 +1,107 @@ + 'minute', 3600 => 'hour', 86400 => 'day']; + + /** + * @return list + */ + 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 + */ + 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; + } +} diff --git a/app/Services/ApiExamples.php b/app/Services/ApiExamples.php new file mode 100644 index 0000000000..3da391ce7b --- /dev/null +++ b/app/Services/ApiExamples.php @@ -0,0 +1,105 @@ + + */ + public function signing(): array + { + return $this->highlight([ + ['label' => 'curl', 'language' => 'bash', 'code' => <<<'SH' + # devnull_sign METHOD PATH [BODY] sets $ts, $nonce and $signature + devnull_sign() { + ts=$(date +%s) + nonce=$(openssl rand -hex 16) + signature=$(printf '%s\n%s\n%s\n%s\n%s' "$ts" "$nonce" "$1" "$2" "${3-}" \ + | ssh-keygen -Y sign -n devnull-api -f ~/.ssh/devnull -q \ + | sed '1d;$d' | tr -d '\n') + } + SH], + ['label' => 'Laravel', 'language' => 'php', 'code' => <<<'PHP' + use Illuminate\Support\Facades\Process; + use Illuminate\Support\Str; + + /** + * The headers that sign a request to the /dev/null API. + * + * @return array + */ + function devnullHeaders(string $method, string $path, string $body = ''): array + { + $timestamp = (string) time(); + $nonce = bin2hex(random_bytes(16)); + $signature = Str::of(Process::input(implode("\n", [$timestamp, $nonce, $method, $path, $body])) + ->run(['ssh-keygen', '-Y', 'sign', '-n', 'devnull-api', '-f', getenv('HOME').'/.ssh/devnull', '-q']) + ->throw() + ->output()) + ->replaceMatches('/-----[A-Z ]+-----|\s/', '') + ->value(); + + return [ + 'X-Devnull-Timestamp' => $timestamp, + 'X-Devnull-Nonce' => $nonce, + 'X-SSH-Signature' => $signature, + ]; + } + PHP], + ['label' => 'fetch', 'language' => 'javascript', 'code' => <<<'JS' + // devnull.mjs, for Node.js, with ssh-keygen on the PATH + import { execFileSync } from 'node:child_process'; + import { randomBytes } from 'node:crypto'; + import { homedir } from 'node:os'; + + // The headers that sign a request to the /dev/null API. + export function devnullHeaders(method, path, body = '') { + const timestamp = String(Math.floor(Date.now() / 1000)); + const nonce = randomBytes(16).toString('hex'); + const signature = execFileSync( + 'ssh-keygen', + ['-Y', 'sign', '-n', 'devnull-api', '-f', `${homedir()}/.ssh/devnull`, '-q'], + { input: [timestamp, nonce, method, path, body].join('\n') }, + ) + .toString() + .replace(/-----[A-Z ]+-----|\s/g, ''); + + return { + 'X-Devnull-Timestamp': timestamp, + 'X-Devnull-Nonce': nonce, + 'X-SSH-Signature': signature, + }; + } + JS], + ]); + } + + /** + * @param list $examples + * @return list + */ + private function highlight(array $examples): array + { + return array_map(fn (array $example): array => [ + ...$example, + 'html' => $this->highlighter->parse($example['code'], $example['language']), + ], $examples); + } +} diff --git a/app/Services/ApiGuideSnippets.php b/app/Services/ApiGuideSnippets.php new file mode 100644 index 0000000000..ec5e58bd5a --- /dev/null +++ b/app/Services/ApiGuideSnippets.php @@ -0,0 +1,84 @@ + + */ + public function for(ApiDocsSection $section): array + { + $snippets = match ($section) { + ApiDocsSection::Introduction => [ + 'firstRequest' => ['bash', 'curl '.ApiExamples::BaseUrl."/users/nunomaduro \\\n -H 'Accept: application/json'"], + ], + ApiDocsSection::Authentication => [ + 'keygen' => ['bash', "ssh-keygen -t ed25519 -f ~/.ssh/devnull -N ''"], + 'message' => ['text', "\n\n\n\n"], + ], + ApiDocsSection::Pagination => [ + 'page' => ['json', $this->page()], + ], + ApiDocsSection::Errors => [ + 'error' => ['json', <<<'JSON' + { + "message": "This commit isn't available.", + "code": "commit_unavailable" + } + JSON], + 'validation' => ['json', <<<'JSON' + { + "message": "The body field is required.", + "errors": { + "body": ["The body field is required."] + } + } + JSON], + ], + default => [], + }; + + return array_map(fn (array $snippet): array => [ + 'language' => $snippet[0], + 'html' => $this->highlighter->parse($snippet[1], $snippet[0]), + ], $snippets); + } + + private function page(): string + { + $url = ApiExamples::BaseUrl; + + return << void>(); + let chosen: string | null | undefined; + + const stored = (): string | null => { + try { + return window.localStorage.getItem(key); + } catch { + return null; + } + }; + + const current = (): string | null => { + if (chosen === undefined) { + chosen = stored(); + } + + return chosen; + }; + + const choose = (value: string): void => { + chosen = value; + + try { + window.localStorage.setItem(key, value); + } catch { + // A private window may refuse it: the choice then lasts as long as the page. + } + + listeners.forEach((listener) => listener()); + }; + + const subscribe = (listener: () => void): (() => void) => { + const onStorage = (event: StorageEvent) => { + // A null key means another tab cleared the whole storage. + if (event.key === key || event.key === null) { + chosen = event.key === null ? null : event.newValue; + listener(); + } + }; + + listeners.add(listener); + window.addEventListener('storage', onStorage); + + return () => { + listeners.delete(listener); + window.removeEventListener('storage', onStorage); + }; + }; + + const useChosen = (): string | null => + useSyncExternalStore(subscribe, current, () => null); + + return { choose, useChosen }; +} diff --git a/resources/js/components/api-docs/example-choice.ts b/resources/js/components/api-docs/example-choice.ts new file mode 100644 index 0000000000..579b7da0b5 --- /dev/null +++ b/resources/js/components/api-docs/example-choice.ts @@ -0,0 +1,20 @@ +import { createChoice } from '@/components/api-docs/choice'; + +const example = createChoice('api-docs:example'); + +export const chooseExample = example.choose; + +/** + * The client the reader picked last, such as Laravel: someone who picks it uses it, so every endpoint shows it. + */ +export const useChosenExample = example.useChosen; + +/** + * The tab to show: the one picked last when this endpoint has it, else the first. + */ +export function activeExample( + labels: string[], + chosenLabel: string | null, +): number { + return Math.max(0, chosenLabel === null ? 0 : labels.indexOf(chosenLabel)); +} diff --git a/resources/js/components/api-docs/example-tabs.tsx b/resources/js/components/api-docs/example-tabs.tsx new file mode 100644 index 0000000000..481fd3a4bf --- /dev/null +++ b/resources/js/components/api-docs/example-tabs.tsx @@ -0,0 +1,166 @@ +import { useId } from 'react'; +import type { CSSProperties, KeyboardEvent } from 'react'; +import { flushSync } from 'react-dom'; +import { + activeExample, + chooseExample, + useChosenExample, +} from '@/components/api-docs/example-choice'; +import { CodeBlock } from '@/components/code-block'; +import { cn, withViewTransition } from '@/lib/utils'; +import type { ApiDocsExample } from '@/types'; + +/** + * The tab a key moves to, as a tab list's keys do: the arrows round the ends, Home and End to the ends. + */ +export function tabKeyTarget( + key: string, + active: number, + count: number, +): number | null { + switch (key) { + case 'ArrowRight': + return (active + 1) % count; + case 'ArrowLeft': + return (active - 1 + count) % count; + case 'Home': + return 0; + case 'End': + return count - 1; + default: + return null; + } +} + +/** + * Moves to the tab a key points at: picks it first, at once rather than after an animated transition, so the tab focus + * lands on is already the selected one and a next key counts from it. Says whether the key moved anything. + */ +export function moveToExample( + key: string, + active: number, + labels: string[], + pick: (label: string) => void, + focus: (index: number) => void, +): boolean { + const next = tabKeyTarget(key, active, labels.length); + const label = next === null ? undefined : labels[next]; + + if (next === null || label === undefined) { + return false; + } + + pick(label); + focus(next); + + return true; +} + +/** + * Code for each client, one tab per client, the active one underlined in Commit Blue like the page tabs. Picking a + * client picks it everywhere, and next time too. + */ +export function ExampleTabs({ examples }: { examples: ApiDocsExample[] }) { + const id = useId(); + // Each tab list on the page slides its own underline, so each needs a name of its own, as a CSS ident. + const indicatorName = `example-tab-${id.replace(/[^\w-]/g, '')}`; + const active = activeExample( + examples.map((example) => example.label), + useChosenExample(), + ); + const setActive = (index: number) => { + const label = examples[index]?.label; + + if (label !== undefined && index !== active) { + void withViewTransition(() => chooseExample(label)); + } + }; + + const onKeyDown = (event: KeyboardEvent) => { + const moved = moveToExample( + event.key, + active, + examples.map((example) => example.label), + (label) => flushSync(() => chooseExample(label)), + (index) => document.getElementById(`${id}-tab-${index}`)?.focus(), + ); + + if (moved) { + event.preventDefault(); + } + }; + + if (examples.length === 0) { + return null; + } + + return ( +
+
+ {examples.map((candidate, index) => ( + + ))} +
+ {/* Where the page renders on the server, every example sits in the same cell, so the tallest sets the + height and the server's first tab giving way to the reader's own client moves nothing. */} +
+ {examples.map((candidate, index) => { + const isActive = index === active; + + return ( +
+ +
+ ); + })} +
+
+ ); +} diff --git a/resources/js/components/api-docs/guide.tsx b/resources/js/components/api-docs/guide.tsx new file mode 100644 index 0000000000..2b410b748b --- /dev/null +++ b/resources/js/components/api-docs/guide.tsx @@ -0,0 +1,128 @@ +import type { ReactNode } from 'react'; +import { CodeBlock } from '@/components/code-block'; +import { cn } from '@/lib/utils'; +import type { ApiDocsSnippet } from '@/types'; + +/** + * How wide the docs' content is, so moving between their pages never changes the page's width. + */ +export const DOCS_WIDTH = 'max-w-[1160px]'; + +/** + * A guide of the API docs, read like the site's other long pages: one Feed White sheet on the console's shell, its + * sections one after the other with a hairline between them, never a card each. + */ +export function Guide({ children }: { children: ReactNode }) { + return ( +
+ {children} +
+ ); +} + +function anchor(title: string): string { + return title + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); +} + +/** + * A section of a guide, its title a link to itself, so a reader can point someone at it. + */ +export function GuideSection({ + title, + meta, + children, +}: { + title: string; + meta?: ReactNode; + children: ReactNode; +}) { + const id = anchor(title); + + return ( +
+
+

+ + {title} + +

+ {meta && ( + + {meta} + + )} +
+ {children} +
+ ); +} + +/** + * A guide's code, in the code block the rest of the site uses, highlighted by the server. + */ +export function Snippet({ snippet }: { snippet: ApiDocsSnippet | undefined }) { + if (snippet === undefined) { + return null; + } + + return ( + + ); +} + +export function Code({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +/** + * Named values in a hairline list, keys in mono, as the settings list what they show. + */ +export function FieldList({ + fields, + keyWidth = 'sm:grid-cols-[9rem_minmax(0,1fr)]', +}: { + fields: { name: string; children: ReactNode }[]; + keyWidth?: string; +}) { + return ( +
+ {fields.map((field) => ( +
+
+ {field.name} +
+
{field.children}
+
+ ))} +
+ ); +} diff --git a/resources/js/components/app-aside.tsx b/resources/js/components/app-aside.tsx index ac5f1184d5..48ffac7e0a 100644 --- a/resources/js/components/app-aside.tsx +++ b/resources/js/components/app-aside.tsx @@ -1,6 +1,7 @@ import { Link, usePage } from '@inertiajs/react'; import { Search } from 'lucide-react'; import AboutController from '@/actions/App/Http/Controllers/AboutController'; +import ApiDocsController from '@/actions/App/Http/Controllers/ApiDocsController'; import AppController from '@/actions/App/Http/Controllers/AppController'; import ChangelogController from '@/actions/App/Http/Controllers/ChangelogController'; import PartnerController from '@/actions/App/Http/Controllers/PartnerController'; @@ -114,6 +115,13 @@ export function AppAside({ > Apps + + API + + + + + API + + = { + introduction: BookOpen, + authentication: KeyRound, + 'rate-limits': Gauge, + pagination: ListOrdered, + errors: CircleAlert, +}; + +function navItems(sections: ApiDocsSection[]) { + return sections.map((section) => ({ + key: section.slug, + title: section.title, + description: section.description, + href: ApiDocsController.show(section.slug), + icon: ICONS[section.slug] ?? BookOpen, + })); +} + +/** + * The API docs as a console beside the log, its guides in the sidebar. + */ +export default function ApiDocsLayout({ children }: PropsWithChildren) { + const { props } = usePage(); + + const groups: ConsoleNavGroup[] = [ + { + label: 'Guide', + items: navItems(props.sections), + }, + ]; + + return ( + + v1 + + } + > + {children} + + ); +} diff --git a/resources/js/layouts/console/layout.tsx b/resources/js/layouts/console/layout.tsx new file mode 100644 index 0000000000..1e829b9ca0 --- /dev/null +++ b/resources/js/layouts/console/layout.tsx @@ -0,0 +1,284 @@ +import { Link } from '@inertiajs/react'; +import type { InertiaLinkProps } from '@inertiajs/react'; +import type { LucideIcon } from 'lucide-react'; +import { ArrowUpRight } from 'lucide-react'; +import { useEffect, useRef } from 'react'; +import type { ReactNode } from 'react'; +import AppLogoIcon from '@/components/app-logo-icon'; +import AppWordmark from '@/components/app-wordmark'; +import AppearanceToggleTab from '@/components/appearance-tabs'; +import { UserAvatar } from '@/components/user-avatar'; +import { cn } from '@/lib/utils'; +import type { User } from '@/types'; + +export type ConsoleNavItem = { + key: string; + title: string; + description: string; + href: NonNullable; + icon: LucideIcon; + external?: boolean; +}; + +export type ConsoleNavGroup = { + label: string; + items: ConsoleNavItem[]; +}; + +const itemClassName = + 'flex h-9 shrink-0 items-center gap-2.5 rounded-lg px-2.5 text-sm font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground'; + +function NavItem({ + item, + isActive, + prefetch, +}: { + item: ConsoleNavItem; + isActive: boolean; + prefetch: boolean; +}) { + if (item.external) { + return ( + + + {item.title} + + + ); + } + + return ( + + + {item.title} + + ); +} + +function Brand({ + chip, + label, + href, + prefetch, +}: { + chip: string; + label: string; + href: NonNullable; + prefetch: boolean; +}) { + return ( + + + + + {chip} + + + ); +} + +/** + * The shell of a standalone console beside the log, such as Operations: a sidebar of grouped pages, a header naming + * the current one, and a way back to /dev/null. Its pages prefetch on hover only when the console asks for it. + */ +export default function ConsoleLayout({ + chip, + label, + navLabel, + brandHref, + prefetch = false, + groups, + current, + backHref, + user, + headerActions, + children, +}: { + chip: string; + label: string; + navLabel: string; + brandHref: NonNullable; + prefetch?: boolean; + groups: ConsoleNavGroup[]; + current: string; + backHref: string; + user: User | null; + headerActions?: ReactNode; + children: ReactNode; +}) { + const items = groups.flatMap((group) => group.items); + const page = items.find((item) => item.key === current && !item.external); + const mobileNav = useRef(null); + + useEffect(() => { + mobileNav.current + ?.querySelector('[aria-current="page"]') + ?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + }, [current]); + + return ( +
+ + +
+
+
+
+ +
+
+

+ {page?.title ?? navLabel} +

+

+ {page?.description} +

+
+ +
+ {headerActions} + + {user ? ( + + ) : ( + + )} + +
+
+ + +
+ +
+
+

+ {page?.title ?? navLabel} +

+

+ {page?.description} +

+
+ {children} +
+
+
+ ); +} diff --git a/resources/js/layouts/operations/layout.tsx b/resources/js/layouts/operations/layout.tsx index e8c7c913e3..22548ec0ec 100644 --- a/resources/js/layouts/operations/layout.tsx +++ b/resources/js/layouts/operations/layout.tsx @@ -1,9 +1,6 @@ -import { Link, router, usePage, usePoll } from '@inertiajs/react'; -import type { InertiaLinkProps } from '@inertiajs/react'; -import type { LucideIcon } from 'lucide-react'; +import { router, usePage, usePoll } from '@inertiajs/react'; import { Activity, - ArrowUpRight, ChartNoAxesCombined, Flag, Gauge, @@ -18,7 +15,7 @@ import { ShieldCheck, TrendingUp, } from 'lucide-react'; -import { useEffect, useRef, useState } from 'react'; +import { useState } from 'react'; import type { PropsWithChildren } from 'react'; import EmailController from '@/actions/App/Http/Controllers/EmailController'; import FeatureController from '@/actions/App/Http/Controllers/FeatureController'; @@ -31,13 +28,11 @@ import ProductMetricsController from '@/actions/App/Http/Controllers/ProductMetr import SiteActivityController from '@/actions/App/Http/Controllers/SiteActivityController'; import SystemHealthController from '@/actions/App/Http/Controllers/SystemHealthController'; import TrafficController from '@/actions/App/Http/Controllers/TrafficController'; -import AppLogoIcon from '@/components/app-logo-icon'; -import AppWordmark from '@/components/app-wordmark'; -import AppearanceToggleTab from '@/components/appearance-tabs'; import { ChatDock } from '@/components/chat/chat-dock'; import { Button } from '@/components/ui/button'; -import { UserAvatar } from '@/components/user-avatar'; import { useRemoteAlerts, useRemoteUpdates } from '@/hooks/use-chat'; +import ConsoleLayout from '@/layouts/console/layout'; +import type { ConsoleNavGroup } from '@/layouts/console/layout'; import { backgroundPollOptions } from '@/lib/background-poll'; import { cn } from '@/lib/utils'; import { home } from '@/routes'; @@ -104,35 +99,27 @@ const POLL_PROPS = Object.fromEntries( ]), ) as Record; -type NavEntry = { - page: OperationsPage; - title: string; - description: string; - href: NonNullable; - icon: LucideIcon; -}; - -function navGroups(): { label: string; items: NavEntry[] }[] { +function navGroups(): ConsoleNavGroup[] { return [ { label: 'Monitor', items: [ { - page: 'operations/show', + key: 'operations/show', title: 'Overview', description: 'What needs attention, and what is fine', href: OperationsController.show(), icon: LayoutDashboard, }, { - page: 'operations/health', + key: 'operations/health', title: 'Health', description: 'Services, queues, failed jobs and backlogs', href: SystemHealthController.show(), icon: HeartPulse, }, { - page: 'operations/events', + key: 'operations/events', title: 'Events', description: 'Everything that happened, newest first', href: OperationsEventController.index(), @@ -144,28 +131,28 @@ function navGroups(): { label: string; items: NavEntry[] }[] { label: 'Product', items: [ { - page: 'operations/forecasts', + key: 'operations/forecasts', title: 'Forecasts', description: 'Where the trends are heading next', href: ForecastController.show(), icon: TrendingUp, }, { - page: 'operations/metrics', + key: 'operations/metrics', title: 'Growth', description: 'Acquisition, activation and retention', href: ProductMetricsController.show(), icon: ChartNoAxesCombined, }, { - page: 'operations/activity', + key: 'operations/activity', title: 'Activity', description: 'Commits, replies and signups over time', href: SiteActivityController.show(), icon: Activity, }, { - page: 'operations/traffic', + key: 'operations/traffic', title: 'Traffic', description: 'Visitors and where they come from', href: TrafficController.show(), @@ -177,14 +164,14 @@ function navGroups(): { label: string; items: NavEntry[] }[] { label: 'Control', items: [ { - page: 'operations/features', + key: 'operations/features', title: 'Features', description: 'Choose who can use each feature', href: FeatureController.index(), icon: Flag, }, { - page: 'operations/emails', + key: 'operations/emails', title: 'Emails', description: 'Write to everyone, or the people you pick', href: EmailController.create(), @@ -192,6 +179,19 @@ function navGroups(): { label: string; items: NavEntry[] }[] { }, ], }, + { + label: 'Elsewhere', + items: [ + { + key: 'moderation', + title: 'Moderation', + description: 'Commits waiting for review', + href: ModerationController.show().url, + icon: ShieldCheck, + external: true, + }, + ], + }, ]; } @@ -201,41 +201,6 @@ function Poll({ only }: { only: string[] }) { return null; } -function NavItem({ item, isActive }: { item: NavEntry; isActive: boolean }) { - return ( - - - {item.title} - - ); -} - -function Brand() { - return ( - - - - - ops - - - ); -} - export default function OperationsLayout({ children }: PropsWithChildren) { const { component, props } = usePage(); const page = component as OperationsPage; @@ -243,26 +208,16 @@ export default function OperationsLayout({ children }: PropsWithChildren) { const [isLive, setIsLive] = useState(true); const only = PAGE_PROPS[page] ?? []; const polls = !ON_DEMAND.includes(page); - const groups = navGroups(); - const items = groups.flatMap((group) => group.items); - const current = items.find((item) => item.page === page); const user = props.auth.user; const hasRemotes = user !== null && props.auth.remotes !== null; const backHref = props.auth.log === null ? home().url : LogController.show(props.auth.log).url; - const mobileNav = useRef(null); useRemoteAlerts(hasRemotes ? user.id : null); useRemoteUpdates(hasRemotes ? user.id : null); - useEffect(() => { - mobileNav.current - ?.querySelector('[aria-current="page"]') - ?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); - }, [page]); - const refresh = () => { if (isRefreshing) { return; @@ -285,226 +240,84 @@ export default function OperationsLayout({ children }: PropsWithChildren) { }; return ( -
+ <> {polls && isLive && ( )} - - -
-
-
-
- -
-
-

- {current?.title ?? 'Operations'} -

-

- {current?.description} -

-
- -
- {polls ? ( - - ) : ( - - - on demand - - )} + + {polls ? ( - {user && ( - - - - )} -
-
- - -
- -
-
-

- {current?.title ?? 'Operations'} -

-

- {current?.description} -

-
- {children} -
-
+ + + + } + > + {children} + {hasRemotes && } -
+ ); } diff --git a/resources/js/pages/api-docs/guides/authentication.tsx b/resources/js/pages/api-docs/guides/authentication.tsx new file mode 100644 index 0000000000..32806cde56 --- /dev/null +++ b/resources/js/pages/api-docs/guides/authentication.tsx @@ -0,0 +1,185 @@ +import { ExampleTabs } from '@/components/api-docs/example-tabs'; +import { + Code, + FieldList, + Guide, + GuideSection, + Snippet, +} from '@/components/api-docs/guide'; +import type { ApiDocsExample, ApiDocsSnippet } from '@/types'; + +export function Authentication({ + signing, + snippets, +}: { + signing: ApiDocsExample[]; + snippets: Record; +}) { + return ( + + + +

Each endpoint of the reference says which it is.

+
+ + +

+ Your app keeps its own SSH key, made for it. It doesn't need + to be on anyone's GitHub account, and a key that is only on + GitHub can't sign API requests. +

+ +

+ Then open https://dev-null.sh/mobile/authorize{' '} + in a browser, the way an OAuth app would, with PKCE: +

+ + The key's, as ssh-keygen -lf{' '} + prints it: SHA256:… + + ), + }, + { + name: 'device_name', + children: + 'Where the key lives, shown on the approval page', + }, + { + name: 'app_name', + children: + 'Optional. Your app, so people can tell apps apart in their devices', + }, + { + name: 'app_id', + children: ( + <> + Optional. A stable platform and identifier, + like macos:sh.dev-null.mac + + ), + }, + { + name: 'code_challenge', + children: ( + <> + The SHA-256 of your verifier, base64url + without padding, 43 characters, with{' '} + code_challenge_method=S256 + + ), + }, + { + name: 'state', + children: 'Anything, sent back as it is', + }, + { + name: 'redirect_uri', + children: ( + <> + Where the code goes:{' '} + http://127.0.0.1:<port>{' '} + your app listens on. devnull://{' '} + is the /dev/null apps' own. + + ), + }, + ]} + /> +

+ The person signs in with GitHub if they need to, checks the + fingerprint and approves. The browser then goes to your{' '} + redirect_uri with a code and your{' '} + state, or with error=access_denied + . Redeem the code with POST /devices, signed + with the new key, its body{' '} + {'{"code": "…", "code_verifier": "…"}'}. The + key is now one of their devices, until they revoke it in + Settings → Devices. +

+

+ Only signing in uses POST /devices, so the + reference leaves it out with the other endpoints only the + apps need to work. +

+
+ + +

+ Every request signs these five lines with the key, as an SSH + signature in the devnull-api namespace: +

+ + +

+ The path and query are exactly the ones you request, from + the root: /api/v1/search/commits?q=laravel. The + body is exactly the bytes you send, as JSON with{' '} + Content-Type: application/json, or nothing when + there is none. +

+

+ Every signed example of the reference calls one of these, + with its method, path and body: +

+ +

+ A request with images or a voice note is multipart, with + nothing else in it: the JSON as a payload file + part of type application/json (with curl,{' '} + -F 'payload=@body.json;type=application/json' + ), and either the images in images[] or the + voice note in voice, never both. The signed + message then has one more line before the body, the SHA-256 + of each file, in hex, comma separated in the order they are + attached, and the namespace is{' '} + devnull-api-images. +

+
+ + +

+ Someone has to accept the commit rules once, in the web + composer, before an app can commit for them. Until then, + commits answer commit_rules_required. +

+
+
+ ); +} diff --git a/resources/js/pages/api-docs/guides/errors.tsx b/resources/js/pages/api-docs/guides/errors.tsx new file mode 100644 index 0000000000..c6b3d6fff3 --- /dev/null +++ b/resources/js/pages/api-docs/guides/errors.tsx @@ -0,0 +1,83 @@ +import { + Code, + Guide, + GuideSection, + Snippet, +} from '@/components/api-docs/guide'; +import type { ApiDocsSnippet, ApiErrorCodeStatus } from '@/types'; + +export function Errors({ + codes, + snippets, +}: { + codes: ApiErrorCodeStatus[]; + snippets: Record; +}) { + return ( + + +

+ Every error says what happened in message, in + the web's own words. An error the API answers itself, listed + below, also says which one it is in code. A + code never changes once released: match on it, and show the + message. +

+

+ Laravel's own errors have no code: a{' '} + 404 for something that doesn't exist or isn't + yours to see, a 403 for an action you can't + take, and validation errors, which also say what is wrong + with each field in errors, below. +

+ +
+ + +
+ + + + + + + + + + {codes.map(({ code, status, meaning }) => ( + + + + + + ))} + +
+ status + code + meaning +
+ {status} + + + {code} + +

+ {meaning} +

+
+ {meaning} +
+
+
+ + +

+ A request that doesn't pass validation is a 422 + , with what is wrong with each field, as Laravel answers it: +

+ +
+
+ ); +} diff --git a/resources/js/pages/api-docs/guides/introduction.tsx b/resources/js/pages/api-docs/guides/introduction.tsx new file mode 100644 index 0000000000..dede918d96 --- /dev/null +++ b/resources/js/pages/api-docs/guides/introduction.tsx @@ -0,0 +1,83 @@ +import { Link } from '@inertiajs/react'; +import ApiDocsController from '@/actions/App/Http/Controllers/ApiDocsController'; +import { + Code, + FieldList, + Guide, + GuideSection, + Snippet, +} from '@/components/api-docs/guide'; +import type { ApiDocsSnippet } from '@/types'; + +const API_URL = 'https://dev-null.sh/api/v1'; + +export function Introduction({ + snippets, +}: { + snippets: Record; +}) { + return ( + + +

+ The JSON API the /dev/null apps use, open to anything you + build: a bot, a bridge, a widget on your own site. +

+

+ Reading public profiles and commits needs nothing. Acting + for someone needs their approval and a signature on every + request: there are no passwords and no API tokens. +

+ {API_URL} }, + { + name: 'format', + children: + 'JSON, or multipart when a request carries images or a voice note', + }, + { + name: 'accept', + children: ( + <> + Accept: application/json on + every request, so every error comes back as + JSON + + ), + }, + ]} + /> +
+ + +

A profile, as anyone can read it:

+ +

+ Lists come a page at a time: see{' '} + + Pagination + + . To read what someone sees, or to commit for them, sign the + request: see{' '} + + Authentication + + . +

+
+ + +

+ A signed request sees what the web shows the person who + signed it, and goes through the same validation, moderation + and limits: a commit may come back pending, and a blocked + profile stays out of reach. +

+
+
+ ); +} diff --git a/resources/js/pages/api-docs/guides/pagination.tsx b/resources/js/pages/api-docs/guides/pagination.tsx new file mode 100644 index 0000000000..8f1411982b --- /dev/null +++ b/resources/js/pages/api-docs/guides/pagination.tsx @@ -0,0 +1,58 @@ +import { + Code, + Guide, + GuideSection, + Snippet, +} from '@/components/api-docs/guide'; +import type { ApiDocsSnippet } from '@/types'; + +export function Pagination({ + snippets, +}: { + snippets: Record; +}) { + return ( + + +

+ Lists are cursor-paginated, newest first, 20 a page. A + cursor marks where the page ended, so commits arriving + meanwhile never push the next page back. +

+ +

+ Follow links.next until it is null + , or pass meta.next_cursor as{' '} + cursor yourself. Keep the other parameters of + the first request: the links already do. +

+
+ + +
    +
  • + Followers, following and followed organizations come 30 + a page. +
  • +
  • + A commit's replies come 50 a page, oldest first, or + newest first with newest=1. +
  • +
  • + A log ranked by something else than time keeps its + rank's order. Asked to reach back to a commit you + already have, a log or the notifications send every one + since, so a page can hold more than 20. +
  • +
  • + Scheduled commits come by page number, 20 a page, drafts + not yet submitted first, then the soonest:{' '} + links.next works the same, and{' '} + meta also has current_page,{' '} + last_page and total. +
  • +
+
+
+ ); +} diff --git a/resources/js/pages/api-docs/guides/rate-limits.tsx b/resources/js/pages/api-docs/guides/rate-limits.tsx new file mode 100644 index 0000000000..d6cbef0157 --- /dev/null +++ b/resources/js/pages/api-docs/guides/rate-limits.tsx @@ -0,0 +1,60 @@ +import { Code, Guide, GuideSection } from '@/components/api-docs/guide'; +import type { ApiRateLimit } from '@/types'; + +export function RateLimits({ limits }: { limits: ApiRateLimit[] }) { + return ( + + +

+ Every request counts toward one of the first two: unsigned + requests by address, signed ones by the person who signed. + Some actions have a budget of their own on top, the same as + on the web. +

+
+ + + + + + + + + + {limits.map((row) => ( + + + + + + ))} + +
what + limit + per
{row.what} + {row.limit} + + {row.per} +
+
+
+ + +

+ Every answer says where you are in the first two in{' '} + X-RateLimit-Limit and{' '} + X-RateLimit-Remaining; an action's own budget + isn't in them. Past any limit, the answer is a{' '} + 429 with Retry-After, the seconds + to wait, and a message. +

+

+ A signed request also gets the code{' '} + rate_limited, except past the pings and commit + searches budgets, which only say it in their message. An + unsigned request never gets a code. +

+
+
+ ); +} diff --git a/resources/js/pages/api-docs/show.tsx b/resources/js/pages/api-docs/show.tsx new file mode 100644 index 0000000000..c0ada6a59a --- /dev/null +++ b/resources/js/pages/api-docs/show.tsx @@ -0,0 +1,32 @@ +import { Head, usePage } from '@inertiajs/react'; +import ApiDocsLayout from '@/layouts/api-docs/layout'; +import { Authentication } from '@/pages/api-docs/guides/authentication'; +import { Errors } from '@/pages/api-docs/guides/errors'; +import { Introduction } from '@/pages/api-docs/guides/introduction'; +import { Pagination } from '@/pages/api-docs/guides/pagination'; +import { RateLimits } from '@/pages/api-docs/guides/rate-limits'; +import type { ApiDocsProps } from '@/types'; + +export default function Show() { + const { sections, current, errorCodes, rateLimits, signing, snippets } = + usePage().props; + const section = sections.find((candidate) => candidate.slug === current); + + return ( + <> + + + {current === 'introduction' && } + {current === 'authentication' && ( + + )} + {current === 'rate-limits' && } + {current === 'pagination' && } + {current === 'errors' && ( + + )} + + ); +} + +Show.layout = ApiDocsLayout; diff --git a/resources/js/types/api-docs.ts b/resources/js/types/api-docs.ts new file mode 100644 index 0000000000..fe88a43be2 --- /dev/null +++ b/resources/js/types/api-docs.ts @@ -0,0 +1,38 @@ +export type ApiDocsSection = { + slug: string; + title: string; + description: string; +}; + +export type ApiErrorCodeStatus = { + code: string; + status: number; + meaning: string; +}; + +export type ApiDocsSnippet = { + language: string; + html: string; +}; + +export type ApiRateLimit = { + what: string; + limit: number; + per: string; +}; + +export type ApiDocsExample = { + label: string; + language: string; + code: string; + html: string; +}; + +export type ApiDocsProps = { + sections: ApiDocsSection[]; + current: string; + signing: ApiDocsExample[]; + rateLimits: ApiRateLimit[]; + snippets: Record; + errorCodes: ApiErrorCodeStatus[]; +}; diff --git a/resources/js/types/index.ts b/resources/js/types/index.ts index f7facc21a5..e585011f25 100644 --- a/resources/js/types/index.ts +++ b/resources/js/types/index.ts @@ -1,4 +1,5 @@ export type * from './achievement'; +export type * from './api-docs'; export type * from './activity'; export type * from './auth'; export type * from './commit'; diff --git a/routes/web.php b/routes/web.php index c10b9580d9..618ff52962 100644 --- a/routes/web.php +++ b/routes/web.php @@ -2,9 +2,11 @@ declare(strict_types=1); +use App\Enums\ApiDocsSection; use App\Enums\Log; use App\Enums\ProfileType; use App\Http\Controllers\AboutController; +use App\Http\Controllers\ApiDocsController; use App\Http\Controllers\AppController; use App\Http\Controllers\BanController; use App\Http\Controllers\BannedController; @@ -251,6 +253,10 @@ // What was merged into production, readable by everyone... Route::get('changelog', [ChangelogController::class, 'index'])->name('changelog.index'); +// The API docs, readable by everyone... +Route::redirect('docs/api', '/docs/api/'.ApiDocsSection::Introduction->value)->name('api-docs.index'); +Route::get('docs/api/{section}', [ApiDocsController::class, 'show'])->name('api-docs.show'); + // Public pages, readable by guests and crawlers... Route::middleware([RememberIntendedUrl::class, RedirectToHandleCase::class])->group(function (): void { // A handle no user has may be an organization's, an unclaimed developer's, or one to look up on GitHub. Bindings diff --git a/tests/Feature/ApiSigningGuideTest.php b/tests/Feature/ApiSigningGuideTest.php new file mode 100644 index 0000000000..6f33c4d514 --- /dev/null +++ b/tests/Feature/ApiSigningGuideTest.php @@ -0,0 +1,87 @@ +throw(); + + Device::factory()->for($user)->withPublicKey(SshPublicKey::fromOpenSsh(File::get("{$home}/.ssh/devnull.pub")))->create(); + + return $home; +} + +/** + * The headers one of the guide's signing helpers makes, run as the guide shows it, with that home. + * + * @return array + */ +function signingGuideHeaders(string $client, string $home, string $method, string $path, string $body): array +{ + $helpers = array_column(resolve(ApiExamples::class)->signing(), 'code', 'label'); + + if ($client === 'Laravel') { + if (! function_exists('SigningGuide\devnullHeaders')) { + eval("namespace SigningGuide;\n".$helpers['Laravel']); + } + + $previous = getenv('HOME'); + putenv("HOME={$home}"); + $headers = devnullHeaders($method, $path, $body); + putenv("HOME={$previous}"); + + return $headers; + } + + if ($client === 'curl') { + $script = $helpers['curl']."\ndevnull_sign \"\$1\" \"\$2\" \"\$3\"\nprintf '%s\\n%s\\n%s' \"\$ts\" \"\$nonce\" \"\$signature\""; + [$timestamp, $nonce, $signature] = explode("\n", Process::env(['HOME' => $home])->run(['bash', '-c', $script, 'sign', $method, $path, $body])->throw()->output()); + + return ['X-Devnull-Timestamp' => $timestamp, 'X-Devnull-Nonce' => $nonce, 'X-SSH-Signature' => $signature]; + } + + File::put("{$home}/devnull.mjs", $helpers['fetch']); + $script = "import { devnullHeaders } from '{$home}/devnull.mjs'; const [method, path, body] = process.argv.slice(1); process.stdout.write(JSON.stringify(devnullHeaders(method, path, body)));"; + + return json_decode(Process::env(['HOME' => $home])->run(['node', '--input-type=module', '-e', $script, $method, $path, $body])->throw()->output(), true, flags: JSON_THROW_ON_ERROR); +} + +it("signs requests the API accepts with each client's helper from the guide", function (string $client): void { + $user = User::factory()->create(); + $followed = User::factory()->create(); + $home = signingGuideHome($user); + + $requests = [ + ['GET', '/api/v1/me', ''], + ['POST', "/api/v1/users/{$followed->handle}/follow", ''], + ['POST', '/api/v1/commits/preview', (string) json_encode(['body' => 'Hello from the API!'])], + ]; + + foreach ($requests as [$method, $path, $body]) { + $headers = signingGuideHeaders($client, $home, $method, $path, $body); + $server = ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json']; + + foreach ($headers as $name => $value) { + $server['HTTP_'.Str::upper(Str::replace('-', '_', $name))] = $value; + } + + $this->call($method, $path, server: $server, content: $body)->assertSuccessful(); + } + + File::deleteDirectory($home); +})->with(['curl', 'Laravel', 'fetch']); diff --git a/tests/Feature/Controllers/ApiDocsControllerTest.php b/tests/Feature/Controllers/ApiDocsControllerTest.php new file mode 100644 index 0000000000..5ac1ef7880 --- /dev/null +++ b/tests/Feature/Controllers/ApiDocsControllerTest.php @@ -0,0 +1,105 @@ +get('/docs/api')->assertRedirect(route('api-docs.show', ApiDocsSection::Introduction)); +}); + +it('renders every section of the API docs for guests', function (ApiDocsSection $section): void { + $this->get(route('api-docs.show', $section)) + ->assertOk() + ->assertInertia(fn ($page) => $page->component('api-docs/show') + ->where('current', $section->value)); +})->with(ApiDocsSection::cases()); + +it('renders the API docs for signed in users', function (): void { + $this->actingAs(User::factory()->create()) + ->get(route('api-docs.show', ApiDocsSection::Authentication)) + ->assertOk() + ->assertInertia(fn ($page) => $page->component('api-docs/show')); +}); + +it('lists the guides in reading order', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertInertia(fn ($page) => $page + ->has('sections', 5) + ->where('sections.0', [ + 'slug' => 'introduction', + 'title' => 'Introduction', + 'description' => 'What the API is for, and where it lives', + ]) + ->where('sections', fn ($sections): bool => collect($sections)->pluck('slug')->all() === [ + 'introduction', 'authentication', 'rate-limits', 'pagination', 'errors', + ])); +}); + +it('gives a guide its code blocks, and none to a guide without', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Errors)) + ->assertInertia(fn ($page) => $page + ->has('snippets', 2) + ->has('snippets.error', fn ($snippet) => $snippet->where('language', 'json')->has('html'))); + + $this->get(route('api-docs.show', ApiDocsSection::RateLimits)) + ->assertInertia(fn ($page) => $page->where('snippets', [])); +}); + +it('lists the rate limits as the code sets them, in Rate limits only', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::RateLimits)) + ->assertInertia(fn ($page) => $page + ->has('rateLimits', count(resolve(ApiRateLimitsQuery::class)->get())) + ->where('rateLimits.1', ['what' => 'Signed requests', 'limit' => 120, 'per' => 'minute, per person'])); + + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertInertia(fn ($page) => $page->where('rateLimits', [])); +}); + +it('shows how each client signs a request in Authentication only', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Authentication)) + ->assertInertia(fn ($page) => $page + ->has('signing', 3) + ->where('signing.1.label', 'Laravel')); + + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertInertia(fn ($page) => $page->where('signing', [])); +}); + +it('lists every error code with the status it comes with', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::Errors)) + ->assertInertia(fn ($page) => $page + ->has('errorCodes', count(ApiErrorCode::cases())) + ->where('errorCodes.0', ['code' => 'invalid_signature', 'status' => 401, 'meaning' => ApiErrorCode::InvalidSignature->meaning()]) + ->where('errorCodes.2.code', 'invalid_grant') + ->where('errorCodes.2.status', 400)); + + $this->get(route('api-docs.show', ApiDocsSection::Introduction)) + ->assertInertia(fn ($page) => $page->where('errorCodes', [])); +}); + +it('says what every error code means, and where it can come from', function (ApiErrorCode $code): void { + expect($code->meaning())->not->toBeEmpty(); +})->with(ApiErrorCode::cases()); + +it('says which errors only come from one place', function (): void { + expect(ApiErrorCode::OwnCommit->meaning())->toBe('You cannot report your own commit.') + ->and(ApiErrorCode::CommitUnavailable->meaning())->toContain('report') + ->and(ApiErrorCode::InvalidGrant->meaning())->toContain('another key'); +}); + +it('answers a section the docs do not have with the not found page', function (): void { + $this->get('/docs/api/webhooks') + ->assertNotFound() + ->assertHeader('Content-Type', 'text/html; charset=UTF-8'); +}); + +it('describes each section to search engines and link previews', function (): void { + $this->get(route('api-docs.show', ApiDocsSection::RateLimits)) + ->assertOk() + ->assertSee('Rate limits - API docs - /dev/null', false) + ->assertSee('', false); +}); diff --git a/tests/Feature/Queries/ApiRateLimitsQueryTest.php b/tests/Feature/Queries/ApiRateLimitsQueryTest.php new file mode 100644 index 0000000000..ca829c3d64 --- /dev/null +++ b/tests/Feature/Queries/ApiRateLimitsQueryTest.php @@ -0,0 +1,31 @@ +get())->toBe([ + ['what' => 'Unsigned requests', 'limit' => 60, 'per' => 'minute, per IP'], + ['what' => 'Signed requests', 'limit' => 120, 'per' => 'minute, per person'], + ['what' => 'Signatures that fail to check out', 'limit' => 60, 'per' => 'minute, per IP'], + ['what' => 'Commits, replies and quotes, now or scheduled', 'limit' => 10, 'per' => 'minute, shared with the web and the terminal'], + ['what' => 'Commit searches', 'limit' => 15, 'per' => 'minute'], + ['what' => 'People searches, mention suggestions and profile cards', 'limit' => 120, 'per' => 'minute'], + ['what' => 'Issue suggestions', 'limit' => 30, 'per' => 'minute'], + ['what' => 'Issue suggestions', 'limit' => 300, 'per' => 'day'], + ['what' => 'Stars', 'limit' => 60, 'per' => 'minute'], + ['what' => 'Pins', 'limit' => 20, 'per' => 'minute'], + ['what' => 'Follows', 'limit' => 30, 'per' => 'minute'], + ['what' => 'Pastéis', 'limit' => 60, 'per' => 'minute'], + ['what' => 'Translations', 'limit' => 10, 'per' => 'minute'], + ['what' => 'Reports', 'limit' => 5, 'per' => 'minute'], + ['what' => 'Organization claims', 'limit' => 10, 'per' => 'minute'], + ['what' => 'Syncs from GitHub', 'limit' => 1, 'per' => 'minute'], + ['what' => 'Feature requests and bug reports', 'limit' => 10, 'per' => 'minute'], + ['what' => 'Feature requests and bug reports opened on GitHub', 'limit' => 10, 'per' => 'day, shared with the web'], + ['what' => 'Reading and polling remotes', 'limit' => 300, 'per' => 'minute'], + ['what' => 'Messages', 'limit' => 30, 'per' => 'minute'], + ['what' => 'Pings', 'limit' => 3, 'per' => 'minute'], + ]); +}); diff --git a/tests/Unit/ApiDocsExamples.test.tsx b/tests/Unit/ApiDocsExamples.test.tsx new file mode 100644 index 0000000000..5cb88e092b --- /dev/null +++ b/tests/Unit/ApiDocsExamples.test.tsx @@ -0,0 +1,273 @@ +/// + +import assert from 'node:assert/strict'; +import { act, createRef, useImperativeHandle, useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import { renderToString } from 'react-dom/server'; +import { afterEach, test, vi } from 'vite-plus/test'; +import { createChoice } from '../../resources/js/components/api-docs/choice'; +import { + activeExample, + chooseExample, + useChosenExample, +} from '../../resources/js/components/api-docs/example-choice'; +import { + ExampleTabs, + moveToExample, + tabKeyTarget, +} from '../../resources/js/components/api-docs/example-tabs'; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +test('shows the client picked last on every endpoint that has it', () => { + const { container, storage } = browser(); + const chosen = createRef<{ label: string | null }>(); + + function Probe() { + const label = useChosenExample(); + useImperativeHandle(chosen, () => ({ label })); + + return null; + } + + const root = createRoot(container); + act(() => root.render()); + const label = () => chosen.current?.label ?? null; + + const labels = ['curl', 'Laravel', 'fetch']; + + assert.equal(activeExample(labels, label()), 0); + + act(() => chooseExample('Laravel')); + + assert.equal(label(), 'Laravel'); + assert.equal(storage.get('api-docs:example'), 'Laravel'); + assert.equal(activeExample(labels, label()), 1); + assert.equal(activeExample(['curl', 'fetch'], label()), 0); + + act(() => root.unmount()); + vi.unstubAllGlobals(); +}); + +function mountChoice(key: string, container: Element) { + const choice = createChoice(key); + const chosen = createRef<{ + value: string | null; + rerender: () => void; + }>(); + + function Probe() { + const value = choice.useChosen(); + const [, setRenders] = useState(0); + useImperativeHandle(chosen, () => ({ + value, + rerender: () => setRenders((renders) => renders + 1), + })); + + return null; + } + + const root = createRoot(container); + act(() => root.render()); + + return { + value: () => chosen.current?.value ?? null, + rerender: () => act(() => chosen.current?.rerender()), + unmount: () => act(() => root.unmount()), + }; +} + +test('reads a choice from the browser once, even when nothing was picked', () => { + const { container } = browser(); + const getItem = vi.spyOn(window.localStorage, 'getItem'); + const choice = mountChoice('api-docs:test-miss', container); + + choice.rerender(); + choice.rerender(); + + assert.equal(choice.value(), null); + assert.equal(getItem.mock.calls.length, 1); + + choice.unmount(); + vi.unstubAllGlobals(); +}); + +test('forgets a choice when another tab clears the storage', () => { + const { container, storage } = browser(); + storage.set('api-docs:test-clear', 'schema'); + const choice = mountChoice('api-docs:test-clear', container); + + assert.equal(choice.value(), 'schema'); + + storage.clear(); + act(() => { + window.dispatchEvent( + Object.assign(new Event('storage'), { key: null, newValue: null }), + ); + }); + + assert.equal(choice.value(), null); + + choice.unmount(); + vi.unstubAllGlobals(); +}); + +test('shows the first example, the others a tab away', () => { + const html = renderToString( + …', + }, + { + label: 'fetch', + language: 'javascript', + code: 'fetch()', + html: 'fetch()', + }, + ]} + />, + ); + + assert.match(html, /role="tablist"/); + assert.match(html, /role="tab" aria-selected="true"[^>]*>curl]*tabindex="-1"[^>]*>fetch…<\/span>/); +}); + +test('underlines the active example tab like the page tabs, with an underline that slides', () => { + const html = renderToString( + , + ); + const tabs = html.match(/]*role="tab".*?<\/button>/g) ?? []; + + assert.equal(tabs.length, 2); + assert.ok(tabs.every((tab) => /text-\[15px\]/.test(tab))); + assert.match( + tabs[0] ?? '', + /