-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplication.php
More file actions
2376 lines (2190 loc) · 112 KB
/
Copy pathApplication.php
File metadata and controls
2376 lines (2190 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Phlix hub component: Hub.
*
* @copyright 2026 Joe Huss <detain@interserver.net>
* @license MIT
*/
declare(strict_types=1);
namespace Phlix\Hub;
use Phlix\Hub\Auth\RateLimitException;
use Phlix\Hub\Common\Container\Providers\HubServicesProvider;
use Channel\Client as ChannelClient;
use Channel\Server as ChannelServer;
use Phlix\Hub\Common\Logger\LogChannels;
use Phlix\Hub\Common\Logger\LoggerFactory;
use Phlix\Hub\Common\Logger\StructuredLogger;
use Phlix\Hub\Health\HealthController;
use Phlix\Hub\Relay\ClientRelayWorker;
use Phlix\Hub\Relay\RelayProxyBridge;
use Phlix\Hub\Relay\RelayProxyProtocol;
use Phlix\Hub\Relay\RelayWorker;
use Phlix\Hub\SyncPlay\ChannelPendingCommandPusher;
use Phlix\Hub\SyncPlay\PendingCommandPusherInterface;
use Phlix\Hub\SyncPlay\SyncPlayRelayWorker;
use Phlix\Hub\Http\Controllers\AdminDashboardController;
use Phlix\Hub\Http\Controllers\AdminUpdatesController;
use Phlix\Hub\Http\Controllers\AdminUserController;
use Phlix\Hub\Http\Controllers\AlexaSkillController;
use Phlix\Hub\Http\Controllers\AuditLogController;
use Phlix\Hub\Http\Controllers\LogController;
use Phlix\Hub\Http\Controllers\AuthController;
use Phlix\Hub\Http\Controllers\ClientMountController;
use Phlix\Hub\Http\Controllers\FederationController;
use Phlix\Hub\Http\Controllers\HubJwksController;
use Phlix\Hub\Http\Controllers\HubRestartController;
use Phlix\Hub\Http\Controllers\HubSettingsController;
use Phlix\Hub\Http\Controllers\InviteLinkController;
use Phlix\Hub\Http\Controllers\LibraryController;
use Phlix\Hub\Http\Controllers\ClientRelayTokenController;
use Phlix\Hub\Http\Controllers\LibraryShareController;
use Phlix\Hub\Http\Controllers\McpController;
use Phlix\Hub\Http\Controllers\McpTokenController;
use Phlix\Hub\Http\Controllers\MeController;
use Phlix\Hub\Http\Controllers\OAuthController;
use Phlix\Hub\Http\Controllers\OAuthUserInfoController;
use Phlix\Hub\Http\Controllers\RelayController;
use Phlix\Hub\Http\Controllers\RequestController;
use Phlix\Hub\Http\Controllers\ServerClaimController;
use Phlix\Hub\Http\Controllers\ServerController;
use Phlix\Hub\Http\Controllers\ServerDetailController;
use Phlix\Hub\Http\Controllers\ServerProxyController;
use Phlix\Hub\Http\Controllers\ServerListController;
use Phlix\Hub\Http\Controllers\ServerManageController;
use Phlix\Hub\Http\Controllers\Stats\MetricsController;
use Phlix\Hub\Http\Controllers\SubdomainController;
use Phlix\Hub\Http\Controllers\UserQuotaController;
use Phlix\Hub\Http\Middleware\AdminMiddleware;
use Phlix\Hub\Http\Middleware\AlexaSignatureMiddleware;
use Phlix\Hub\Http\Middleware\AuthMiddleware;
use Phlix\Hub\Http\Middleware\EnrollmentJwtMiddleware;
use Phlix\Hub\Http\Middleware\HubProtocolMiddleware;
use Phlix\Hub\Http\Middleware\OAuthResourceMiddleware;
use Phlix\Hub\Http\Request;
use Phlix\Hub\Http\Response;
use Phlix\Hub\Http\Router;
use Phlix\Hub\Stats\Metrics\MetricsCollector;
use Phlix\Hub\Stats\Metrics\MetricsFlushService;
use Psr\Container\ContainerInterface;
use Throwable;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request as WorkermanRequest;
use Workerman\Timer;
use Workerman\Worker;
/**
* Phlix Hub main application bootstrap.
*
* Wires the HTTP router with the public surface:
*
* - `GET /health` — service health JSON.
* - `GET /` — landing page (SSR).
* - `GET /signup` / `POST /signup` — signup form + submission.
* - `GET /login` / `POST /login` — login form + submission.
* - `POST /logout` — clear cookies + redirect.
* - `GET /my-servers` — protected dashboard.
* - `POST /api/v1/auth/signup` — JSON signup.
* - `POST /api/v1/auth/login` — JSON login.
* - `POST /api/v1/auth/logout` — JSON logout.
* - `POST /api/v1/auth/refresh` — refresh access token.
* - `GET /api/v1/me` — current user JSON (protected).
*
* @package Phlix\Hub
*/
final class Application
{
/**
* Upper bound for the per-worker static-file stat/realpath memos. The
* public/ asset set is finite, so this is a defensive cap against a flood
* of distinct (typically 404) candidate paths growing the memo without
* limit in a resident Workerman worker (no unbounded static state).
*/
private const int STATIC_FILE_MEMO_MAX = 4096;
private Router $router;
/**
* @param ContainerInterface $container PSR-11 container.
* @param array<string, mixed> $config Server config slice (host, port, workers, …).
*/
public function __construct(
private readonly ContainerInterface $container,
private readonly array $config,
) {
$this->router = new Router();
$this->registerRoutes();
}
/**
* Per-worker realpath() memo — avoids repeated syscalls for hot static paths.
*
* @param string $path Filesystem path to resolve.
*
* @return string|false Resolved real path, or false if not found.
*/
private static function getRealPathMemo(string $path): string|false
{
/** @var array<string, string|false> $memo */
static $memo = [];
if (isset($memo[$path])) {
return $memo[$path];
}
return $memo[$path] = realpath($path);
}
/**
* Per-worker stat memo for hot static paths.
*
* Resolves and caches realpath + mtime + size (and the is_file decision) so
* that serving a static asset does not re-issue blocking realpath()/stat()/
* is_file() syscalls on the event loop for every hit, and so the ETag can be
* derived without an extra syscall. Reuses {@see self::getRealPathMemo()} for
* the realpath leg. Returns false for anything that is not a regular file.
*
* Deploy-staleness caveat: like the realpath memo, both a negative result and
* the mtime/size are cached for the worker's lifetime. Replacing an asset
* in-place without recycling the worker (e.g. `systemctl reload phlix-hub`)
* will keep serving the stale mtime/size (and thus a stale ETag) until the
* worker restarts — acceptable for hashed-immutable assets and the finite
* public/ asset set.
*
* @param string $candidate Filesystem path under the public root.
*
* @return array{real: string, mtime: int, size: int}|false
*/
private static function getStaticFileMemo(string $candidate): array|false
{
/** @var array<string, array{real: string, mtime: int, size: int}|false> $memo */
static $memo = [];
if (array_key_exists($candidate, $memo)) {
return $memo[$candidate];
}
if (count($memo) >= self::STATIC_FILE_MEMO_MAX) {
// Bound the memo to the finite asset set (clear-on-overflow); at
// worst this forces a re-resolve of live entries — never incorrect.
$memo = [];
}
$real = self::getRealPathMemo($candidate);
if ($real === false || !is_file($real)) {
return $memo[$candidate] = false;
}
$stat = @stat($real);
if ($stat === false) {
return $memo[$candidate] = false;
}
return $memo[$candidate] = [
'real' => $real,
'mtime' => $stat['mtime'],
'size' => $stat['size'],
];
}
/**
* Build the canonical HTTP 429 envelope for a {@see RateLimitException}
* that bubbles out of dispatch: `status(429)` + a `Retry-After` header
* (seconds until the window resets, never negative) + a JSON body of
* `{error, code: 'rate_limited'}`. Shared by the central HTTP catch and
* exercised directly by tests so the proxy/jwks central-mapping path (whose
* controllers throw rather than map locally) has coverage. HTTP-only — the
* WS surfaces reject with a close 1013 and never call this.
*/
public static function rateLimitResponse(RateLimitException $e): Response
{
return (new Response())
->status(429)
->header('Retry-After', (string) $e->retryAfterSeconds())
->json(['error' => 'Too Many Requests', 'code' => 'rate_limited']);
}
/**
* Compute the cache headers + conditional-GET (304) decision for a static
* asset. Pure and side-effect-free (no I/O) so it is unit-testable.
*
* Hashed-immutable assets get a year-long immutable Cache-Control and no
* validators — the browser never revalidates them. Non-hashed assets get a
* short max-age plus a strong ETag (mtime+size) and Last-Modified so the
* browser can revalidate; when a request carries a matching If-None-Match
* (weak comparison per RFC 7232 §2.3.2) — or, in its absence, an
* If-Modified-Since not older than the file mtime (§3.3) — the result is
* 304 Not Modified carrying the validators and NO body (the caller must not
* attach a file to a 304).
*
* @param string $mime Resolved Content-Type.
* @param bool $isHashedAsset Path carries a content hash.
* @param int $mtime File modification time (unix seconds).
* @param int $size File size in bytes.
* @param string|null $ifNoneMatch Raw If-None-Match request header.
* @param string|null $ifModifiedSince Raw If-Modified-Since request header.
*
* @return array{status: int, headers: array<string, string>}
*/
public static function computeStaticCacheDecision(
string $mime,
bool $isHashedAsset,
int $mtime,
int $size,
?string $ifNoneMatch,
?string $ifModifiedSince,
): array {
if ($isHashedAsset) {
return [
'status' => 200,
'headers' => [
'Content-Type' => $mime,
'Cache-Control' => 'public, max-age=31536000, immutable',
],
];
}
// Strong validator derived from mtime+size — cheap, stable, and unique
// enough for a static asset without hashing the file contents.
$etag = sprintf('"%x-%x"', $mtime, $size);
$validators = [
'Cache-Control' => 'public, max-age=86400',
'ETag' => $etag,
'Last-Modified' => gmdate('D, d M Y H:i:s', $mtime) . ' GMT',
];
if (self::isStaticAssetNotModified($etag, $mtime, $ifNoneMatch, $ifModifiedSince)) {
// 304: validators only, no Content-Type, no body.
return ['status' => 304, 'headers' => $validators];
}
return ['status' => 200, 'headers' => ['Content-Type' => $mime] + $validators];
}
/**
* Evaluate a conditional GET against a non-hashed asset's validators.
* If-None-Match takes precedence over If-Modified-Since (RFC 7232 §3.3).
*/
private static function isStaticAssetNotModified(
string $etag,
int $mtime,
?string $ifNoneMatch,
?string $ifModifiedSince,
): bool {
if ($ifNoneMatch !== null && $ifNoneMatch !== '') {
return self::etagMatches($ifNoneMatch, $etag);
}
if ($ifModifiedSince !== null && $ifModifiedSince !== '') {
$since = strtotime($ifModifiedSince);
return $since !== false && $mtime <= $since;
}
return false;
}
/**
* Weak comparison of an If-None-Match header (which may be `*`, a single
* entity-tag, or a comma-separated list, any of them weak) against $etag.
*/
private static function etagMatches(string $ifNoneMatch, string $etag): bool
{
$ifNoneMatch = trim($ifNoneMatch);
if ($ifNoneMatch === '*') {
return true;
}
$target = self::stripWeakEtag($etag);
foreach (explode(',', $ifNoneMatch) as $candidate) {
if (self::stripWeakEtag(trim($candidate)) === $target) {
return true;
}
}
return false;
}
/**
* Strip a leading weak indicator (`W/`) from an entity-tag so weak and
* strong forms of the same tag compare equal.
*/
private static function stripWeakEtag(string $etag): string
{
return str_starts_with($etag, 'W/') ? substr($etag, 2) : $etag;
}
/**
* Register every route the hub exposes today.
*/
private function registerRoutes(): void
{
$health = $this->container->get(HealthController::class);
if (!$health instanceof HealthController) {
throw new \RuntimeException('Container returned an unexpected HealthController instance');
}
// S312: the payload now carries the MAINTENANCE WORKER's own liveness,
// and the probe answers 503 when that worker is not completing sweeps.
// `curl -fsS` (the image's HEALTHCHECK) fails on 503, so a container
// whose maintenance worker is crash-looping stops reporting `healthy` —
// which, measured on master, it did not: `docker inspect` said `healthy`
// and `RestartCount=0` while the worker was re-forked every 60s.
$this->router->get('/health', static function () use ($health): Response {
$payload = $health();
return (new Response())->json($payload, HealthController::statusCodeFor($payload));
});
// The legacy Smarty SSR UI has been retired: the bare root and the old
// SSR auth pages now redirect to the Vue SPA (which owns its own auth).
// /signup and /login stay public (no auth gate).
$this->router->get('/', static fn (Request $r): Response => (new Response())->redirect('/app/servers'));
$this->router->get(
'/signup',
static fn (Request $r): Response => (new Response())->redirect('/app/signup'),
);
$this->router->get(
'/login',
static fn (Request $r): Response => (new Response())->redirect('/app/login'),
);
// Shared Vue 3 SPA shell (Phase C) — no auth gate; SPA handles its own auth.
/** @var string $publicRoot */
$publicRoot = is_string($this->config['public_root'] ?? null)
? $this->config['public_root']
: rtrim(dirname(__DIR__) . '/public', DIRECTORY_SEPARATOR);
$sharedUi = new \Phlix\Hub\Http\Controllers\SharedUiController($publicRoot);
$this->router->get('/app', static fn (Request $r) => $sharedUi->shell($r, []));
$this->router->get('/app/{path:.*}', static function (Request $r, array $params) use ($sharedUi): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $sharedUi->shell($r, $typedParams);
});
// JSON API. `/register` is the canonical signup path used by the shared
// @phlix/ui SPA (and phlix-server); `/signup` is kept as an alias. The
// SPA posts auth to `/api/v1/auth/*`; the legacy form-driven SSR POSTs
// (`POST /signup|/login|/logout`) have been retired with the Smarty UI.
$auth = $this->resolveAuthController();
$this->router->post('/api/v1/auth/register', static fn (Request $r): Response => $auth($r));
$this->router->post('/api/v1/auth/signup', static fn (Request $r): Response => $auth($r));
$this->router->post('/api/v1/auth/login', static fn (Request $r): Response => $auth($r));
$this->router->post('/api/v1/auth/logout', static fn (Request $r): Response => $auth($r));
$this->router->post('/api/v1/auth/refresh', static fn (Request $r): Response => $auth($r));
// Protected pages + API.
$authMiddleware = $this->resolveAuthMiddleware();
// Legacy SSR dashboard pages now redirect to the Vue SPA. They stay
// auth-gated so an unauthenticated browser is bounced to /app/login by
// the AuthMiddleware challenge before the redirect ever runs.
$this->router->group('/my-servers', static function (Router $r): void {
$r->get('', static fn (Request $req): Response => (new Response())->redirect('/app/servers'));
}, [$authMiddleware]);
$this->router->group('/claim-server', static function (Router $r): void {
// No dedicated claim page — the claim modal lives in the SPA's
// MyServersPage (/app/servers).
$r->get('', static fn (Request $req): Response => (new Response())->redirect('/app/servers'));
}, [$authMiddleware]);
// Redirect to Vue SPA.
$this->router->group('/invite-links', static function (Router $r): void {
$r->get('', static function (Request $request): Response {
return (new Response())->redirect('/app/invite-links');
});
}, [$authMiddleware]);
$this->router->group('/hub-settings', static function (Router $r): void {
$r->get('', static fn (Request $req): Response => (new Response())->redirect('/app/admin/settings'));
}, [$authMiddleware]);
$this->router->group('/audit-logs', static function (Router $r): void {
$r->get('', static fn (Request $req): Response => (new Response())->redirect('/app/admin/audit-logs'));
}, [$authMiddleware]);
$this->router->group('/logs', static function (Router $r): void {
$r->get('', static fn (Request $req): Response => (new Response())->redirect('/app/admin/logs'));
}, [$authMiddleware]);
$this->router->group('/federation', static function (Router $r): void {
$r->get('', static fn (Request $req): Response => (new Response())->redirect('/app/federation'));
// Redirect to Vue SPA.
$r->get('/shares', static function (Request $request): Response {
return (new Response())->redirect('/app/federation/shares');
});
}, [$authMiddleware]);
// Redirect to Vue SPA.
$this->router->group('/servers/{id}', static function (Router $r): void {
$r->get('', static function (Request $request, array $params): Response {
/** @var string $id */
$id = $params['id'];
return (new Response())->redirect('/app/servers/' . $id);
});
}, [$authMiddleware]);
$me = $this->resolveMeController();
$serverList = $this->resolveServerListController();
$serverManage = $this->resolveServerManageController();
$serverDetail = $this->resolveServerDetailController();
$libraryController = $this->resolveLibraryController();
$serverProxy = $this->resolveServerProxyController();
$relayToken = $this->resolveClientRelayTokenController();
$mcpToken = $this->resolveMcpTokenController();
// MCP (S62/S63) — the Streamable HTTP transport, inside THIS `:8800`
// worker, not a sidecar and not a new port. BOTH verbs live on the ONE
// path the transport defines: `POST` carries client→server JSON-RPC,
// `GET` opens the server→client SSE stream (S63).
//
// Registered with NO route middleware on purpose: an MCP client presents
// a personal access token, not the hub session JWT/cookie AuthMiddleware
// understands, so McpController authenticates BOTH verbs itself — the
// same arrangement RelayController / ClientMountController /
// SubdomainController already use for the enrollment JWT. The ungated set
// is pinned by ApplicationRouteCompositionTest, so this is declared
// rather than accidental, and `GET` is listed there beside `POST`
// precisely so a reviewer sees that the new verb is ungated too.
$mcp = $this->resolveMcpController();
$this->router->post('/mcp', static function (Request $req, array $params) use ($mcp): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $mcp->handle($req, $typedParams);
});
$this->router->get('/mcp', static function (Request $req, array $params) use ($mcp): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $mcp->stream($req, $typedParams);
});
$this->router->group('/api/v1', function (Router $r) use (
$me,
$serverList,
$serverManage,
$serverDetail,
$libraryController,
$serverProxy,
$relayToken,
$mcpToken,
): void {
$r->get('/me', static fn (Request $req): Response => $me($req));
// `/auth/me` is the path the shared @phlix/ui SPA calls (matches
// phlix-server); aliased to the same MeController as `/me`.
$r->get('/auth/me', static fn (Request $req): Response => $me($req));
$r->get('/me/servers', static fn (Request $req): Response => $serverList($req));
$r->delete(
'/me/servers/{id}',
static function (Request $req, array $params) use ($serverManage): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $serverManage->deleteServer($req, $typedParams);
},
);
$r->get(
'/me/servers/{id}/access-info',
static function (Request $req, array $params) use ($serverManage): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $serverManage->accessInfo($req, $typedParams);
},
);
$r->get(
'/me/libraries',
static function (Request $req) use ($libraryController): Response {
return $libraryController->listForServer($req);
},
);
$r->get(
'/me/servers/{id}',
static function (Request $req, array $params) use ($serverDetail): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $serverDetail->getServerDetail($req, $typedParams);
},
);
// Mint a per-user, server-scoped, revocable client relay token
// (Step S2a). Owner-gated: 404 unknown / 403 not-owned. The
// plaintext token is returned exactly once. Worker enforcement +
// dropping the `?token=` query path is the S2b follow-up.
$r->post(
'/me/servers/{id}/relay-token',
static function (Request $req, array $params) use ($relayToken): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $relayToken->mint($req, $typedParams);
},
);
// MCP personal access tokens (S62). Auth-gated by THIS group's
// AuthMiddleware — a hub session mints and revokes MCP tokens; the
// MCP tokens themselves are only ever presented to `POST /mcp`, and
// are useless on this surface (they are not hub session JWTs).
$r->get(
'/me/mcp-tokens',
static function (Request $req, array $params) use ($mcpToken): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $mcpToken->index($req, $typedParams);
},
);
$r->post(
'/me/mcp-tokens',
static function (Request $req, array $params) use ($mcpToken): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $mcpToken->create($req, $typedParams);
},
);
$r->delete(
'/me/mcp-tokens/{id}',
static function (Request $req, array $params) use ($mcpToken): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $mcpToken->revoke($req, $typedParams);
},
);
// HTTP-over-relay proxy: forward a browser request to a paired
// media server over the reverse tunnel (owner-gated). The
// {path:.*} catch-all carries the server-side path + sub-segments.
$proxyHandler = static function (Request $req, array $params) use ($serverProxy): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $serverProxy->proxy($req, $typedParams);
};
$r->get('/servers/{id}/proxy/{path:.*}', $proxyHandler);
// S247: HEAD is registered so a player can PROBE the direct-play
// byte stream (`HEAD /media/{id}/stream`) before it opens it — a
// HEAD that 404s, or that returns a body/a wrong Content-Length,
// breaks the player rather than erroring. Scope is NOT the GET
// scope: `ServerProxyController::BROWSE_SCOPE_PATTERNS['HEAD']`
// carries exactly one anchored entry (the byte stream) and there is
// no HEAD prefix allowlist at all, so every other HEAD reaches the
// controller and gets a deliberate 403 `proxy.scope_denied`. The
// body is suppressed on the buffered reply path via
// `Response::$headOnly` → `BodylessResponse`.
$r->head('/servers/{id}/proxy/{path:.*}', $proxyHandler);
$r->put('/servers/{id}/proxy/{path:.*}', $proxyHandler);
$r->delete('/servers/{id}/proxy/{path:.*}', $proxyHandler);
// PATCH is registered but has NO allowlist/pattern entry in
// ServerProxyController: the media server exposes no PATCH write
// route, so every PATCH deliberately fails closed with 403
// `proxy.scope_denied` (registered-but-deny → a clean 403 rather than
// a bare 404). Add anchored PATCH patterns here + in
// BROWSE_SCOPE_PATTERNS only if the server ever gains a PATCH write.
$r->patch('/servers/{id}/proxy/{path:.*}', $proxyHandler);
// POST is registered so non-allowlisted POSTs still reach the
// controller and get a deliberate 403 `proxy.scope_denied` (fails
// closed) rather than a bare 404. The permitted write actions
// (favorite, rating, like, watched/unwatched, poster, playlist,
// transcode) are ANCHORED per-action PCREs in
// ServerProxyController::BROWSE_SCOPE_PATTERNS.
$r->post('/servers/{id}/proxy/{path:.*}', $proxyHandler);
}, [$authMiddleware]);
// Server-claim and server routes.
$this->registerServerRoutes($authMiddleware);
// Library sharing routes.
$this->registerSharingRoutes($authMiddleware);
// Invite link routes.
$this->registerInviteLinkRoutes();
// Hub admin settings routes (admin-only API).
$this->registerHubSettingsRoutes();
// Audit log routes (admin-only API).
$this->registerAuditLogRoutes();
// Log viewer routes (admin-only API) — list + tail the hub log files.
$this->registerLogRoutes();
// Shared admin console log-viewer routes — the @phlix/ui AdminLogsApi
// calls `/api/v1/admin/logs*`; mirror the `/api/v1/me/logs*` routes
// onto that path so the shared admin pages work on the hub (hubby.md H1.1).
$this->registerAdminLogRoutes();
// Shared admin console settings routes — the @phlix/ui AdminSettingsApi
// calls `/api/v1/admin/settings`; mirror the `/api/v1/me/hub-settings`
// surface onto that path so the shared admin Settings page works on the
// hub (hubby.md H1.2). Same HubSettingsController, same auth + admin gate.
$this->registerAdminSettingsRoutes();
// Phase 10: graceful hub restart — POST /api/v1/admin/restart (SIGUSR1).
$this->registerAdminRestartRoutes();
// Core update check (S75 / updates.md #48) — read the update status the
// maintenance worker polls for, and toggle the poll on/off.
$this->registerAdminUpdatesRoutes();
// Shared admin console user-management routes — the @phlix/ui
// AdminUsersApi calls `/api/v1/admin/users*`; this serves that surface
// (list/get/create/update/delete + set-admin/reset-password, and an
// always-empty per-user profiles list) so the shared admin Users page
// works on the hub (hubby.md H1.3). Same auth + admin gate.
$this->registerAdminUserRoutes();
// Shared admin console dashboard routes — the @phlix/ui
// AdminHubDashboardApi (HubDashboardPage) calls
// `/api/v1/admin/dashboard/{summary,activity}`; this serves the
// hub-scoped headline counters + recent-activity feed aggregated from
// existing tables (hubby.md H1.4). Same auth + admin gate.
$this->registerAdminDashboardRoutes();
// Federation management routes.
$this->registerFederationRoutes();
// Media request routes.
$this->registerRequestRoutes();
// Per-user relay bandwidth quota routes (HB-3.4 G5): self usage +
// admin set/view of caps.
$this->registerUserQuotaRoutes();
// Metrics routes (admin-only API, S4).
$this->registerMetricsRoutes();
// Alexa custom skill endpoint (S91), gated by S90's signature middleware.
$this->registerAlexaRoutes();
// OAuth 2.0 Authorization Server (S92) — shared, not Alexa-specific.
$this->registerOAuthRoutes();
}
/**
* Register the OAuth 2.0 Authorization Server (S92) and its first protected
* resource (S286) — exactly four routes.
*
* ```
* GET /oauth/authorize AuthMiddleware renders the consent screen; mints NOTHING
* POST /oauth/authorize AuthMiddleware records the decision; mints the code
* POST /oauth/token (no middleware) exchanges the code / rotates a refresh token
* GET /oauth/userinfo OAuthResourceMiddleware the linked account's identity
* ```
*
* The first three lines are the Authorization Server; the fourth is the
* RESOURCE server, and it is the only route in the hub on which an OAuth
* access token grants anything. Note the fourth gate is a DIFFERENT
* middleware from the first two — see the block that registers it.
*
* Three deliberate decisions are encoded in that table, and each is pinned
* by the route suites rather than left to this comment:
*
* - **The two `/oauth/authorize` verbs share a gate and split the work.**
* Consent is enforced because the GET has no code-minting path at all,
* not because it renders a page. Moving the mint into the GET, or
* dropping the POST, would leave a route table that still looks correct.
* - **`AuthMiddleware`, not `AuthMiddleware` + something.** The path is not
* under `/api/`, so an unauthenticated visitor is bounced to
* `/app/login` (a 302) rather than handed a JSON 401 — which is what a
* human arriving from a third-party app should get. The POST is also
* cookie-authenticable for the same reason: `AuthMiddleware` only forces
* bearer-only on mutating `/api/` paths. The consent form's CSRF defence
* is the single-use, user-bound consent ticket, which a cross-origin page
* cannot read (see {@see \Phlix\Hub\OAuth\ConsentTicketService}).
* - **`/oauth/token` carries NO route middleware, on purpose.** Its caller
* is a client, not a hub user; it has no session and must not be bounced
* to a login page. It authenticates itself inside the controller with
* `client_id` (+ `client_secret` when confidential) and mandatory PKCE.
* It is listed in `ApplicationRouteCompositionTest::UNGATED_ROUTES`, so
* it is ungated by an explicit decision that a reviewer signed off, not
* by an omission.
*/
private function registerOAuthRoutes(): void
{
$oauth = $this->resolveOAuthController();
$authMiddleware = $this->resolveAuthMiddleware();
$this->router->group('/oauth', static function (Router $r) use ($oauth): void {
$r->get('/authorize', static function (Request $req, array $params) use ($oauth): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $oauth->authorize($req, $typedParams);
});
$r->post('/authorize', static function (Request $req, array $params) use ($oauth): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $oauth->consent($req, $typedParams);
});
}, [$authMiddleware]);
// Registered OUTSIDE the group above: the token endpoint must not
// inherit its AuthMiddleware. A client exchanging a code has no hub
// session and would be 302'd to /app/login.
$this->router->post('/oauth/token', static function (Request $req, array $params) use ($oauth): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $oauth->token($req, $typedParams);
});
// S286 — the RESOURCE-SERVER surface, and the ONLY route on which an
// OAuth access token grants anything at all.
//
// Its gate is {@see OAuthResourceMiddleware}, NOT AuthMiddleware, and the
// two are not interchangeable: AuthMiddleware authenticates a hub user
// holding a session JWT that carries no scopes, so putting it here would
// serve an unscoped credential on a scoped surface (and would 302 a
// third-party client to `/app/login`, which no client can follow).
//
// The required scope is passed to the middleware at construction and is
// rejected there if it normalises to nothing, so this route cannot end
// up gated on an empty allow-list — see that class.
$userInfo = $this->resolveOAuthUserInfoController();
$this->router->group('/oauth', static function (Router $r) use ($userInfo): void {
$r->get('/userinfo', static function (Request $req, array $params) use ($userInfo): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $userInfo->userInfo($req, $typedParams);
});
}, [$this->resolveOAuthResourceMiddleware()]);
}
private function resolveOAuthController(): OAuthController
{
$controller = $this->container->get(OAuthController::class);
if (!$controller instanceof OAuthController) {
throw new \RuntimeException('Container returned an unexpected OAuthController instance');
}
return $controller;
}
private function resolveOAuthUserInfoController(): OAuthUserInfoController
{
$controller = $this->container->get(OAuthUserInfoController::class);
if (!$controller instanceof OAuthUserInfoController) {
throw new \RuntimeException('Container returned an unexpected OAuthUserInfoController instance');
}
return $controller;
}
private function resolveOAuthResourceMiddleware(): OAuthResourceMiddleware
{
$middleware = $this->container->get(OAuthResourceMiddleware::class);
if (!$middleware instanceof OAuthResourceMiddleware) {
throw new \RuntimeException('Container returned an unexpected OAuthResourceMiddleware instance');
}
return $middleware;
}
/**
* Register the Alexa custom skill endpoint (S91) — exactly one route.
*
* `POST /alexa/skill`, gated by {@see AlexaSignatureMiddleware} and by
* NOTHING else. That is deliberate on both counts:
*
* - There is no {@see AuthMiddleware}. An Alexa request carries no hub
* session: it carries Amazon's detached RSA signature over the raw body,
* and a linked-account bearer token inside the JSON. The signature is the
* authenticity proof and it is checked by the middleware; the linked
* account is resolved inside {@see AlexaSkillController} by
* `AlexaAccountLink`, which answers "please link your account" rather than
* a 401 when it cannot. Fronting the path with `AuthMiddleware` would
* bounce every real Alexa request with a 401 before the signature was
* ever examined.
* - The signature middleware is NOT optional and is not something the
* controller re-checks. It is the only thing standing between this public
* path and anyone on the internet, so the route's middleware chain is
* pinned by class name in the route suite: a wrapper that replaced it —
* even one that called through — would fail that assertion, which is why
* S91's rate limiter and rejection auditor live INSIDE the middleware
* rather than beside it (the router has no "after" hook).
*/
private function registerAlexaRoutes(): void
{
$alexaSignature = $this->resolveAlexaSignatureMiddleware();
$skill = $this->resolveAlexaSkillController();
// `Router::post()` takes no middleware argument — a group is the only way
// to attach one, exactly as every other gated route here does it.
$this->router->group('/alexa/skill', static function (Router $r) use ($skill): void {
$r->post('', static function (Request $req, array $params) use ($skill): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $skill->handle($req, $typedParams);
});
}, [$alexaSignature]);
}
private function resolveAlexaSignatureMiddleware(): AlexaSignatureMiddleware
{
$middleware = $this->container->get(AlexaSignatureMiddleware::class);
if (!$middleware instanceof AlexaSignatureMiddleware) {
throw new \RuntimeException('Container returned an unexpected AlexaSignatureMiddleware instance');
}
return $middleware;
}
private function resolveAlexaSkillController(): AlexaSkillController
{
$controller = $this->container->get(AlexaSkillController::class);
if (!$controller instanceof AlexaSkillController) {
throw new \RuntimeException('Container returned an unexpected AlexaSkillController instance');
}
return $controller;
}
/**
* Register the media-request routes — both the user surface under
* `/api/v1/me/requests` and the admin queue under
* `/api/v1/admin/requests`. Also wires the SSR pages at `/requests`
* (user) and `/admin/requests` (admin queue).
*/
private function registerRequestRoutes(): void
{
$authMiddleware = $this->resolveAuthMiddleware();
$adminMiddleware = $this->resolveAdminMiddleware();
$requestController = $this->resolveRequestController();
// Redirect to Vue SPA.
$this->router->group('/requests', static function (Router $r): void {
$r->get('', static function (Request $request): Response {
return (new Response())->redirect('/app/requests');
});
}, [$authMiddleware]);
// Redirect to Vue SPA. Admin-gated like every other `/admin/*` surface:
// the page it points at is the admin queue, so a non-admin is refused
// here (403) rather than bounced into an SPA route they cannot use.
$this->router->group('/admin/requests', static function (Router $r): void {
$r->get('', static function (Request $request): Response {
return (new Response())->redirect('/app/admin/requests');
});
}, [$authMiddleware, $adminMiddleware]);
// User-scoped JSON API.
$this->router->group('/api/v1/me/requests', static function (Router $r) use ($requestController): void {
$r->post('', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->createRequest($req, $typedParams);
});
$r->get('', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->listMyRequests($req, $typedParams);
});
$r->get('/{id}', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->getMyRequest($req, $typedParams);
});
$r->delete('/{id}', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->deleteMyRequest($req, $typedParams);
});
}, [$authMiddleware]);
// Admin queue + actions. Gated by AdminMiddleware in addition to the
// controller's own requireAdmin() so the group is protected even if a
// future handler in this group forgets the inline check.
$this->router->group('/api/v1/admin/requests', static function (Router $r) use ($requestController): void {
$r->get('', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->listAdminRequests($req, $typedParams);
});
$r->post('/{id}/approve', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->approveRequest($req, $typedParams);
});
$r->post('/{id}/deny', static function (Request $req, array $params) use ($requestController): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $requestController->denyRequest($req, $typedParams);
});
}, [$authMiddleware, $adminMiddleware]);
}
/**
* Register the per-user relay bandwidth quota routes (HB-3.4 G5).
*
* Self surface under `/api/v1/me/bandwidth` (auth only — a user reads their
* OWN usage). Admin surface under `/api/v1/admin/users/{id}/...` gated by
* {@see AdminMiddleware} in addition to the controller's own requireAdmin()
* so a non-admin can neither set another user's caps nor read another
* user's usage (403). This covers both the monthly byte-cap quota
* (`PUT …/quota`) and the per-user relay throttle (`PUT …/throttle`, S41).
* These are hub-local admin/self endpoints and are NOT exposed over the
* relay proxy allowlist.
*/
private function registerUserQuotaRoutes(): void
{
$authMiddleware = $this->resolveAuthMiddleware();
$adminMiddleware = $this->resolveAdminMiddleware();
$controller = $this->resolveUserQuotaController();
// Self usage — auth only.
$this->router->group('/api/v1/me/bandwidth', static function (Router $r) use ($controller): void {
$r->get('', static fn (Request $req): Response => $controller->viewOwnBandwidth($req));
}, [$authMiddleware]);
// Admin set/view — auth + admin (plus the controller's inline requireAdmin).
$this->router->group('/api/v1/admin/users', static function (Router $r) use ($controller): void {
$r->get('/{id}/bandwidth', static function (Request $req, array $params) use ($controller): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $controller->viewUserBandwidth($req, $typedParams);
});
$r->put('/{id}/quota', static function (Request $req, array $params) use ($controller): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $controller->setUserQuota($req, $typedParams);
});
$r->put('/{id}/throttle', static function (Request $req, array $params) use ($controller): Response {
/** @var array<string, string> $typedParams */
$typedParams = $params;
return $controller->setUserThrottle($req, $typedParams);
});
}, [$authMiddleware, $adminMiddleware]);
}
private function resolveUserQuotaController(): UserQuotaController
{
$controller = $this->container->get(UserQuotaController::class);
if (!$controller instanceof UserQuotaController) {
throw new \RuntimeException('Container returned an unexpected UserQuotaController instance');
}
return $controller;
}
private function resolveAdminMiddleware(): AdminMiddleware
{
$middleware = $this->container->get(AdminMiddleware::class);
if (!$middleware instanceof AdminMiddleware) {
throw new \RuntimeException('Container returned an unexpected AdminMiddleware instance');
}
return $middleware;
}
private function resolveRequestController(): RequestController
{
$controller = $this->container->get(RequestController::class);
if (!$controller instanceof RequestController) {
throw new \RuntimeException('Container returned an unexpected RequestController instance');
}
return $controller;
}
private function resolveAuthController(): AuthController
{
$controller = $this->container->get(AuthController::class);
if (!$controller instanceof AuthController) {
throw new \RuntimeException('Container returned an unexpected AuthController instance');
}
return $controller;
}
private function resolveMeController(): MeController
{
$controller = $this->container->get(MeController::class);
if (!$controller instanceof MeController) {
throw new \RuntimeException('Container returned an unexpected MeController instance');
}
return $controller;
}
private function resolveServerListController(): ServerListController
{
$controller = $this->container->get(ServerListController::class);
if (!$controller instanceof ServerListController) {
throw new \RuntimeException('Container returned an unexpected ServerListController instance');
}
return $controller;
}
private function resolveServerManageController(): ServerManageController
{
$controller = $this->container->get(ServerManageController::class);
if (!$controller instanceof ServerManageController) {
throw new \RuntimeException('Container returned an unexpected ServerManageController instance');