From d8b302f8a960d5e9d027acf891fb7594a8d8e25b Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 25 Nov 2026 16:41:34 +0800 Subject: [PATCH 1/6] chore(release): open release v2.0.6 --- RELEASE.md | 21 +++++++++++++-------- composer.json | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index 6da47a30..d4f03bd1 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,15 +1,20 @@ -> v2.0.5 ~ "App Review types that share a model" +> v2.0.6 ~ "Platform token sign-in for instance apps" -# v2.0.5 — App Review types that share a model +# v2.0.6 — Platform token sign-in for instance apps + +## Added + +- **A middleware group for the routes an app calls before its user signs in: `fleetbase.api-or-platform`.** It is `fleetbase.api` that also accepts the instance's platform token (`flb_platform_…`). An app built for the whole instance, such as Navigator, has no organization until its user signs in, so it can present the platform token on these routes instead of one organization's API key. API keys and access tokens work on them as before. + - `AuthenticateApiOrPlatformToken` checks a bearer token that starts with `flb_platform_` against the platform token and answers 401 if it is wrong; it is never tried as an API key. Any other credential goes to `AuthenticateOnceWithBasicAuth` unchanged. + - A request that authenticated with the platform token has no organization and no user. `PlatformApi::authenticated($request)` tells a controller which kind it is handling. + - New helpers: `PlatformApi::isPlatformToken()`, `PlatformApi::markAuthenticated()`, `PlatformApi::TOKEN_PREFIX`. + - **The platform token ships inside apps, so treat it as public.** Only put a route in this group if it is safe for anyone to call. ## Fixed -- **A second App Review type on the same model is read and changed as itself.** `AppReview::typeOf()` returns the first registered type whose model matches. Fleet-Ops registers an organization's Navigator app on `Company`, so any other type on `Company` (such as Fleet-Ops' customer apps) was always read, changed and checked as Navigator's. - - `accessFor()`, `isEnabledFor()`, `acceptsCode()`, `update()` and `status()` take an optional `?string $type` as their last argument. Left out, it is `typeOf($subject)`, so existing callers behave as before. - - A type registered for a different model never applies: `acceptsCode()` and `isEnabledFor()` answer false, `status()` reports no type, and `update()` throws. - - New `AppReview::resolveType($subject, $type)` gives the type a subject is checked as. - - The Console endpoint (`/int/v1/review-access/{type}/{id}`) and the OAuth endpoint (`/oauth/v1/review-access/{type}/{id}`) pass the route's `{type}` through, so each type keeps its own number, code and access row. +- **Requests carrying the platform token are rate limited per client address.** The limiter keys on the presented credential, and every installed app presents the same platform token, so they all shared one bucket: one busy or hostile client could lock every user out. An API key is still one bucket wherever it is sent from. The API consumers view lists these requests as **Platform token**. +- **A use of the platform token is written down at most once every five minutes.** `PlatformApi::markUsed()` saved `last_used_at` on every request, and each save clears the system settings cache. ## Upgrade Steps -- No migration. Extensions that register more than one type on the same model must pass the type to the calls above. +- No migration. `fleetbase.platform-api` and `fleetbase.api` are unchanged. diff --git a/composer.json b/composer.json index 99d1b90a..88729671 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "fleetbase/core-api", - "version": "2.0.5", + "version": "2.0.6", "description": "Core Framework and Resources for Fleetbase API", "keywords": [ "fleetbase", From adc89a3b72a5941e16b3c73ca130c00f42b1ccb2 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 25 Nov 2026 16:41:34 +0800 Subject: [PATCH 2/6] feat(platform-api): accept the platform token on app sign-in routes Adds the fleetbase.api-or-platform middleware group: fleetbase.api that also accepts the instance's platform token, for routes an app calls before its user signs in. A request that used the token has no organization and no user; PlatformApi::authenticated() tells a controller which it is handling. Requests carrying the platform token are rate limited per client address, since every installed app presents the same token, and a use of the token is written down at most once every five minutes. --- .../AuthenticateApiOrPlatformToken.php | 45 +++++++++ src/Http/Middleware/ThrottleRequests.php | 22 +++++ src/Providers/CoreServiceProvider.php | 9 ++ src/Support/PlatformApi.php | 57 +++++++++++- tests/Unit/Http/MiddlewareContractsTest.php | 30 ++++++ .../Providers/CoreProviderContractsTest.php | 7 ++ tests/Unit/Support/PlatformApiTest.php | 91 +++++++++++++++++++ 7 files changed, 259 insertions(+), 2 deletions(-) create mode 100644 src/Http/Middleware/AuthenticateApiOrPlatformToken.php diff --git a/src/Http/Middleware/AuthenticateApiOrPlatformToken.php b/src/Http/Middleware/AuthenticateApiOrPlatformToken.php new file mode 100644 index 00000000..ea8e41ec --- /dev/null +++ b/src/Http/Middleware/AuthenticateApiOrPlatformToken.php @@ -0,0 +1,45 @@ +bearerToken(); + + if (!PlatformApi::isPlatformToken($token)) { + return app(AuthenticateOnceWithBasicAuth::class)->handle($request, $next); + } + + if (!PlatformApi::validateToken($token)) { + return response()->error('Invalid platform API token.', 401); + } + + PlatformApi::markUsed(); + PlatformApi::markAuthenticated($request); + + return $next($request); + } +} diff --git a/src/Http/Middleware/ThrottleRequests.php b/src/Http/Middleware/ThrottleRequests.php index 597e4fc5..97b0ce02 100644 --- a/src/Http/Middleware/ThrottleRequests.php +++ b/src/Http/Middleware/ThrottleRequests.php @@ -4,6 +4,7 @@ use Fleetbase\Support\ApiConsumerMetrics; use Fleetbase\Support\ApiRateLimits; +use Fleetbase\Support\PlatformApi; use Illuminate\Http\Exceptions\ThrottleRequestsException; use Illuminate\Routing\Middleware\ThrottleRequests as ThrottleRequestsMiddleware; use Illuminate\Support\Facades\Log; @@ -119,6 +120,10 @@ protected function recordConsumer($request, array $settings, ?int $limit, ?array */ protected function describeConsumer($request): array { + if ($this->presentsPlatformToken($request)) { + return ['type' => 'platform', 'label' => 'Platform token', 'detail' => $request->ip(), 'company_uuid' => null]; + } + if ($credential = $this->extractApiKey($request)) { return ApiRateLimits::identify($credential); } @@ -156,6 +161,13 @@ protected function resolveRequestSignature($request) { $scope = 'fleetbase-throttle|' . ($request->segment(1) ?? ''); + // Every installed app presents the same platform token, so the token alone would + // put them all in one bucket: one busy or hostile client would lock every user + // out of signing in. Each address gets its own. + if ($this->presentsPlatformToken($request)) { + return sha1($scope . '|platform|' . $request->ip()); + } + if ($credential = $this->extractApiKey($request)) { return sha1($scope . '|credential|' . $credential); } @@ -167,6 +179,16 @@ protected function resolveRequestSignature($request) return sha1($scope . '|ip|' . $request->ip()); } + /** + * Whether the request carries a platform token (valid or not) as its bearer token. + * + * @param \Illuminate\Http\Request $request + */ + protected function presentsPlatformToken($request): bool + { + return PlatformApi::isPlatformToken($request->bearerToken()); + } + /** * Extract API key from the request. * diff --git a/src/Providers/CoreServiceProvider.php b/src/Providers/CoreServiceProvider.php index 34d6cdfd..5918b866 100644 --- a/src/Providers/CoreServiceProvider.php +++ b/src/Providers/CoreServiceProvider.php @@ -75,6 +75,15 @@ class CoreServiceProvider extends ServiceProvider \Fleetbase\Http\Middleware\AuthenticatePlatformApiToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], + // "fleetbase.api" that also accepts the platform token: for the routes an app + // calls before its user has signed in. + 'fleetbase.api-or-platform' => [ + \Fleetbase\Http\Middleware\ThrottleRequests::class, + \Illuminate\Session\Middleware\StartSession::class, + \Fleetbase\Http\Middleware\AuthenticateApiOrPlatformToken::class, + \Illuminate\Routing\Middleware\SubstituteBindings::class, + \Fleetbase\Http\Middleware\LogApiRequests::class, + ], ]; /** diff --git a/src/Support/PlatformApi.php b/src/Support/PlatformApi.php index 0ebd14cd..2038c20d 100644 --- a/src/Support/PlatformApi.php +++ b/src/Support/PlatformApi.php @@ -3,6 +3,7 @@ namespace Fleetbase\Support; use Fleetbase\Models\Setting; +use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; @@ -12,10 +13,20 @@ class PlatformApi public const TOKEN_HASH_KEY = 'platform_api.token_hash'; public const TOKEN_ROTATED_AT_KEY = 'platform_api.token_rotated_at'; public const TOKEN_LAST_USED_KEY = 'platform_api.token_last_used_at'; + public const TOKEN_PREFIX = 'flb_platform_'; + + /** + * How often, in seconds, a use of the token is written down. Every app signed in + * through the token presents it, and each write clears the system settings cache. + */ + public const USED_WRITE_INTERVAL = 300; + + /** Request attribute set once a request has authenticated with the platform token. */ + public const REQUEST_ATTRIBUTE = 'fleetbase.platform_api'; public static function generateToken(): string { - return 'flb_platform_' . Str::random(64); + return static::TOKEN_PREFIX . Str::random(64); } public static function rotateToken(): string @@ -49,9 +60,51 @@ public static function validateToken(?string $token): bool return is_string($token) && $token !== '' && is_string($hash) && $hash !== '' && Hash::check($token, $hash); } + /** + * Whether a credential is shaped like a platform token, valid or not. + */ + public static function isPlatformToken(?string $token): bool + { + return is_string($token) && Str::startsWith($token, static::TOKEN_PREFIX); + } + + /** + * Whether the request authenticated with the platform token rather than an + * organization's API credential or a user's access token. Such a request has no + * organization and no user. + */ + public static function authenticated(?Request $request = null): bool + { + $request ??= request(); + + return $request instanceof Request && $request->attributes->get(static::REQUEST_ATTRIBUTE) === true; + } + + public static function markAuthenticated(Request $request): void + { + $request->attributes->set(static::REQUEST_ATTRIBUTE, true); + } + + /** + * Records that the token was used, at most once per USED_WRITE_INTERVAL. + */ public static function markUsed(): void { - Setting::configureSystem(static::TOKEN_LAST_USED_KEY, Carbon::now()->toISOString()); + $now = Carbon::now(); + $lastUsed = Setting::system(static::TOKEN_LAST_USED_KEY); + + if (is_string($lastUsed) && $lastUsed !== '') { + try { + $elapsed = $now->getTimestamp() - Carbon::parse($lastUsed)->getTimestamp(); + if ($elapsed >= 0 && $elapsed < static::USED_WRITE_INTERVAL) { + return; + } + } catch (\Throwable $e) { + // An unreadable timestamp is replaced below. + } + } + + Setting::configureSystem(static::TOKEN_LAST_USED_KEY, $now->toISOString()); } public static function status(): array diff --git a/tests/Unit/Http/MiddlewareContractsTest.php b/tests/Unit/Http/MiddlewareContractsTest.php index 5da56557..36c61769 100644 --- a/tests/Unit/Http/MiddlewareContractsTest.php +++ b/tests/Unit/Http/MiddlewareContractsTest.php @@ -1144,6 +1144,36 @@ public function info(string $message, array $context = []): void ->not->toBe($signature->invoke($middleware, $request(null, '10.0.0.6'))); }); + test('throttle requests gives each address presenting the platform token its own bucket', function () { + middleware_contracts_fixture([ + 'api.throttle.enabled' => true, + 'api.throttle.max_attempts' => 1, + 'api.throttle.unlimited_keys' => [], + ]); + + $middleware = middleware_contracts_throttle(); + $signature = new ReflectionMethod($middleware, 'resolveRequestSignature'); + $signature->setAccessible(true); + $describe = new ReflectionMethod($middleware, 'describeConsumer'); + $describe->setAccessible(true); + $request = function (string $bearer, string $ip) { + $request = Request::create('/v1/drivers/login', 'POST', [], [], [], ['REMOTE_ADDR' => $ip]); + $request->headers->set('Authorization', 'Bearer ' . $bearer); + + return $request; + }; + + // Every installed app sends the same token: the address tells them apart. + expect($signature->invoke($middleware, $request('flb_platform_shared', '10.0.0.5'))) + ->toBe($signature->invoke($middleware, $request('flb_platform_shared', '10.0.0.5'))) + ->not->toBe($signature->invoke($middleware, $request('flb_platform_shared', '10.0.0.6'))) + // An API key is still one bucket wherever it is sent from. + ->and($signature->invoke($middleware, $request('flb_live_key', '10.0.0.5'))) + ->toBe($signature->invoke($middleware, $request('flb_live_key', '10.0.0.6'))) + ->and($describe->invoke($middleware, $request('flb_platform_shared', '10.0.0.5'))) + ->toBe(['type' => 'platform', 'label' => 'Platform token', 'detail' => '10.0.0.5', 'company_uuid' => null]); + }); + test('basic auth middleware rejects requests without bearer credentials before continuing', function () { middleware_contracts_fixture(); diff --git a/tests/Unit/Providers/CoreProviderContractsTest.php b/tests/Unit/Providers/CoreProviderContractsTest.php index 30726a96..236adb01 100644 --- a/tests/Unit/Providers/CoreProviderContractsTest.php +++ b/tests/Unit/Providers/CoreProviderContractsTest.php @@ -602,6 +602,13 @@ function core_provider_database(CoreProviderContractsApplicationFake $container) ) ->and($provider->middleware['fleetbase.api'])->toContain(LogApiRequests::class) ->and($provider->middleware['fleetbase.platform-api'])->toContain(AuthenticatePlatformApiToken::class) + ->and($provider->middleware['fleetbase.api-or-platform'])->toBe([ + Fleetbase\Http\Middleware\ThrottleRequests::class, + Illuminate\Session\Middleware\StartSession::class, + Fleetbase\Http\Middleware\AuthenticateApiOrPlatformToken::class, + Illuminate\Routing\Middleware\SubstituteBindings::class, + LogApiRequests::class, + ]) ->and($provider->commands)->toContain( Fleetbase\Console\Commands\Recovery::class, Fleetbase\Console\Commands\ForceResetDatabase::class, diff --git a/tests/Unit/Support/PlatformApiTest.php b/tests/Unit/Support/PlatformApiTest.php index 8a12a575..1da904ff 100644 --- a/tests/Unit/Support/PlatformApiTest.php +++ b/tests/Unit/Support/PlatformApiTest.php @@ -1,5 +1,7 @@ toBe('2026-07-17T12:00:00.000000Z'); + + // Within the interval nothing is written, so the settings cache is left alone. + $cache->forgotten = []; + Carbon::setTestNow(Carbon::parse('2026-07-17 12:04:59')); + PlatformApi::markUsed(); + expect(PlatformApi::status()['last_used_at'])->toBe('2026-07-17T12:00:00.000000Z') + ->and($cache->forgotten)->toBe([]); + + Carbon::setTestNow(Carbon::parse('2026-07-17 12:05:00')); + PlatformApi::markUsed(); + expect(PlatformApi::status()['last_used_at'])->toBe('2026-07-17T12:05:00.000000Z'); + + Carbon::setTestNow(); +}); + +test('platform api recognises its own tokens and the requests they authenticated', function () { + platform_api_fixture(); + $request = Request::create('/v1/drivers/login', 'POST'); + + expect(PlatformApi::isPlatformToken(PlatformApi::generateToken()))->toBeTrue() + ->and(PlatformApi::isPlatformToken('flb_platform_'))->toBeTrue() + ->and(PlatformApi::isPlatformToken('flb_live_abc'))->toBeFalse() + ->and(PlatformApi::isPlatformToken('12|plaintext'))->toBeFalse() + ->and(PlatformApi::isPlatformToken(null))->toBeFalse() + ->and(PlatformApi::authenticated($request))->toBeFalse(); + + PlatformApi::markAuthenticated($request); + + expect(PlatformApi::authenticated($request))->toBeTrue() + ->and(PlatformApi::authenticated(Request::create('/v1/drivers/login', 'POST')))->toBeFalse(); +}); + +test('api or platform middleware accepts the platform token and hands every other credential to api authentication', function () { + platform_api_fixture(); + Carbon::setTestNow(Carbon::parse('2026-07-17 13:00:00')); + $token = PlatformApi::rotateToken(); + $middleware = new AuthenticateApiOrPlatformToken(); + $send = function (?string $bearer) use ($middleware) { + $request = Request::create('/v1/drivers/login', 'POST'); + if ($bearer !== null) { + $request->headers->set('Authorization', 'Bearer ' . $bearer); + } + + return [$middleware->handle($request, fn () => new JsonResponse(['ok' => true])), $request]; + }; + + // Everything that isn't a platform token is the API middleware's to judge. + $delegated = []; + app()->instance(AuthenticateOnceWithBasicAuth::class, new class($delegated) { + public function __construct(private array &$seen) + { + } + + public function handle($request, Closure $next) + { + $this->seen[] = $request->bearerToken(); + + return new JsonResponse(['delegated' => true]); + } + }); + + [$valid, $validRequest] = $send($token); + expect($valid->getData(true))->toBe(['ok' => true]) + ->and(PlatformApi::authenticated($validRequest))->toBeTrue() + ->and(PlatformApi::status()['last_used_at'])->toBe('2026-07-17T13:00:00.000000Z'); + + // A platform-shaped token that is wrong is refused here, never tried as an API key. + [$wrong, $wrongRequest] = $send('flb_platform_wrong'); + expect($wrong->getStatusCode())->toBe(401) + ->and($wrong->getData(true)['errors'])->toBe(['Invalid platform API token.']) + ->and(PlatformApi::authenticated($wrongRequest))->toBeFalse(); + + [$apiKey, $apiKeyRequest] = $send('flb_live_key'); + [$none] = $send(null); + expect($apiKey->getData(true))->toBe(['delegated' => true]) + ->and($none->getData(true))->toBe(['delegated' => true]) + ->and(PlatformApi::authenticated($apiKeyRequest))->toBeFalse() + ->and($delegated)->toBe(['flb_live_key', null]); + + Carbon::setTestNow(); +}); From 14ff0fbb82c66d5f98277b50cd47de66098694e3 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 25 Nov 2026 19:35:44 +0800 Subject: [PATCH 3/6] Keep the platform token retrievable for linking apps The token is stored encrypted next to its hash when it is rotated, and PlatformApi::token() returns it while it is the one in force. FleetOps uses it to build the Navigator link and QR code, so linking no longer hands an organization's API key to the app. A token rotated before this change is not retrievable until it is rotated again; status() reports which. --- src/Support/PlatformApi.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Support/PlatformApi.php b/src/Support/PlatformApi.php index 2038c20d..c50e1f99 100644 --- a/src/Support/PlatformApi.php +++ b/src/Support/PlatformApi.php @@ -5,6 +5,7 @@ use Fleetbase\Models\Setting; use Illuminate\Http\Request; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; @@ -13,6 +14,7 @@ class PlatformApi public const TOKEN_HASH_KEY = 'platform_api.token_hash'; public const TOKEN_ROTATED_AT_KEY = 'platform_api.token_rotated_at'; public const TOKEN_LAST_USED_KEY = 'platform_api.token_last_used_at'; + public const TOKEN_ENCRYPTED_KEY = 'platform_api.token_encrypted'; public const TOKEN_PREFIX = 'flb_platform_'; /** @@ -35,6 +37,10 @@ public static function rotateToken(): string $now = Carbon::now()->toISOString(); Setting::configureSystem(static::TOKEN_HASH_KEY, Hash::make($token)); + // Kept encrypted as well, so the instance can hand the token to an app it is + // linking (see token()). The token only opens the sign-in routes and already + // ships inside every app built for the instance. + Setting::configureSystem(static::TOKEN_ENCRYPTED_KEY, Crypt::encryptString($token)); Setting::configureSystem(static::TOKEN_ROTATED_AT_KEY, $now); Setting::configureSystem(static::TOKEN_LAST_USED_KEY, null); @@ -44,10 +50,33 @@ public static function rotateToken(): string public static function revokeToken(): void { Setting::configureSystem(static::TOKEN_HASH_KEY, null); + Setting::configureSystem(static::TOKEN_ENCRYPTED_KEY, null); Setting::configureSystem(static::TOKEN_ROTATED_AT_KEY, null); Setting::configureSystem(static::TOKEN_LAST_USED_KEY, null); } + /** + * The current token in plain text, for handing to an app that is being linked to + * this instance. Null when no token is configured, or when the current one was + * issued before tokens were kept retrievable: rotating it once makes it so. + */ + public static function token(): ?string + { + $encrypted = Setting::system(static::TOKEN_ENCRYPTED_KEY); + if (!is_string($encrypted) || $encrypted === '') { + return null; + } + + try { + $token = Crypt::decryptString($encrypted); + } catch (\Throwable $e) { + return null; + } + + // Only ever the token that is in force: a copy left behind by an older one is not returned. + return static::validateToken($token) ? $token : null; + } + public static function isConfigured(): bool { return is_string(static::tokenHash()) && static::tokenHash() !== ''; @@ -111,6 +140,7 @@ public static function status(): array { return [ 'configured' => static::isConfigured(), + 'retrievable' => static::token() !== null, 'rotated_at' => Setting::system(static::TOKEN_ROTATED_AT_KEY), 'last_used_at' => Setting::system(static::TOKEN_LAST_USED_KEY), ]; From 1d030a418497d7a0e7526032b9cc5a33893d81b0 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 25 Nov 2026 22:05:16 +0800 Subject: [PATCH 4/6] Chat API: only participants act on a channel, closed chats refuse posts, list feeds are capped - A user finds, posts to, reads and changes only channels they take part in; renaming and deleting a channel is for its creator; removing someone else is for the creator, leaving is for anyone - A message is sent and marked read only as the caller's own participant in that channel, and deleted only by its author - Posting into a chat closed with its order is refused - Participants named on create must belong to the caller's company - The list call returns each channel's latest 30 feed entries with feed_truncated; the find call takes limit and before to page older messages - Requests made with the organization's own key keep their wider reach --- .../Api/v1/ChatChannelController.php | 222 +++++++++++++- src/Http/Resources/ChatChannel.php | 2 + src/Models/ChatChannel.php | 107 ++++++- tests/Unit/Http/ChatChannelControllerTest.php | 271 +++++++++++++++++- 4 files changed, 582 insertions(+), 20 deletions(-) diff --git a/src/Http/Controllers/Api/v1/ChatChannelController.php b/src/Http/Controllers/Api/v1/ChatChannelController.php index b116c2ba..a10700a8 100644 --- a/src/Http/Controllers/Api/v1/ChatChannelController.php +++ b/src/Http/Controllers/Api/v1/ChatChannelController.php @@ -19,6 +19,7 @@ use Fleetbase\Models\File; use Fleetbase\Models\User; use Illuminate\Http\Request; +use Illuminate\Support\Carbon; class ChatChannelController extends Controller { @@ -42,7 +43,15 @@ public function create(CreateChatChannelRequest $request) // If participants provided add them foreach ($participants as $userId) { - $user = User::where('public_id', $userId)->first(); + // Only people of this organisation: a public id from another one must not pull + // its user into the channel, where they would be sent every message. + $user = User::where('public_id', $userId) + ->where(function ($query) { + $query->where('company_uuid', session('company'))->orWhereHas('companyUsers', function ($query) { + $query->where('company_uuid', session('company')); + }); + }) + ->first(); if ($user) { ChatParticipant::create([ 'company_uuid' => session('company'), @@ -67,7 +76,7 @@ public function update($id, UpdateChatChannelRequest $request) { // find for the chat channel try { - $chatChannel = ChatChannel::findRecordOrFail($id); + $chatChannel = $this->findChannelForCaller($id); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return response()->json( [ @@ -77,6 +86,11 @@ public function update($id, UpdateChatChannelRequest $request) ); } + // Renaming is for whoever created the channel + if (!$this->callerCreatedChannel($chatChannel)) { + return response()->apiError('Only the creator of this chat channel can change it.', 403); + } + // get request input $input = $request->only(['name']); @@ -96,19 +110,29 @@ public function query(Request $request) { $results = ChatChannel::queryWithRequest($request); + // Each channel carries only its latest entries; the rest is fetched per channel with + // `GET chat-channels/{id}`, which says so through `feed_truncated`. + foreach ($results as $chatChannel) { + $chatChannel->limitFeed(ChatChannel::LIST_FEED_LIMIT); + } + return ChatChannelResource::collection($results); } /** * Finds a single Fleetbase Chat Channel resources. * + * The whole feed comes back unless the request pages it: `limit` keeps the most recent + * entries (up to ChatChannel::MAX_FEED_LIMIT), and `before` (a chat message id or a time) + * keeps only what is older, for loading earlier history a page at a time. + * * @return \Fleetbase\Http\Resources\ChatChannelCollection */ - public function find($id) + public function find($id, Request $request) { // find for the chat channel try { - $chatChannel = ChatChannel::findRecordOrFail($id); + $chatChannel = $this->findChannelForCaller($id); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return response()->json( [ @@ -118,6 +142,19 @@ public function find($id) ); } + // Page the feed when asked to + if ($request->filled('limit') || $request->filled('before')) { + $before = null; + if ($request->filled('before')) { + $before = $this->feedCursor($chatChannel, (string) $request->input('before')); + if (!$before) { + return response()->apiError('The `before` value must be a message id from this chat channel or a valid time.', 422); + } + } + + $chatChannel->limitFeed((int) $request->input('limit', ChatChannel::LIST_FEED_LIMIT), $before); + } + // response the chat channel resource return new ChatChannelResource($chatChannel); } @@ -131,7 +168,7 @@ public function delete($id) { // find for the chat channel try { - $chatChannel = ChatChannel::findRecordOrFail($id); + $chatChannel = $this->findChannelForCaller($id); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return response()->json( [ @@ -141,6 +178,11 @@ public function delete($id) ); } + // Deleting is for whoever created the channel + if (!$this->callerCreatedChannel($chatChannel)) { + return response()->apiError('Only the creator of this chat channel can delete it.', 403); + } + // delete the chat channel $chatChannel->delete(); @@ -156,7 +198,15 @@ public function delete($id) public function getAvailablePartificants(Request $request) { $chatChannelId = $request->input('channel'); - $chatChannel = $chatChannelId ? ChatChannel::where('public_id', $chatChannelId)->first() : null; + $chatChannel = null; + if ($chatChannelId) { + // A channel the caller cannot see filters nothing, the same as no channel + try { + $chatChannel = $this->findChannelForCaller($chatChannelId); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { + $chatChannel = null; + } + } $users = User::where('company_uuid', session('company'))->get(); if ($chatChannel) { @@ -181,7 +231,7 @@ public function addParticipant($id, Request $request) // find for the chat channel try { - $chatChannel = ChatChannel::findRecordOrFail($id); + $chatChannel = $this->findChannelForCaller($id); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return response()->json( [ @@ -232,6 +282,27 @@ public function removeParticipant($participantId) ); } + $callerUserUuid = $this->callerUserUuid(); + if ($callerUserUuid !== null) { + // A participant of a channel the caller is not in is answered as not found + $chatChannel = $this->callerParticipatesIn($chatParticipant->chat_channel_uuid) + ? ChatChannel::where('uuid', $chatParticipant->chat_channel_uuid)->first() + : null; + if (!$chatChannel) { + return response()->json( + [ + 'error' => 'Chat participant resource not found.', + ], + 422 + ); + } + + // Anyone may leave; removing someone else is for whoever created the channel + if ($chatParticipant->user_uuid !== $callerUserUuid && $chatChannel->created_by_uuid !== $callerUserUuid) { + return response()->apiError('Only the creator of this chat channel can remove other participants.', 403); + } + } + // Delete the chat participant $chatParticipant->delete(); @@ -249,7 +320,7 @@ public function sendMessage($id, Request $request) // Find for the chat channel try { - $chatChannel = ChatChannel::findRecordOrFail($id); + $chatChannel = $this->findChannelForCaller($id); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return response()->json( [ @@ -259,9 +330,16 @@ public function sendMessage($id, Request $request) ); } - // Find for the chat participant sender + // An order's chat ends with the order: once closed it can be read but not written to + if (data_get($chatChannel, 'meta.closed_at')) { + return response()->apiError('This conversation has ended.', 422); + } + + // Find for the chat participant sender, who has to be in this channel try { - $sender = ChatParticipant::findRecordOrFail($senderId); + $sender = ChatParticipant::findRecordOrFail($senderId, [], ['*'], function ($query) use ($chatChannel) { + $query->where('chat_channel_uuid', $chatChannel->uuid); + }); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return response()->json( [ @@ -271,6 +349,12 @@ public function sendMessage($id, Request $request) ); } + // A person can only speak as themselves + $callerUserUuid = $this->callerUserUuid(); + if ($callerUserUuid !== null && $sender->user_uuid !== $callerUserUuid) { + return response()->apiError('You can only send messages as yourself.', 403); + } + // Get the message contents and attachment file id $content = $request->input('content'); $attachments = $request->inputArray('files'); @@ -329,6 +413,19 @@ public function deleteMessage($chatMessageId) return response()->apiError('Chat message resource not found.', 404); } + $callerUserUuid = $this->callerUserUuid(); + if ($callerUserUuid !== null) { + // A message in a channel the caller is not in is answered as not found + if (!$this->callerParticipatesIn($chatMessage->chat_channel_uuid)) { + return response()->apiError('Chat message resource not found.', 404); + } + + // Only the person who wrote a message can delete it + if (data_get($chatMessage, 'sender.user_uuid') !== $callerUserUuid) { + return response()->apiError('Only the author of this message can delete it.', 403); + } + } + // Delete the chat message $chatMessage->delete(); @@ -351,15 +448,27 @@ public function createReadReceipt($chatMessageId, Request $request) $chatParticipantId = $request->input('participant'); $companyUuid = session('company'); - // Load models - $chatMessage = ChatMessage::where('public_id', $chatMessageId)->first(); - $chatParticipant = ChatParticipant::where('public_id', $chatParticipantId)->first(); + // Load models, from this organisation only + $chatMessage = ChatMessage::where('public_id', $chatMessageId)->where('company_uuid', $companyUuid)->first(); + $chatParticipant = ChatParticipant::where('public_id', $chatParticipantId)->where('company_uuid', $companyUuid)->first(); // Guard clauses for invalid references if (!$chatMessage || !$chatParticipant) { return response()->apiError('Invalid message or participant reference.', 404); } + // A message in a channel the caller is not in is answered as not found, and so is a + // reader who is not in the message's channel + $callerUserUuid = $this->callerUserUuid(); + if (($callerUserUuid !== null && !$this->callerParticipatesIn($chatMessage->chat_channel_uuid)) || $chatParticipant->chat_channel_uuid !== $chatMessage->chat_channel_uuid) { + return response()->apiError('Invalid message or participant reference.', 404); + } + + // A person can only mark messages read for themselves + if ($callerUserUuid !== null && $chatParticipant->user_uuid !== $callerUserUuid) { + return response()->apiError('You can only mark messages as read for yourself.', 403); + } + // Check for existing receipt $existingChatReceipt = ChatReceipt::where('company_uuid', $companyUuid) ->where('chat_message_uuid', $chatMessage->uuid) @@ -385,4 +494,91 @@ public function createReadReceipt($chatMessageId, Request $request) return response()->apiError($message); } } + + /** + * The user making the request with their own token, or null when it was made with the + * organisation's API key. + * + * Both kinds of request have a session user (a key runs as the user who created it), so + * the token is what tells them apart: an organisation key is the one credential whose key + * or secret is the bearer token itself. A personal token, such as the one a driver or + * customer signs in with, never is, and so is held to that person's own channels. A + * request that cannot be shown to come from an organisation key is treated as a person's. + */ + protected function callerUserUuid(): ?string + { + $token = request()->bearerToken(); + if (is_string($token) && $token !== '') { + foreach ([session('api_key'), session('api_secret')] as $credential) { + if (is_string($credential) && $credential !== '' && hash_equals($credential, $token)) { + return null; + } + } + } + + return (string) session('user'); + } + + /** + * Whether the calling user is a participant of the channel. Always true for a request + * made with the organisation's API key. + */ + protected function callerParticipatesIn(?string $chatChannelUuid): bool + { + $callerUserUuid = $this->callerUserUuid(); + if ($callerUserUuid === null) { + return true; + } + + return ChatParticipant::where(['chat_channel_uuid' => $chatChannelUuid, 'user_uuid' => $callerUserUuid])->exists(); + } + + /** + * Whether the caller may rename or delete the channel: the user who created it, or the + * organisation's API key. + */ + protected function callerCreatedChannel(ChatChannel $chatChannel): bool + { + $callerUserUuid = $this->callerUserUuid(); + + return $callerUserUuid === null || $chatChannel->created_by_uuid === $callerUserUuid; + } + + /** + * Finds a chat channel of this organisation by its public id, as the caller sees it: a + * user only finds the channels they participate in, so every other channel is not found. + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException + */ + protected function findChannelForCaller($id): ChatChannel + { + $callerUserUuid = $this->callerUserUuid(); + + return ChatChannel::findRecordOrFail($id, [], ['*'], function ($query) use ($callerUserUuid) { + if ($callerUserUuid !== null) { + $query->whereHas('participants', function ($query) use ($callerUserUuid) { + $query->where('user_uuid', $callerUserUuid); + }); + } + }); + } + + /** + * The time a `before` value points at: when the message with that id in this channel was + * sent, or the time itself. Null when it is neither. + */ + protected function feedCursor(ChatChannel $chatChannel, string $before): ?Carbon + { + $chatMessage = ChatMessage::where(['public_id' => $before, 'chat_channel_uuid' => $chatChannel->uuid])->first(); + if ($chatMessage) { + return $chatMessage->created_at; + } + + try { + // Stored timestamps are in the application's timezone + return Carbon::parse($before)->setTimezone(date_default_timezone_get()); + } catch (\Throwable $exception) { + return null; + } + } } diff --git a/src/Http/Resources/ChatChannel.php b/src/Http/Resources/ChatChannel.php index 055ddf5d..51a6c648 100644 --- a/src/Http/Resources/ChatChannel.php +++ b/src/Http/Resources/ChatChannel.php @@ -32,6 +32,8 @@ public function toArray($request) 'unread_count' => $this->when($user, fn () => $this->getUnreadMessageCountForUser($user)), 'slug' => $this->slug, 'feed' => $this->resource_feed, + // Read after `feed`, which is what works it out. True when older entries were left out. + 'feed_truncated' => $this->when(Http::isPublicRequest(), fn () => method_exists($this->resource, 'feedWasTruncated') && $this->resource->feedWasTruncated()), 'participants' => ChatParticipant::collection($this->participants), 'meta' => data_get($this, 'meta', Utils::createObject()), 'updated_at' => $this->updated_at, diff --git a/src/Models/ChatChannel.php b/src/Models/ChatChannel.php index a64945ee..fa7465b1 100644 --- a/src/Models/ChatChannel.php +++ b/src/Models/ChatChannel.php @@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasOne; +use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Spatie\Sluggable\HasSlug; use Spatie\Sluggable\SlugOptions; @@ -80,6 +81,32 @@ class ChatChannel extends Model 'meta' => Json::class, ]; + /** + * How many feed entries the public list call embeds in each channel. A list of fifty + * channels used to carry every message ever sent in all of them. + */ + public const LIST_FEED_LIMIT = 30; + + /** + * The most feed entries one request may ask for. + */ + public const MAX_FEED_LIMIT = 100; + + /** + * The window `resource_feed` is cut to, set with `limitFeed()`. Null means the whole feed. + */ + protected ?int $feedLimit = null; + + /** + * Only entries older than this are in the feed. Null means up to now. + */ + protected ?Carbon $feedBefore = null; + + /** + * Whether the last feed built left older entries out. + */ + protected bool $feedTruncated = false; + /** * @var SlugOptions */ @@ -283,23 +310,27 @@ public function getFeedAttribute(): Collection * transforms them into their respective HTTP resources, and returns them as a unified feed. * Each item in the feed is an array containing the type (message, attachment, log), * the corresponding HTTP resource, and the creation timestamp. The feed is sorted in - * descending order of creation time, ensuring the most recent activities are listed first. + * ascending order of creation time, so the most recent activities are listed last. * This method is particularly useful for generating standardized API responses * that encapsulate the diverse activities within a chat channel. * + * The whole feed unless `limitFeed()` was called first. + * * @return Collection the aggregated and resource-formatted feed of chat activities */ public function getResourceFeedAttribute(): Collection { - $messages = $this->messages()->get()->map(function ($message) { + $records = $this->feedRecords(); + + $messages = $records['messages']->map(function ($message) { return ['type' => 'message', 'data' => new ChatMessageResource($message), 'created_at' => $message->created_at]; }); - $attachments = $this->attachments()->get()->map(function ($attachment) { + $attachments = $records['attachments']->map(function ($attachment) { return ['type' => 'attachment', 'data' => new ChatAttachmentResource($attachment), 'created_at' => $attachment->created_at]; }); - $logs = $this->logs()->get()->map(function ($log) { + $logs = $records['logs']->map(function ($log) { return ['type' => 'log', 'data' => new ChatLogResource($log), 'created_at' => $log->created_at]; }); @@ -307,4 +338,72 @@ public function getResourceFeedAttribute(): Collection return $feed; } + + /** + * Cut `resource_feed` to the most recent `$limit` entries, optionally only those older than + * `$before`. Passing neither puts the whole feed back. + */ + public function limitFeed(?int $limit, ?Carbon $before = null): static + { + $this->feedLimit = $limit === null ? null : max(1, min($limit, self::MAX_FEED_LIMIT)); + $this->feedBefore = $before; + + return $this; + } + + /** + * Whether the feed last built by `resource_feed` left older entries out, so a client + * knows there is more to ask for. + */ + public function feedWasTruncated(): bool + { + return $this->feedTruncated; + } + + /** + * The messages, attachments and logs that make up the feed, inside the window set by + * `limitFeed()`. + * + * A cut never lands inside a second: timestamps are whole seconds, so entries written in + * the same second as the oldest one kept are kept too (a page can run a little over the + * limit). That is what lets a client ask for "older than the oldest entry I have" without + * losing the ones that shared its timestamp. + * + * @return array + */ + protected function feedRecords(): array + { + $relations = ['messages', 'attachments', 'logs']; + $before = $this->feedBefore; + $this->feedTruncated = false; + + $window = function (string $relation) use ($before) { + $query = $this->{$relation}(); + + return $before ? $query->where('created_at', '<', $before) : $query; + }; + + $since = null; + if ($this->feedLimit !== null) { + // Read only the timestamps first, so the cut is found without loading messages + // that will not be sent. + $timestamps = collect(); + foreach ($relations as $relation) { + $timestamps = $timestamps->concat($window($relation)->latest()->limit($this->feedLimit + 1)->pluck('created_at')); + } + + if ($timestamps->count() > $this->feedLimit) { + $this->feedTruncated = true; + $since = $timestamps->sortDesc()->values()->get($this->feedLimit - 1); + } + } + + $records = []; + foreach ($relations as $relation) { + $query = $window($relation); + $records[$relation] = ($since ? $query->where('created_at', '>=', $since) : $query)->get(); + } + + return $records; + } } diff --git a/tests/Unit/Http/ChatChannelControllerTest.php b/tests/Unit/Http/ChatChannelControllerTest.php index 162c6578..1b911594 100644 --- a/tests/Unit/Http/ChatChannelControllerTest.php +++ b/tests/Unit/Http/ChatChannelControllerTest.php @@ -545,6 +545,37 @@ function public_chat_channel_query_request(array $query = []): Request return $request; } +function public_chat_channel_find_request(array $query = []): Request +{ + return Request::create('/v1/chat-channels/chat_current', 'GET', $query); +} + +/** + * Makes the request one authenticated with the organisation's API key, run as the given user. + */ +function public_chat_channel_as_organisation_key(string $userUuid): void +{ + session(['user' => $userUuid, 'api_key' => 'flb_live_organisation']); + + $request = Request::create('/v1/chat-channels', 'GET'); + $request->headers->set('Authorization', 'Bearer flb_live_organisation'); + Container::getInstance()->instance('request', $request); +} + +function public_chat_channel_insert_message(Capsule $capsule, string $key, string $sender, string $createdAt, string $channel = 'channel-current'): void +{ + $capsule->getConnection('mysql')->table('chat_messages')->insert([ + 'uuid' => 'message-' . $key, + 'public_id' => 'message_' . $key, + 'company_uuid' => 'company-1', + 'chat_channel_uuid' => $channel, + 'sender_uuid' => $sender, + 'content' => 'Message ' . $key, + 'created_at' => $createdAt, + 'updated_at' => $createdAt, + ]); +} + function chat_channel_controller_reflect(string $method, string $id): mixed { $reflection = new ReflectionMethod(ChatChannelController::class, $method); @@ -869,7 +900,7 @@ function chat_channel_controller_reflect(string $method, string $id): mixed expect(public_chat_channel_controller_payload($response)['name'])->toBe('Public Dispatch') ->and($channel->company_uuid)->toBe('company-1') ->and($channel->created_by_uuid)->toBe('user-current') - ->and($participantUserUuids)->toBe(['user-active', 'user-current', 'user-other-company']) + ->and($participantUserUuids)->toBe(['user-active', 'user-current']) ->and($capsule->getConnection('mysql')->table('chat_channels')->where('public_id', 'chat_other')->value('company_uuid'))->toBe('company-2'); }); @@ -882,10 +913,10 @@ function chat_channel_controller_reflect(string $method, string $id): mixed $missingUpdate = public_chat_channel_controller()->update('missing_chat', public_chat_channel_update_request([ 'name' => 'Missing Channel', ])); - $found = public_chat_channel_controller()->find('chat_current'); + $found = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request()); $queried = public_chat_channel_controller()->query(public_chat_channel_query_request()); $deleted = public_chat_channel_controller()->delete('chat_current'); - $missing = public_chat_channel_controller()->find('chat_current'); + $missing = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request()); $missingDelete = public_chat_channel_controller()->delete('missing_chat'); expect(public_chat_channel_controller_payload($updated)['name'])->toBe('Renamed Channel') @@ -1062,3 +1093,237 @@ function chat_channel_controller_reflect(string $method, string $id): mixed expect($response->getStatusCode())->toBe(400) ->and($response->getData(true)['error'])->toContain('receipt insert blocked'); }); + +test('public chat channel hides channels from users who are not participants', function () { + $capsule = chat_channel_controller_database(); + public_chat_channel_insert_message($capsule, 'hidden', 'participant-current', '2026-07-18 00:30:00'); + + // A signed-in user of the same company who is not in the channel + session(['user' => 'user-extra']); + $capsule->getConnection('mysql')->table('chat_channels')->insert([ + 'uuid' => 'channel-extra', 'public_id' => 'chat_extra', 'company_uuid' => 'company-1', 'created_by_uuid' => 'user-extra', 'name' => 'Extra Channel', 'created_at' => '2026-07-18 00:00:00', 'updated_at' => '2026-07-18 00:00:00', + ]); + $capsule->getConnection('mysql')->table('chat_participants')->insert([ + 'uuid' => 'participant-extra', 'public_id' => 'participant_extra', 'company_uuid' => 'company-1', 'chat_channel_uuid' => 'channel-extra', 'user_uuid' => 'user-extra', 'created_at' => '2026-07-18 00:00:00', 'updated_at' => '2026-07-18 00:00:00', + ]); + + $found = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request()); + $queried = public_chat_channel_controller()->query(public_chat_channel_query_request()); + $updated = public_chat_channel_controller()->update('chat_current', public_chat_channel_update_request(['name' => 'Taken Over'])); + $deleted = public_chat_channel_controller()->delete('chat_current'); + $added = public_chat_channel_controller()->addParticipant('chat_current', Request::create('/v1/chat-channels/chat_current/add-participant', 'POST', ['user' => 'user_extra'])); + $removed = public_chat_channel_controller()->removeParticipant('participant_active'); + $sentAsOther = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_current', + 'content' => 'Not mine to send', + ])); + $sentAsSelf = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_extra', + 'content' => 'From another channel', + ])); + $deletedMessage = public_chat_channel_controller()->deleteMessage('message_hidden'); + $read = public_chat_channel_controller()->createReadReceipt('message_hidden', Request::create('/v1/chat-channels/read-message/message_hidden', 'POST', ['participant' => 'participant_extra'])); + $readAsOther = public_chat_channel_controller()->createReadReceipt('message_hidden', Request::create('/v1/chat-channels/read-message/message_hidden', 'POST', ['participant' => 'participant_active'])); + $available = public_chat_channel_controller()->getAvailablePartificants(Request::create('/v1/chat-channels/available-participants', 'GET', ['channel' => 'chat_current'])); + + expect($found->getStatusCode())->toBe(404) + ->and($queried->collection->pluck('public_id')->all())->toBe(['chat_extra']) + ->and($updated->getStatusCode())->toBe(404) + ->and($deleted->getStatusCode())->toBe(404) + ->and($added->getStatusCode())->toBe(404) + ->and($removed->getStatusCode())->toBe(422) + ->and($removed->getData(true))->toBe(['error' => 'Chat participant resource not found.']) + ->and($sentAsOther->getStatusCode())->toBe(404) + ->and($sentAsSelf->getStatusCode())->toBe(404) + ->and($deletedMessage->getStatusCode())->toBe(404) + ->and($read->getStatusCode())->toBe(404) + ->and($readAsOther->getStatusCode())->toBe(404) + // The channel filter is ignored, so nothing is learnt about who is in it + ->and($available->collection->pluck('uuid')->all())->toBe(['user-current', 'user-active', 'user-extra']) + ->and(ChatChannel::where('public_id', 'chat_current')->value('name'))->toBe('Current Channel') + ->and(ChatParticipant::where('public_id', 'participant_active')->exists())->toBeTrue() + ->and(ChatMessage::where('chat_channel_uuid', 'channel-current')->pluck('public_id')->all())->toBe(['message_hidden']) + ->and(ChatReceipt::query()->count())->toBe(0); +}); + +test('public chat channel keeps a participant to their own identity and leaves the rest to the creator', function () { + $capsule = chat_channel_controller_database(); + public_chat_channel_insert_message($capsule, 'creator', 'participant-current', '2026-07-18 00:30:00'); + public_chat_channel_insert_message($capsule, 'own', 'participant-active', '2026-07-18 00:31:00'); + + // A participant who did not create the channel + session(['user' => 'user-active']); + + $found = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request()); + $updated = public_chat_channel_controller()->update('chat_current', public_chat_channel_update_request(['name' => 'Renamed By Member'])); + $deleted = public_chat_channel_controller()->delete('chat_current'); + $added = public_chat_channel_controller()->addParticipant('chat_current', Request::create('/v1/chat-channels/chat_current/add-participant', 'POST', ['user' => 'user_extra'])); + $removed = public_chat_channel_controller()->removeParticipant('participant_current'); + $sentAsOther = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_current', + 'content' => 'Speaking for someone else', + ])); + $sent = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_active', + 'content' => 'Speaking for myself', + ])); + $deletedOther = public_chat_channel_controller()->deleteMessage('message_creator'); + $deletedOwn = public_chat_channel_controller()->deleteMessage('message_own'); + $readAsOther = public_chat_channel_controller()->createReadReceipt('message_creator', Request::create('/v1/chat-channels/read-message/message_creator', 'POST', ['participant' => 'participant_current'])); + $read = public_chat_channel_controller()->createReadReceipt('message_creator', Request::create('/v1/chat-channels/read-message/message_creator', 'POST', ['participant' => 'participant_active'])); + $left = public_chat_channel_controller()->removeParticipant('participant_active'); + + expect(public_chat_channel_controller_payload($found)['id'])->toBe('chat_current') + ->and($updated->getStatusCode())->toBe(403) + ->and($updated->getData(true))->toBe(['error' => 'Only the creator of this chat channel can change it.']) + ->and($deleted->getStatusCode())->toBe(403) + ->and($deleted->getData(true))->toBe(['error' => 'Only the creator of this chat channel can delete it.']) + ->and($added->resource->user_uuid)->toBe('user-extra') + ->and($removed->getStatusCode())->toBe(403) + ->and($removed->getData(true))->toBe(['error' => 'Only the creator of this chat channel can remove other participants.']) + ->and($sentAsOther->getStatusCode())->toBe(403) + ->and($sentAsOther->getData(true))->toBe(['error' => 'You can only send messages as yourself.']) + ->and($sent->resource->sender_uuid)->toBe('participant-active') + ->and($deletedOther->getStatusCode())->toBe(403) + ->and($deletedOther->getData(true))->toBe(['error' => 'Only the author of this message can delete it.']) + ->and($deletedOwn->resource->public_id)->toBe('message_own') + ->and($readAsOther->getStatusCode())->toBe(403) + ->and($readAsOther->getData(true))->toBe(['error' => 'You can only mark messages as read for yourself.']) + ->and($read->resource->participant_uuid)->toBe('participant-active') + ->and($left->resource->public_id)->toBe('participant_active') + ->and(ChatChannel::where('public_id', 'chat_current')->value('name'))->toBe('Current Channel') + ->and(ChatParticipant::where('public_id', 'participant_current')->exists())->toBeTrue() + ->and(ChatMessage::where('public_id', 'message_creator')->exists())->toBeTrue(); +}); + +test('public chat channel lets the creator remove another participant', function () { + chat_channel_controller_database(); + + $removed = public_chat_channel_controller()->removeParticipant('participant_active'); + + expect($removed->resource->public_id)->toBe('participant_active') + ->and(ChatParticipant::where('public_id', 'participant_active')->exists())->toBeFalse(); +}); + +test('public chat channel requests made with the organisation key are not held to participation', function () { + $capsule = chat_channel_controller_database(); + public_chat_channel_insert_message($capsule, 'creator', 'participant-current', '2026-07-18 00:30:00'); + + // The key runs as a user who is in none of the channels + public_chat_channel_as_organisation_key('user-extra'); + + $found = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request()); + $updated = public_chat_channel_controller()->update('chat_current', public_chat_channel_update_request(['name' => 'Renamed By Integration'])); + $sent = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_current', + 'content' => 'Sent by the integration', + ])); + $read = public_chat_channel_controller()->createReadReceipt('message_creator', Request::create('/v1/chat-channels/read-message/message_creator', 'POST', ['participant' => 'participant_active'])); + $deletedMessage = public_chat_channel_controller()->deleteMessage('message_creator'); + $removed = public_chat_channel_controller()->removeParticipant('participant_active'); + $otherCompany = public_chat_channel_controller()->find('chat_other', public_chat_channel_find_request()); + $deleted = public_chat_channel_controller()->delete('chat_current'); + + expect(public_chat_channel_controller_payload($found)['id'])->toBe('chat_current') + ->and(public_chat_channel_controller_payload($updated)['name'])->toBe('Renamed By Integration') + ->and($sent->resource->sender_uuid)->toBe('participant-current') + ->and($read->resource->participant_uuid)->toBe('participant-active') + ->and($deletedMessage->resource->public_id)->toBe('message_creator') + ->and($removed->resource->public_id)->toBe('participant_active') + ->and($otherCompany->getStatusCode())->toBe(404) + ->and($deleted->resource->public_id)->toBe('chat_current'); +}); + +test('public chat channel does not treat a personal token as the organisation key', function () { + chat_channel_controller_database(); + + // The session holds the company's key, as it does for a driver's token, but the token sent is not that key + session(['user' => 'user-extra', 'api_key' => 'flb_live_organisation']); + $request = Request::create('/v1/chat-channels/chat_current', 'GET'); + $request->headers->set('Authorization', 'Bearer 12|personal-token'); + Container::getInstance()->instance('request', $request); + + expect(public_chat_channel_controller()->find('chat_current', $request)->getStatusCode())->toBe(404); +}); + +test('public chat channel refuses senders and readers from another channel', function () { + $capsule = chat_channel_controller_database(); + $now = '2026-07-18 00:00:00'; + $capsule->getConnection('mysql')->table('chat_channels')->insert([ + 'uuid' => 'channel-second', 'public_id' => 'chat_second', 'company_uuid' => 'company-1', 'created_by_uuid' => 'user-current', 'name' => 'Second Channel', 'created_at' => $now, 'updated_at' => $now, + ]); + $capsule->getConnection('mysql')->table('chat_participants')->insert([ + 'uuid' => 'participant-second', 'public_id' => 'participant_second', 'company_uuid' => 'company-1', 'chat_channel_uuid' => 'channel-second', 'user_uuid' => 'user-current', 'created_at' => $now, 'updated_at' => $now, + ]); + public_chat_channel_insert_message($capsule, 'first', 'participant-active', '2026-07-18 00:30:00'); + + $sent = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_second', + 'content' => 'Wrong room', + ])); + $read = public_chat_channel_controller()->createReadReceipt('message_first', Request::create('/v1/chat-channels/read-message/message_first', 'POST', ['participant' => 'participant_second'])); + + expect($sent->getStatusCode())->toBe(422) + ->and($sent->getData(true))->toBe(['error' => 'Sender of chat message not found.']) + ->and($read->getStatusCode())->toBe(404) + ->and($read->getData(true))->toBe(['error' => 'Invalid message or participant reference.']) + ->and(ChatMessage::where('content', 'Wrong room')->exists())->toBeFalse() + ->and(ChatReceipt::query()->count())->toBe(0); +}); + +test('public chat channel refuses messages into a closed conversation', function () { + $capsule = chat_channel_controller_database(); + $capsule->getConnection('mysql')->table('chat_channels')->where('uuid', 'channel-current')->update([ + 'meta' => json_encode(['closed_at' => '2026-07-18T01:00:00.000000Z']), + ]); + + $sent = public_chat_channel_controller()->sendMessage('chat_current', Request::create('/v1/chat-channels/chat_current/send-message', 'POST', [ + 'sender' => 'participant_current', + 'content' => 'Too late', + ])); + $found = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request()); + + expect($sent->getStatusCode())->toBe(422) + ->and($sent->getData(true))->toBe(['error' => 'This conversation has ended.']) + ->and(ChatMessage::where('content', 'Too late')->exists())->toBeFalse() + // It can still be read + ->and(public_chat_channel_controller_payload($found)['id'])->toBe('chat_current'); +}); + +test('public chat channel list caps each feed and find pages through the rest', function () { + $capsule = chat_channel_controller_database(); + // Resources tell a public request from the route of the current request + Container::getInstance()->instance('request', public_chat_channel_query_request()); + + // 35 messages a minute apart, then two more sharing the oldest minute + for ($i = 1; $i <= 35; $i++) { + public_chat_channel_insert_message($capsule, sprintf('%02d', $i), 'participant-active', sprintf('2026-07-18 01:%02d:00', $i)); + } + public_chat_channel_insert_message($capsule, 'tie-a', 'participant-active', '2026-07-18 01:06:00'); + public_chat_channel_insert_message($capsule, 'tie-b', 'participant-active', '2026-07-18 01:06:00'); + + $ids = fn (array $payload) => collect($payload['feed'])->map(fn ($entry) => $entry['data']->resource->public_id)->all(); + + $listed = public_chat_channel_controller()->query(public_chat_channel_query_request()); + $channel = public_chat_channel_controller_payload($listed->collection->first()); + $whole = public_chat_channel_controller_payload(public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request())); + $recent = public_chat_channel_controller_payload(public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request(['limit' => 5]))); + $older = public_chat_channel_controller_payload(public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request(['limit' => 5, 'before' => 'message_31']))); + $oldest = public_chat_channel_controller_payload(public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request(['before' => '2026-07-18T01:07:00Z']))); + $invalid = public_chat_channel_controller()->find('chat_current', public_chat_channel_find_request(['before' => 'not a time'])); + + // The cut falls on 01:06, so all three messages of that minute are kept + expect($channel['feed_truncated'])->toBeTrue() + ->and($ids($channel))->toHaveCount(32) + ->and($ids($channel)[31])->toBe('message_35') + ->and(array_slice($ids($channel), 0, 3))->toEqualCanonicalizing(['message_06', 'message_tie-a', 'message_tie-b']) + ->and($whole['feed_truncated'])->toBeFalse() + ->and($ids($whole))->toHaveCount(37) + ->and($recent['feed_truncated'])->toBeTrue() + ->and($ids($recent))->toBe(['message_31', 'message_32', 'message_33', 'message_34', 'message_35']) + ->and($older['feed_truncated'])->toBeTrue() + ->and($ids($older))->toBe(['message_26', 'message_27', 'message_28', 'message_29', 'message_30']) + ->and($oldest['feed_truncated'])->toBeFalse() + ->and($ids($oldest))->toHaveCount(8) + ->and($invalid->getStatusCode())->toBe(422); +}); From 3c34b89e44735836fe378f333791dcb5ae353079 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 27 Nov 2026 12:43:46 +0800 Subject: [PATCH 5/6] Notification preferences: a person can switch off kinds of push, kept on the user; chat messages honour it --- src/Notifications/ChatMessageReceived.php | 2 +- src/Support/NotificationPreferences.php | 102 ++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 src/Support/NotificationPreferences.php diff --git a/src/Notifications/ChatMessageReceived.php b/src/Notifications/ChatMessageReceived.php index 1c07a7c8..46188c90 100644 --- a/src/Notifications/ChatMessageReceived.php +++ b/src/Notifications/ChatMessageReceived.php @@ -96,7 +96,7 @@ public function __construct(ChatMessage $chatMessage, ChatParticipant $chatRecip */ public function via($notifiable) { - return ['broadcast', FcmChannel::class, ApnChannel::class]; + return \Fleetbase\Support\NotificationPreferences::channels($notifiable, 'messages', ['broadcast', FcmChannel::class, ApnChannel::class]); } /** diff --git a/src/Support/NotificationPreferences.php b/src/Support/NotificationPreferences.php new file mode 100644 index 00000000..2190006c --- /dev/null +++ b/src/Support/NotificationPreferences.php @@ -0,0 +1,102 @@ +user_uuid)) { + $user = method_exists($notifiable, 'relationLoaded') && $notifiable->relationLoaded('user') ? $notifiable->user : null; + + return $user instanceof User ? $user : User::where('uuid', $notifiable->user_uuid)->first(); + } + + return null; + } + + /** + * Every category with the person's answer. + * + * @return array + */ + public static function for(?User $user): array + { + $stored = $user ? (array) data_get($user->meta, static::META_KEY, []) : []; + $out = []; + foreach (static::CATEGORIES as $category) { + $out[$category] = array_key_exists($category, $stored) ? (bool) $stored[$category] : true; + } + + return $out; + } + + /** + * Saves the categories given and leaves the rest as they were. + * + * @return array + */ + public static function update(User $user, array $changes): array + { + $preferences = static::for($user); + foreach (static::CATEGORIES as $category) { + if (array_key_exists($category, $changes)) { + $preferences[$category] = filter_var($changes[$category], FILTER_VALIDATE_BOOLEAN); + } + } + + $meta = (array) $user->meta; + $meta[static::META_KEY] = $preferences; + $user->meta = $meta; + $user->saveQuietly(); + + return $preferences; + } + + public static function allows($notifiable, string $category): bool + { + try { + return static::for(static::userFor($notifiable))[$category] ?? true; + } catch (\Throwable $e) { + // A preference that cannot be read must not cost anyone a notification. + return true; + } + } + + /** + * The channels a notification of this category may use for this person. + */ + public static function channels($notifiable, string $category, array $channels): array + { + if (static::allows($notifiable, $category)) { + return $channels; + } + + return array_values(array_filter($channels, fn ($channel) => in_array($channel, static::QUIET_CHANNELS, true))); + } +} From a321d2ae86d04cdc245eb1e8ddd7d1039ec605b4 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 27 Nov 2026 15:15:20 +0800 Subject: [PATCH 6/6] Devices carry what they are; Apple pushes go through sandbox or production per device; dead tokens are retired --- ...d_device_details_to_user_devices_table.php | 56 ++++++++++++ src/Models/UserDevice.php | 8 +- src/Notifications/Channels/ApnChannel.php | 90 +++++++++++++++++++ src/Providers/CoreServiceProvider.php | 3 + src/Support/PushNotification.php | 8 +- 5 files changed, 160 insertions(+), 5 deletions(-) create mode 100644 migrations/2026_11_27_000000_add_device_details_to_user_devices_table.php create mode 100644 src/Notifications/Channels/ApnChannel.php diff --git a/migrations/2026_11_27_000000_add_device_details_to_user_devices_table.php b/migrations/2026_11_27_000000_add_device_details_to_user_devices_table.php new file mode 100644 index 00000000..a8bda677 --- /dev/null +++ b/migrations/2026_11_27_000000_add_device_details_to_user_devices_table.php @@ -0,0 +1,56 @@ + 191, + 'model' => 191, + 'manufacturer' => 191, + 'os_version' => 64, + 'app_version' => 64, + 'app_build' => 64, + 'locale' => 32, + 'timezone' => 64, + ]; + + public function up(): void + { + if (!Schema::hasTable('user_devices')) { + return; + } + + Schema::table('user_devices', function (Blueprint $table) { + foreach ($this->columns as $column => $length) { + if (!Schema::hasColumn('user_devices', $column)) { + $table->string($column, $length)->nullable(); + } + } + if (!Schema::hasColumn('user_devices', 'signed_out_at')) { + $table->timestamp('signed_out_at')->nullable(); + } + }); + } + + public function down(): void + { + if (!Schema::hasTable('user_devices')) { + return; + } + + Schema::table('user_devices', function (Blueprint $table) { + foreach (array_merge(array_keys($this->columns), ['signed_out_at']) as $column) { + if (Schema::hasColumn('user_devices', $column)) { + $table->dropColumn($column); + } + } + }); + } +}; diff --git a/src/Models/UserDevice.php b/src/Models/UserDevice.php index 12631e79..9d1e78a6 100644 --- a/src/Models/UserDevice.php +++ b/src/Models/UserDevice.php @@ -37,7 +37,7 @@ class UserDevice extends Model * * @var array */ - protected $fillable = ['user_uuid', 'company_uuid', 'push_app_uuid', 'platform', 'push_provider', 'app_identifier', 'environment', 'token', 'status', 'last_seen_at']; + protected $fillable = ['user_uuid', 'company_uuid', 'push_app_uuid', 'platform', 'push_provider', 'app_identifier', 'environment', 'token', 'status', 'last_seen_at', 'name', 'model', 'manufacturer', 'os_version', 'app_version', 'app_build', 'locale', 'timezone', 'signed_out_at']; /** * The attributes that should be cast to native types. @@ -45,7 +45,8 @@ class UserDevice extends Model * @var array */ protected $casts = [ - 'last_seen_at' => 'datetime', + 'last_seen_at' => 'datetime', + 'signed_out_at' => 'datetime', ]; /** @@ -91,7 +92,8 @@ public static function normalizePlatform(?string $platform): ?string public static function installTokens(iterable $devices, string $platform): array { return collect($devices) - ->filter(fn ($device) => $device->platform === $platform && empty($device->push_app_uuid)) + // Only devices still signed in and whose token the push service still accepts. + ->filter(fn ($device) => $device->platform === $platform && empty($device->push_app_uuid) && !in_array($device->status, ['signed_out', 'invalid'], true)) ->map(fn ($device) => $device->token) ->values() ->toArray(); diff --git a/src/Notifications/Channels/ApnChannel.php b/src/Notifications/Channels/ApnChannel.php new file mode 100644 index 00000000..2ef93ba7 --- /dev/null +++ b/src/Notifications/Channels/ApnChannel.php @@ -0,0 +1,90 @@ +routeNotificationFor('apn', $notification); + if (empty($tokens)) { + return null; + } + + $message = $notification->toApn($notifiable); + $sandbox = static::sandboxTokens($tokens); + $groups = [ + [array_values(array_diff($tokens, $sandbox)), null], + [array_values(array_intersect($tokens, $sandbox)), false], + ]; + $responses = []; + + foreach ($groups as [$group, $production]) { + if (!$group) { + continue; + } + + try { + // The configured service for most; Apple's sandbox for devices that registered as development builds. + $client = $production === null ? ($message->client ?? $this->factory->instance()) : PushNotification::getApnClient($production); + $responses = array_merge($responses, $this->sendNotifications($client, $message, $group)); + } catch (\Throwable $e) { + report($e); + } + } + + $this->dispatchEvents($notifiable, $notification, $responses); + static::retireDeadTokens($responses); + + return $responses; + } + + /** The tokens among these that belong to development builds. */ + protected static function sandboxTokens(array $tokens): array + { + try { + return UserDevice::whereIn('token', $tokens)->whereIn('environment', static::SANDBOX_ENVIRONMENTS)->pluck('token')->all(); + } catch (\Throwable $e) { + return []; + } + } + + protected static function retireDeadTokens(array $responses): void + { + $dead = []; + foreach ($responses as $response) { + if ($response instanceof Response && $response->getStatusCode() !== Response::APNS_SUCCESS && in_array($response->getErrorReason(), static::DEAD_TOKEN_REASONS, true)) { + $dead[] = $response->getDeviceToken(); + } + } + + if ($dead) { + try { + UserDevice::whereIn('token', $dead)->update(['status' => 'invalid']); + } catch (\Throwable $e) { + report($e); + } + } + } +} diff --git a/src/Providers/CoreServiceProvider.php b/src/Providers/CoreServiceProvider.php index 5918b866..326442eb 100644 --- a/src/Providers/CoreServiceProvider.php +++ b/src/Providers/CoreServiceProvider.php @@ -145,6 +145,9 @@ class CoreServiceProvider extends ServiceProvider */ public function register() { + // Apple pushes go to each device through the service its token belongs to (sandbox or production). + $this->app->bind(\NotificationChannels\Apn\ApnChannel::class, \Fleetbase\Notifications\Channels\ApnChannel::class); + $this->mergeConfigFrom(__DIR__ . '/../../config/database.connections.php', 'database.connections'); $this->mergeConfigFrom(__DIR__ . '/../../config/database.redis.php', 'database.redis'); $this->mergeConfigFrom(__DIR__ . '/../../config/broadcasting.connections.php', 'broadcasting.connections'); diff --git a/src/Support/PushNotification.php b/src/Support/PushNotification.php index 5ae2d2a1..a4cf574c 100644 --- a/src/Support/PushNotification.php +++ b/src/Support/PushNotification.php @@ -76,8 +76,12 @@ public static function createFcmMessage(string $title, string $body, array $data ->usingClient(static::getFcmMessagingClient()); } - public static function getApnClient(): PushOkClient + /** + * @param bool|null $production which of Apple's services to use; the configured one when null + */ + public static function getApnClient(?bool $production = null): PushOkClient { + $forced = $production; $config = config('broadcasting.connections.apn'); // Get the APN key file and it's contents and store to config @@ -98,7 +102,7 @@ public static function getApnClient(): PushOkClient if ($production === null) { $production = app()->isProduction(); } - $isProductionEnv = Utils::castBoolean($production); + $isProductionEnv = $forced ?? Utils::castBoolean($production); return new PushOkClient(PuskOkToken::create($config), $isProductionEnv); }