From e52fdfd416a26d08032f7747800cd849d3b2c856 Mon Sep 17 00:00:00 2001 From: Anthony Date: Tue, 6 Oct 2026 00:18:41 -0500 Subject: [PATCH] Fix extension translations staying cached after an extension update Fixes #7245 --- .../Controllers/Base/LocaleController.php | 22 +++++--- app/Http/Requests/Base/LocaleRequest.php | 2 + .../Extensions/ExtensionRepository.php | 26 ++++++++- packages/sdk/types/extensions/registry.d.ts | 2 + resources/scripts/extensions/registry.ts | 2 + resources/scripts/i18n.spec.ts | 18 +++++++ resources/scripts/i18n.ts | 19 ++++++- .../Controllers/Base/LocaleControllerTest.php | 54 +++++++++++++++++++ .../Extensions/ExtensionManifestTest.php | 24 +++++++++ 9 files changed, 160 insertions(+), 9 deletions(-) diff --git a/app/Http/Controllers/Base/LocaleController.php b/app/Http/Controllers/Base/LocaleController.php index cd65bc95c..ff2d22721 100644 --- a/app/Http/Controllers/Base/LocaleController.php +++ b/app/Http/Controllers/Base/LocaleController.php @@ -35,13 +35,23 @@ class LocaleController extends Controller JsonValueGuard::assertValue($translations); $response[$locale][$namespace] = $this->i18n($translations); - return new JsonResponse($response, 200, [ - // Cache this in the browser for an hour, and allow the browser to use a stale - // cache for up to a day after it was created while it fetches an updated set - // of translation keys. - 'Cache-Control' => 'public, max-age=3600, stale-while-revalidate=86400', - 'ETag' => hash('sha256', json_encode($response, JSON_THROW_ON_ERROR)), + $json = new JsonResponse($response, 200, [ + // Core translations only change with a panel build, and the frontend puts the + // build hash in the URL: cache them in the browser for an hour, and allow a stale + // copy for up to a day while it fetches an updated set of translation keys. + // + // An extension's translations change whenever it is installed or upgraded, so + // the frontend adds their revision to the URL and they are cached the same way. + // Without it the URL would stay the same, and the browser has to revalidate. + 'Cache-Control' => count($segments) === 2 && ! $request->has('revision') + ? 'no-cache' + : 'public, max-age=3600, stale-while-revalidate=86400', ]); + $json->setEtag(hash('sha256', json_encode($response, JSON_THROW_ON_ERROR))); + // Answers a matching If-None-Match with an empty 304, which keeps revalidation cheap. + $json->isNotModified($request); + + return $json; } /** diff --git a/app/Http/Requests/Base/LocaleRequest.php b/app/Http/Requests/Base/LocaleRequest.php index c0284c7b2..dcac96828 100644 --- a/app/Http/Requests/Base/LocaleRequest.php +++ b/app/Http/Requests/Base/LocaleRequest.php @@ -16,6 +16,8 @@ class LocaleRequest extends FormRequest return [ 'locale' => ['required', 'string', 'regex:/^[a-z][a-z]$/'], 'namespace' => ['required', 'string', 'regex:/^(?:[a-z]{1,191}|ext-[a-z][a-z0-9-]{0,47}::[a-z][a-z0-9_-]{0,63})$/'], + // The revision of an extension's translations, which only makes the URL unique. + 'revision' => ['sometimes', 'string', 'regex:/^[a-f0-9]{32}$/'], ]; } } diff --git a/app/Services/Extensions/ExtensionRepository.php b/app/Services/Extensions/ExtensionRepository.php index c8a7a0fda..2340bea50 100644 --- a/app/Services/Extensions/ExtensionRepository.php +++ b/app/Services/Extensions/ExtensionRepository.php @@ -6,12 +6,14 @@ namespace Pterodactyl\Services\Extensions; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; use Pterodactyl\Events\Extensions\ExtensionLoadFailed; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Models\Extension; use Pterodactyl\Support\JsonValueGuard; +use Symfony\Component\Finder\SplFileInfo; use Throwable; class ExtensionRepository @@ -152,7 +154,7 @@ class ExtensionRepository * The enabled frontend extensions for the SPA to load. Signed-in users receive * each extension's frontend settings; everyone else only those marked ->public(). * - * @return array, components: list, development: array{url: string, version: string}|null}> + * @return array, components: list, development: array{url: string, version: string}|null}> */ public function frontendPayload(bool $authenticated): array { @@ -167,6 +169,7 @@ class ExtensionRepository 'version' => $manifest->version, 'entry' => $this->assets->entryUrl($manifest), 'prefix' => $manifest->uiPrefix, + 'translations' => $this->translationsRevision($manifest), 'config' => (object) $this->frontendConfig($manifest->id, ! $authenticated), 'screens' => $manifest->screens, 'components' => $manifest->components, @@ -224,6 +227,27 @@ class ExtensionRepository return $this->settings[$identifier] ??= new ExtensionSettings($identifier); } + /** + * Changes whenever the extension's translation files do. The frontend puts it in the + * URL it loads those translations from, which lets the browser cache them for as long + * as core translations and still pick up an installed or upgraded extension at once. + */ + private function translationsRevision(ExtensionManifest $manifest): ?string + { + $directory = $manifest->path('resources', 'lang'); + if (! is_dir($directory)) { + return null; + } + + $files = array_map( + fn (SplFileInfo $file): string => implode("\0", [$file->getRelativePathname(), $file->getSize(), $file->getMTime()]), + File::allFiles($directory), + ); + sort($files); + + return hash('xxh128', $manifest->version."\0".implode("\0", $files)); + } + /** * @param array $records * @return Collection diff --git a/packages/sdk/types/extensions/registry.d.ts b/packages/sdk/types/extensions/registry.d.ts index 5afa0f00b..e89d59623 100644 --- a/packages/sdk/types/extensions/registry.d.ts +++ b/packages/sdk/types/extensions/registry.d.ts @@ -168,6 +168,8 @@ export interface SiteExtensionEntry { entry: string; /** The Tailwind prefix declared as `ui.prefix`: the extension writes `:flex`. */ prefix?: string | null; + /** Changes with the extension's translation files, and is sent when loading them. */ + translations?: string | null; config?: ExtensionConfig; screens?: ExtensionScreenDefinition[]; components?: ComponentName[]; diff --git a/resources/scripts/extensions/registry.ts b/resources/scripts/extensions/registry.ts index 164ad4f41..8921207b3 100644 --- a/resources/scripts/extensions/registry.ts +++ b/resources/scripts/extensions/registry.ts @@ -371,6 +371,8 @@ export interface SiteExtensionEntry { entry: string; /** The Tailwind prefix declared as `ui.prefix`: the extension writes `:flex`. */ prefix?: string | null; + /** Changes with the extension's translation files, and is sent when loading them. */ + translations?: string | null; config?: ExtensionConfig; screens?: ExtensionScreenDefinition[]; components?: ComponentName[]; diff --git a/resources/scripts/i18n.spec.ts b/resources/scripts/i18n.spec.ts index 91468cb73..2c466beaf 100644 --- a/resources/scripts/i18n.spec.ts +++ b/resources/scripts/i18n.spec.ts @@ -65,3 +65,21 @@ it('follows language changes of the cached current user', async () => { expect(instance.language).toBe('nl'); client.clear(); }); + +it('adds the revision of an extension to the URL of its translations only', async () => { + (window as BootstrapWindow).SiteConfiguration = { + extensions: [ + { id: 'notes', entry: '/notes.js', translations: 'a1b2' }, + { id: 'plain', entry: '/plain.js', translations: null }, + ], + }; + const { localeLoadPath } = await import('@/i18n'); + const core = '/locales/locale.json?locale={{lng}}&namespace={{ns}}'; + + expect(localeLoadPath(['ext-notes::messages'])).toBe(`${core}&revision=a1b2`); + expect(localeLoadPath(['strings'])).toBe(core); + expect(localeLoadPath(['ext-plain::messages'])).toBe(core); + expect(localeLoadPath(['ext-missing::messages'])).toBe(core); + // One request for several namespaces has no single revision to carry. + expect(localeLoadPath(['ext-notes::messages', 'strings'])).toBe(core); +}); diff --git a/resources/scripts/i18n.ts b/resources/scripts/i18n.ts index 3892175df..c868af1a7 100644 --- a/resources/scripts/i18n.ts +++ b/resources/scripts/i18n.ts @@ -6,7 +6,7 @@ import I18NextHttpBackend from 'i18next-http-backend'; import I18NextMultiloadBackendAdapter from 'i18next-multiload-backend-adapter'; import { currentUserQueryKey } from '@/api/account/queries'; import type { UserData } from '@/api/account/types'; -import { getBootstrapSiteSettings, getBootstrapUser } from '@/bootstrap'; +import { getBootstrapExtensions, getBootstrapSiteSettings, getBootstrapUser } from '@/bootstrap'; interface MultiloadHttpBackendOptions extends HttpBackendOptions { allowMultiLoading: boolean; @@ -15,6 +15,21 @@ interface MultiloadHttpBackendOptions extends HttpBackendOptions { // Busts the locale cache on every reload under HMR, otherwise once per build. const hash = import.meta.hot ? Date.now().toString(16) : import.meta.env.WEBPACK_BUILD_HASH; +const localePath = '/locales/locale.json?locale={{lng}}&namespace={{ns}}'; + +/** + * Extension translations change when the extension is upgraded, not with the panel build, + * so their URL also carries the revision the panel reported for that extension. + */ +export function localeLoadPath(namespaces: string[]): string { + const extensionId = namespaces.length === 1 ? /^ext-(.+)::/.exec(namespaces[0]!)?.[1] : undefined; + const revision = extensionId + ? getBootstrapExtensions().find((extension) => extension.id === extensionId)?.translations + : undefined; + + return revision ? `${localePath}&revision=${revision}` : localePath; +} + export const initialLanguage = (): string => getBootstrapUser()?.language || getBootstrapSiteSettings()?.locale || 'en'; export function followCurrentUserLanguage(queryClient: QueryClient, instance: I18n = i18n): () => void { @@ -41,7 +56,7 @@ i18n.use(I18NextMultiloadBackendAdapter) backend: { backend: I18NextHttpBackend, backendOption: { - loadPath: '/locales/locale.json?locale={{lng}}&namespace={{ns}}', + loadPath: (_languages, namespaces) => localeLoadPath(namespaces), queryStringParams: { hash }, allowMultiLoading: true, } satisfies MultiloadHttpBackendOptions, diff --git a/tests/Unit/Http/Controllers/Base/LocaleControllerTest.php b/tests/Unit/Http/Controllers/Base/LocaleControllerTest.php index 17970cfb0..45cc378ba 100644 --- a/tests/Unit/Http/Controllers/Base/LocaleControllerTest.php +++ b/tests/Unit/Http/Controllers/Base/LocaleControllerTest.php @@ -24,3 +24,57 @@ test('serves namespaced extension translations and rejects path traversal', func \Illuminate\Support\Facades\File::deleteDirectory($directory); } }); + +test('caches translations whose URL changes with them and makes the browser revalidate the rest', function (): void { + $directory = sys_get_temp_dir().'/ptero-locale-'.uniqid(); + \Illuminate\Support\Facades\File::ensureDirectoryExists($directory.'/en'); + \Illuminate\Support\Facades\File::put($directory.'/en/messages.php', ' "Welcome"];'); + $this->app->make(\Illuminate\Translation\Translator::class)->addNamespace('ext-probe', $directory); + try { + $core = $this->getJson('/locales/locale.json?locale=en&namespace=auth')->assertOk(); + expect($core->headers->get('Cache-Control'))->toContain('max-age=3600')->toContain('public'); + + // The frontend sends the revision of the extension's translations, so upgrading + // the extension changes the URL. + $revision = str_repeat('a1', 16); + $extension = $this->getJson("/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages&revision={$revision}")->assertOk(); + expect($extension->headers->get('Cache-Control'))->toContain('max-age=3600')->toContain('public'); + + // Without it an upgrade leaves the URL as it was, so a cached copy must never be + // used without asking the server first. + $bare = $this->getJson('/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages')->assertOk(); + expect($bare->headers->get('Cache-Control'))->toContain('no-cache')->not->toContain('max-age'); + + $this->getJson('/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages&revision=..%2F')->assertUnprocessable(); + } finally { + \Illuminate\Support\Facades\File::deleteDirectory($directory); + } +}); + +test('answers an unchanged translation set with 304 and a changed one with the new strings', function (): void { + $directory = sys_get_temp_dir().'/ptero-locale-'.uniqid(); + $url = '/locales/locale.json?locale=en&namespace=ext-probe%3A%3Amessages'; + \Illuminate\Support\Facades\File::ensureDirectoryExists($directory.'/en'); + \Illuminate\Support\Facades\File::put($directory.'/en/messages.php', ' "Welcome"];'); + $this->app->make(\Illuminate\Translation\Translator::class)->addNamespace('ext-probe', $directory); + try { + $etag = $this->getJson($url)->assertOk()->headers->get('ETag'); + expect($etag)->toBeString()->toStartWith('"'); + + $this->getJson($url, ['If-None-Match' => $etag])->assertStatus(304); + + // What an extension upgrade does: the same URL now holds different strings. + \Illuminate\Support\Facades\File::put($directory.'/en/messages.php', ' "Welcome", "summary" => "Summary"];'); + if (function_exists('opcache_invalidate')) { + opcache_invalidate($directory.'/en/messages.php', true); + } + $this->refreshApplication(); + $this->app->make(\Illuminate\Translation\Translator::class)->addNamespace('ext-probe', $directory); + + $this->getJson($url, ['If-None-Match' => $etag]) + ->assertOk() + ->assertJsonPath('en.ext-probe::messages.summary', 'Summary'); + } finally { + \Illuminate\Support\Facades\File::deleteDirectory($directory); + } +}); diff --git a/tests/Unit/Services/Extensions/ExtensionManifestTest.php b/tests/Unit/Services/Extensions/ExtensionManifestTest.php index b5b30e3c3..1bc16503c 100644 --- a/tests/Unit/Services/Extensions/ExtensionManifestTest.php +++ b/tests/Unit/Services/Extensions/ExtensionManifestTest.php @@ -185,8 +185,32 @@ test('leaves settings out of the bootstrap payload when config is not included', $payload = $repository->frontendPayload(authenticated: false); expect($payload[0]['id'])->toBe('example'); expect($payload[0]['prefix'])->toBeNull(); + expect($payload[0]['translations'])->toBeNull(); expect((array) $payload[0]['config'])->toBe([]); }); +test('reports a translations revision that changes with the translation files', function (): void { + writeManifest(['id' => 'example', 'name' => 'Example', 'version' => '1.0.0', 'ui' => ['entry' => 'dist/client.js']]); + $manifest = (new ExtensionManifestValidator)->fromDirectory($this->directory); + $repository = Mockery::mock(ExtensionRepository::class, [ + new ExtensionManifestValidator, + resolve(ExtensionAssetPublisher::class), + resolve(Dispatcher::class), + resolve(ExtensionSettingsRegistry::class), + resolve(\Pterodactyl\Services\Extensions\ExtensionCompatibility::class), + ])->makePartial(); + $repository->shouldReceive('enabled')->andReturn(collect(['example' => $manifest])); + $revision = fn (): ?string => $repository->frontendPayload(authenticated: false)[0]['translations']; + + File::ensureDirectoryExists($this->directory.'/resources/lang/en'); + File::put($this->directory.'/resources/lang/en/messages.php', ' "Welcome"];'); + $installed = $revision(); + expect($installed)->toMatch('/^[a-f0-9]{32}$/')->toBe($revision()); + + // What an upgrade does: the same file, with different contents. + File::put($this->directory.'/resources/lang/en/messages.php', ' "Welcome", "summary" => "Summary"];'); + clearstatcache(); + expect($revision())->toMatch('/^[a-f0-9]{32}$/')->not->toBe($installed); +}); test('preserves resource tab parents in validated screen metadata', function (): void { $screens = [