Phase 8 Mobil: REST-API, Web-Push, installierbare App (0.25.0)
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 3m54s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 4m0s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 4m54s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 4m50s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m48s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m38s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m56s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 7m5s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m17s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-27 08:20:07 +00:00
parent 232dc5c59c
commit f11a3e24b3
201 changed files with 3604 additions and 427 deletions

View file

@ -0,0 +1,70 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Support\Audit;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
/**
* Token für eine App (nur Konten mit Portal-Passwort; bei Anmeldung über
* Microsoft & Co. erzeugt man das Token unter „Profil → Apps & Geräte“).
*/
public function token(Request $request): JsonResponse
{
$data = $request->validate([
'email' => ['required', 'email'],
'password' => ['required', 'string'],
'device_name' => ['required', 'string', 'max:100'],
]);
$user = User::query()->where('email', $data['email'])->first();
if (! $user || ! $user->is_active || $user->password === null || ! Hash::check($data['password'], $user->password)) {
throw ValidationException::withMessages(['email' => 'Diese Kombination aus Zugangsdaten wurde nicht gefunden.']);
}
$token = $user->createToken(trim($data['device_name']));
Audit::log('api.token_created', ['user' => $user->id, 'device' => $data['device_name']]);
return response()->json(['token' => $token->plainTextToken, 'user' => self::profile($user)], 201);
}
public function me(Request $request): JsonResponse
{
return response()->json(['user' => self::profile($request->user())]);
}
public function revoke(Request $request): JsonResponse
{
$request->user()->currentAccessToken()?->delete();
return response()->json(['revoked' => true]);
}
/**
* @return array<string, mixed>
*/
private static function profile(User $user): array
{
return [
'id' => $user->id,
'name' => $user->name,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'job_title' => $user->job_title,
'department' => $user->department,
'location' => $user->location,
'avatar_url' => $user->avatarUrl(256),
'cover_url' => $user->coverUrl(),
'unread_notifications' => $user->unreadNotifications()->count(),
];
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Notifications\DatabaseNotification;
class NotificationController extends Controller
{
public function index(Request $request): JsonResponse
{
$page = $request->user()->notifications()->latest()->paginate(30);
return response()->json([
'data' => collect($page->items())->map(fn (DatabaseNotification $n) => [
'id' => $n->id,
...array_intersect_key((array) $n->data, array_flip(['title', 'body', 'url', 'icon'])),
'read' => $n->read_at !== null,
'created_at' => $n->created_at?->toIso8601String(),
]),
'meta' => ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'unread' => $request->user()->unreadNotifications()->count()],
]);
}
public function read(Request $request, string $id): JsonResponse
{
$request->user()->notifications()->whereKey($id)->firstOrFail()->markAsRead();
return response()->json(['read' => true]);
}
public function readAll(Request $request): JsonResponse
{
$request->user()->unreadNotifications()->update(['read_at' => now()]);
return response()->json(['read' => true]);
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\PersonResource;
use App\Models\User;
use App\Support\ProfileFields;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PeopleController extends Controller
{
public function index(Request $request): JsonResponse
{
$q = trim((string) ($request->validate(['q' => ['nullable', 'string', 'max:100']])['q'] ?? ''));
$like = '%'.str_replace(['%', '_'], ['\%', '\_'], $q).'%';
$people = User::query()->active()
->when($q !== '', fn (Builder $query) => $query->where(fn (Builder $w) => $w
->where('name', 'like', $like)->orWhere('email', 'like', $like)
->orWhere('department', 'like', $like)->orWhere('job_title', 'like', $like)))
->orderBy('last_name')->orderBy('first_name')
->paginate(50);
return response()->json([
'data' => PersonResource::collection($people->items())->resolve(),
'meta' => ['current_page' => $people->currentPage(), 'last_page' => $people->lastPage(), 'total' => $people->total()],
]);
}
public function show(Request $request, User $user, ProfileFields $fields): JsonResponse
{
abort_unless($user->is_active, 404);
return response()->json(['data' => [
...(new PersonResource($user))->resolve(),
'email' => $user->email,
'phone' => $user->phone,
'mobile' => $user->mobile,
'location' => $user->location,
'about' => $user->about,
'avatar_url' => $user->avatarUrl(256),
'cover_url' => $user->coverUrl(),
'fields' => $fields->visibleValues($user, $request->user()),
'manager_id' => $user->manager?->is_active ? $user->manager_id : null,
]]);
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Search\GlobalSearch;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function __invoke(Request $request, GlobalSearch $search): JsonResponse
{
$query = trim((string) ($request->validate(['q' => ['required', 'string', 'max:100']])['q']));
return response()->json(['query' => $query, 'groups' => $search->run($request->user(), $query, 10)]);
}
}

View file

@ -5,9 +5,11 @@ namespace App\Http\Controllers;
use App\Http\Requests\UpdateProfileRequest;
use App\Models\User;
use App\Profile\ProfileSections;
use App\Support\Audit;
use App\Support\Avatars;
use App\Support\Covers;
use App\Support\ProfileFields;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
@ -45,6 +47,13 @@ class ProfileController extends Controller
'managed' => $managed,
'customFields' => $profileFields->formFor($user, $managed),
'sections' => app(ProfileSections::class)->resolve($user),
// Apps & Geräte: persönliche Zugangs-Tokens für die REST-API
'tokens' => $user->tokens()->latest()->get()->map(fn ($token) => [
'id' => $token->id,
'name' => $token->name,
'created_at' => $token->created_at?->toIso8601String(),
'last_used_at' => $token->last_used_at?->toIso8601String(),
]),
]);
}
@ -94,6 +103,24 @@ class ProfileController extends Controller
return back()->with('status', 'avatar-deleted');
}
public function createToken(Request $request): JsonResponse
{
$data = $request->validate(['name' => ['required', 'string', 'max:100']], [], ['name' => 'Name']);
abort_if($request->user()->tokens()->count() >= 20, 422, 'Höchstens 20 Apps und Geräte – bitte alte entfernen.');
$token = $request->user()->createToken(trim($data['name']));
Audit::log('api.token_created', ['user' => $request->user()->id, 'device' => $data['name']]);
return response()->json(['token' => $token->plainTextToken, 'id' => $token->accessToken->id]);
}
public function destroyToken(Request $request, int $token): RedirectResponse
{
$request->user()->tokens()->whereKey($token)->delete();
return back()->with('status', 'token-deleted');
}
public function updateCover(Request $request, Covers $covers): RedirectResponse
{
$request->validate([

View file

@ -0,0 +1,55 @@
<?php
namespace App\Http\Controllers;
use App\Notifications\PortalNotification;
use App\Push\PushSubscription;
use App\Push\WebPush;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Push-Benachrichtigungen je Gerät an- und abmelden.
*/
class PushController extends Controller
{
public function subscribe(Request $request, WebPush $push): JsonResponse
{
abort_unless(WebPush::supported(), 404);
$data = $request->validate([
'endpoint' => ['required', 'string', 'max:2000', 'regex:#^https://#'],
'keys.p256dh' => ['required', 'string', 'max:120'],
'keys.auth' => ['required', 'string', 'max:40'],
]);
PushSubscription::query()->updateOrCreate(
['endpoint_hash' => hash('sha256', $data['endpoint'])],
[
'user_id' => $request->user()->id,
'endpoint' => $data['endpoint'],
'public_key' => $data['keys']['p256dh'],
'auth_token' => $data['keys']['auth'],
'user_agent' => mb_substr((string) $request->userAgent(), 0, 255),
],
);
return response()->json(['subscribed' => true]);
}
public function unsubscribe(Request $request): JsonResponse
{
$request->validate(['endpoint' => ['required', 'string', 'max:2000']]);
PushSubscription::query()->where('user_id', $request->user()->id)->where('endpoint_hash', hash('sha256', (string) $request->input('endpoint')))->delete();
return response()->json(['subscribed' => false]);
}
public function test(Request $request): JsonResponse
{
$request->user()->notify(new PortalNotification('Push funktioniert', 'So erscheinen Hinweise aus dem Portal auf diesem Gerät.', '/', 'bell'));
return response()->json(['sent' => true]);
}
}

View file

@ -2,6 +2,7 @@
namespace App\Http\Middleware;
use App\Push\WebPush;
use App\Support\Branding;
use App\Support\Navigation;
use Illuminate\Http\Request;
@ -41,6 +42,8 @@ class HandleInertiaRequests extends Middleware
],
'navigation' => fn () => $user ? $this->navigation->items($request, $user) : [],
'notifications' => fn () => $user ? ['unread' => $user->unreadNotifications()->count()] : null,
// Web-Push: öffentlicher Schlüssel für dieses Portal
'push' => fn () => $user && WebPush::supported() ? ['key' => app(WebPush::class)->publicKey()] : null,
'flash' => [
'status' => fn () => $request->session()->get('status'),
'comment' => fn () => $request->session()->get('comment'),

View file

@ -21,6 +21,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
#[Fillable([
'name', 'first_name', 'last_name', 'email', 'password',
@ -31,7 +32,7 @@ use Illuminate\Support\Str;
class User extends Authenticatable implements FilamentUser, HasAvatar
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
use HasApiTokens, HasFactory, Notifiable;
public const THEMES = ['system', 'light', 'dark'];

View file

@ -2,6 +2,9 @@
namespace App\Notifications;
use App\Models\User;
use App\Push\PushSubscription;
use App\Push\WebPushChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
@ -27,7 +30,10 @@ class PortalNotification extends Notification
*/
public function via(object $notifiable): array
{
return ['database'];
// Zusätzlich als Push auf Geräte, die das eingeschaltet haben
$push = $notifiable instanceof User && PushSubscription::query()->where('user_id', $notifiable->id)->exists();
return $push ? ['database', WebPushChannel::class] : ['database'];
}
/**

View file

@ -208,6 +208,11 @@ class PluginManager
Route::middleware(['web', EnsurePluginAccess::class.':'.$manifest->slug])->group($manifest->path.'/routes/web.php');
}
// REST-API des Plugins: /api/v1/…, nur mit gültigem Token
if (is_file($manifest->path.'/routes/api.php') && ! $this->app->routesAreCached()) {
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', EnsurePluginAccess::class.':'.$manifest->slug])->group($manifest->path.'/routes/api.php');
}
$plugin->boot();
});
}

View file

@ -39,6 +39,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Sanctum\Sanctum;
class AppServiceProvider extends ServiceProvider
{
@ -84,6 +85,9 @@ class AppServiceProvider extends ServiceProvider
public function boot(): void
{
// API-Tokens deaktivierter Konten gelten nicht mehr
Sanctum::authenticateAccessTokensUsing(fn ($token, bool $isValid) => $isValid && $token->tokenable instanceof User && $token->tokenable->is_active);
CoreWidgets::register($this->app->make(Widgets::class));
$this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder', 'media.*'], sort: 85,

View file

@ -0,0 +1,25 @@
<?php
namespace App\Push;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['user_id', 'endpoint_hash', 'endpoint', 'public_key', 'auth_token', 'user_agent', 'last_used_at'])]
class PushSubscription extends Model
{
protected function casts(): array
{
return ['last_used_at' => 'datetime'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

38
app/Push/SendWebPush.php Normal file
View file

@ -0,0 +1,38 @@
<?php
namespace App\Push;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Throwable;
/**
* Push-Nachricht an alle Geräte einer Person – im Hintergrund, damit
* langsame Push-Dienste keine Seite aufhalten.
*/
class SendWebPush implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable;
public int $tries = 2;
/**
* @param array<string, mixed> $payload
*/
public function __construct(public readonly int $userId, public readonly array $payload) {}
public function handle(WebPush $push): void
{
foreach (PushSubscription::query()->where('user_id', $this->userId)->get() as $subscription) {
try {
$push->send($subscription, $this->payload)
? $subscription->forceFill(['last_used_at' => now()])->save()
: $subscription->delete();
} catch (Throwable $e) {
report($e);
}
}
}
}

187
app/Push/WebPush.php Normal file
View file

@ -0,0 +1,187 @@
<?php
namespace App\Push;
use App\Support\Settings;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use OpenSSLAsymmetricKey;
use RuntimeException;
use Throwable;
/**
* Web-Push ohne zusätzliche Pakete – nur mit OpenSSL:
* Verschlüsselung nach RFC 8291 (aes128gcm) und Absender-Kennung nach RFC 8292 (VAPID).
*
* Die Schlüssel entstehen beim ersten Gebrauch und liegen verschlüsselt in den Einstellungen.
*/
class WebPush
{
public const KEYS = 'push.vapid';
/** Präfix einer DER-kodierten P-256-Public-Key-Struktur (SubjectPublicKeyInfo) vor dem 65-Byte-Punkt */
private const P256_SPKI_PREFIX = '3059301306072a8648ce3d020106082a8648ce3d030107034200';
public function __construct(private readonly Settings $settings) {}
public static function supported(): bool
{
return extension_loaded('openssl') && function_exists('openssl_pkey_derive') && in_array('aes-128-gcm', openssl_get_cipher_methods(), true);
}
/** Öffentlicher Schlüssel für den Browser (applicationServerKey, base64url) */
public function publicKey(): ?string
{
return self::supported() ? $this->keys()['public'] : null;
}
/**
* Nachricht an ein Abonnement senden. Liefert false, wenn das Abonnement ungültig ist (abgelaufen, abgemeldet).
*
* @param array<string, mixed> $payload
*/
public function send(PushSubscription $subscription, array $payload): bool
{
$body = $this->encrypt((string) json_encode($payload, JSON_UNESCAPED_UNICODE), $subscription->public_key, $subscription->auth_token);
$keys = $this->keys();
$response = Http::timeout(10)->withHeaders([
'Authorization' => 'vapid t='.$this->jwt($subscription->endpoint, $keys['private']).', k='.$keys['public'],
'Content-Encoding' => 'aes128gcm',
'Content-Type' => 'application/octet-stream',
'TTL' => '86400',
'Urgency' => 'normal',
])->withBody($body, 'application/octet-stream')->post($subscription->endpoint);
if (in_array($response->status(), [404, 410], true)) {
return false;
}
if (! $response->successful()) {
Log::warning('Web-Push abgelehnt: HTTP '.$response->status().' '.mb_substr($response->body(), 0, 200));
}
return true;
}
/**
* Inhalt verschlüsseln (RFC 8291). Ergebnis: Kopf (Salt, Satzgröße, Absenderschlüssel) + Chiffrat.
*/
public function encrypt(string $plaintext, string $userPublicKey, string $userAuth): string
{
$uaPublic = self::base64UrlDecode($userPublicKey);
$authSecret = self::base64UrlDecode($userAuth);
if (strlen($uaPublic) !== 65 || $uaPublic[0] !== "\x04" || strlen($authSecret) < 16) {
throw new RuntimeException('Ungültiges Push-Abonnement.');
}
// Einmal-Schlüsselpaar des Servers für diese Nachricht
$ephemeral = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
$asPublic = self::rawPublicKey($ephemeral);
$shared = openssl_pkey_derive(self::publicKeyFromRaw($uaPublic), $ephemeral, 32);
if ($shared === false) {
throw new RuntimeException('Schlüsselaustausch fehlgeschlagen.');
}
$ikm = hash_hkdf('sha256', $shared, 32, "WebPush: info\0".$uaPublic.$asPublic, $authSecret);
$salt = random_bytes(16);
$cek = hash_hkdf('sha256', $ikm, 16, "Content-Encoding: aes128gcm\0", $salt);
$nonce = hash_hkdf('sha256', $ikm, 12, "Content-Encoding: nonce\0", $salt);
$tag = '';
$cipher = openssl_encrypt($plaintext."\x02", 'aes-128-gcm', $cek, OPENSSL_RAW_DATA, $nonce, $tag);
return $salt.pack('N', 4096).chr(65).$asPublic.$cipher.$tag;
}
/**
* VAPID-Kennung: signiertes JWT (ES256) für den Push-Dienst des Abonnements.
*/
private function jwt(string $endpoint, OpenSSLAsymmetricKey $private): string
{
$parts = parse_url($endpoint);
$header = self::base64UrlEncode('{"typ":"JWT","alg":"ES256"}');
$claims = self::base64UrlEncode((string) json_encode([
'aud' => $parts['scheme'].'://'.$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : ''),
'exp' => time() + 12 * 3600,
'sub' => rtrim((string) config('app.url'), '/') ?: 'mailto:admin@example.org',
]));
openssl_sign($header.'.'.$claims, $der, $private, OPENSSL_ALGO_SHA256);
return $header.'.'.$claims.'.'.self::base64UrlEncode(self::derToRaw($der));
}
/**
* @return array{public: string, private: OpenSSLAsymmetricKey}
*/
private function keys(): array
{
$stored = $this->settings->get(self::KEYS);
try {
if (is_array($stored) && isset($stored['private'], $stored['public'])) {
$private = openssl_pkey_get_private(Crypt::decryptString($stored['private']));
if ($private) {
return ['public' => $stored['public'], 'private' => $private];
}
}
} catch (Throwable) {
// z. B. neuer APP_KEY – dann neue Schlüssel (bestehende Abonnements werden ungültig)
}
$private = openssl_pkey_new(['curve_name' => 'prime256v1', 'private_key_type' => OPENSSL_KEYTYPE_EC]);
openssl_pkey_export($private, $pem);
$public = self::base64UrlEncode(self::rawPublicKey($private));
$this->settings->set(self::KEYS, ['public' => $public, 'private' => Crypt::encryptString($pem)]);
PushSubscription::query()->delete();
return ['public' => $public, 'private' => $private];
}
public static function rawPublicKey(OpenSSLAsymmetricKey $key): string
{
$ec = openssl_pkey_get_details($key)['ec'];
return "\x04".str_pad($ec['x'], 32, "\0", STR_PAD_LEFT).str_pad($ec['y'], 32, "\0", STR_PAD_LEFT);
}
public static function publicKeyFromRaw(string $raw): OpenSSLAsymmetricKey
{
$pem = "-----BEGIN PUBLIC KEY-----\n".chunk_split(base64_encode(hex2bin(self::P256_SPKI_PREFIX).$raw), 64, "\n")."-----END PUBLIC KEY-----\n";
$key = openssl_pkey_get_public($pem);
if (! $key) {
throw new RuntimeException('Ungültiger öffentlicher Schlüssel.');
}
return $key;
}
/** ECDSA-Signatur von DER (SEQUENCE r, s) in 64 Byte r||s umwandeln */
private static function derToRaw(string $der): string
{
$offset = 3 + (ord($der[1]) & 0x80 ? ord($der[1]) & 0x7F : 0);
$rLength = ord($der[$offset]);
$r = substr($der, $offset + 1, $rLength);
$offset += 1 + $rLength + 1;
$sLength = ord($der[$offset]);
$s = substr($der, $offset + 1, $sLength);
return str_pad(ltrim($r, "\0"), 32, "\0", STR_PAD_LEFT).str_pad(ltrim($s, "\0"), 32, "\0", STR_PAD_LEFT);
}
public static function base64UrlEncode(string $value): string
{
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
}
public static function base64UrlDecode(string $value): string
{
return (string) base64_decode(strtr($value, '-_', '+/').str_repeat('=', (4 - strlen($value) % 4) % 4));
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Push;
use App\Models\User;
use App\Support\Branding;
use Illuminate\Notifications\Notification;
/**
* Benachrichtigungskanal: dieselben Hinweise wie in der Glocke zusätzlich als Push.
*/
class WebPushChannel
{
public function send(object $notifiable, Notification $notification): void
{
if (! $notifiable instanceof User || ! method_exists($notification, 'toArray')) {
return;
}
$data = $notification->toArray($notifiable);
SendWebPush::dispatch($notifiable->id, [
'title' => (string) ($data['title'] ?? ''),
'body' => (string) ($data['body'] ?? ''),
'url' => $data['url'] ?? '/',
'tag' => $notification->id,
'icon' => self::icon(),
]);
}
/** App-Symbol (192 px) aus dem Erscheinungsbild, sonst das Favicon */
private static function icon(): string
{
$branding = app(Branding::class);
$icons = (array) ($branding->get('icons') ?? []);
return $branding->url($icons[192] ?? $icons['192'] ?? null) ?? $branding->faviconUrl();
}
}

View file

@ -9,5 +9,5 @@ namespace App;
*/
final class Version
{
public const VERSION = '0.24.0';
public const VERSION = '0.25.0';
}