From 4599a46c8983ea32def8ccc35b41d30a5af8ca3e Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Mon, 9 Nov 2026 15:30:52 +0100 Subject: [PATCH 1/2] CLARIN-DSpace v9/SSR static pages use the configured UI origin; SSR cache keyed by origin and language During SSR, HtmlContentService built the static-file URL from the request protocol and Host header. It now uses the origin of the configured ui.baseUrl, and the unused REQUEST injection is gone. The SSR page caches were keyed by path only, but an anonymous render also depends on the request origin and the dsLanguage cookie. The key moves to getSsrCacheKey (protocol, Host, language cookie, path) so it can be unit tested. The bot cache is read only for anonymous requests, like the anonymous cache. A static page name that contains a path separator once decoded loads nothing and renders the existing 404. Source: 60f6ccb1d4309bd273c66c26ee310bebbc6a5d78 Co-Authored-By: Claude Opus 5.5 --- server.ts | 25 +++++------------ src/app/shared/html-content.service.spec.ts | 30 +++++++++++++-------- src/app/shared/html-content.service.ts | 30 +++++++++++++-------- src/app/shared/ssr-cache-key.util.spec.ts | 21 +++++++++++++++ src/app/shared/ssr-cache-key.util.ts | 13 +++++++++ 5 files changed, 79 insertions(+), 40 deletions(-) create mode 100644 src/app/shared/ssr-cache-key.util.spec.ts create mode 100644 src/app/shared/ssr-cache-key.util.ts diff --git a/server.ts b/server.ts index 2056ec753ef..1b3e051f270 100644 --- a/server.ts +++ b/server.ts @@ -58,6 +58,7 @@ import { RESPONSE, } from './src/express.tokens'; import { SsrExcludePatterns } from "./src/config/ssr-config.interface"; +import { getSsrCacheKey } from './src/app/shared/ssr-cache-key.util'; /* * Set path for the browser application's dist folder @@ -403,14 +404,14 @@ function anonymousCacheEnabled(): boolean { /** * Check if the currently requested page is in our server-side, in-memory cache. - * Caching is ONLY done for SSR requests. Pages are cached base on their path (e.g. /home or /search?query=test) + * Caching is ONLY done for SSR requests. Pages are cached by path, origin and language (see getSsrCacheKey) */ function cacheCheck(req, res, next) { // Cached copy of page (if found) let cachedCopy; - // If the bot cache is enabled and this request looks like a bot, check the bot cache for a cached page. - if (botCacheEnabled() && isbot(req.get('user-agent'))) { + // If the bot cache is enabled and this request looks like an anonymous bot, check the bot cache for a cached page. + if (botCacheEnabled() && isbot(req.get('user-agent')) && !isUserAuthenticated(req)) { cachedCopy = checkCacheForRequest('bot', botCache, req, res, next); } else if (anonymousCacheEnabled() && !isUserAuthenticated(req)) { cachedCopy = checkCacheForRequest('anonymous', anonymousCache, req, res, next); @@ -454,7 +455,7 @@ function cacheCheck(req, res, next) { */ function checkCacheForRequest(cacheName: string, cache: LRUCache, req, res, next): any { // Get the cache key for this request - const key = getCacheKey(req); + const key = getSsrCacheKey(req); // Check if this page is in our cache const cachedCopy = cache.get(key); @@ -478,18 +479,6 @@ function checkCacheForRequest(cacheName: string, cache: LRUCache, r return cachedCopy; } -/** - * Create a cache key from the current request. - * The cache key is the URL path (NOTE: this key will also include any querystring params). - * E.g. "/home" or "/search?query=test" - * @param req current request - * @returns cache key to use for this page - */ -function getCacheKey(req): string { - // NOTE: this will return the URL path *without* any baseUrl - return req.url; -} - /** * Save page to server side cache(s), if enabled. If caching is not enabled or a user is authenticated, this is a noop * If multiple caches are enabled, the page will be saved to any caches where it does not yet exist (or is expired). @@ -502,9 +491,9 @@ function saveToCache(req, page: any) { // NOTE: It's not safe to save page data to the cache when a user is authenticated. In that situation, // the page may include sensitive or user-specific materials. As the cache is shared across all users, it can only contain public info. if (!isUserAuthenticated(req)) { - const key = getCacheKey(req); + const key = getSsrCacheKey(req); // Avoid caching "/reload/[random]" paths (these are hard refreshes after logout) - if (key.startsWith('/reload')) { return; } + if (req.url.startsWith('/reload')) { return; } // Avoid caching not successful responses (status code different from 2XX status) if (hasNotSucceeded(req.res.statusCode)) { return; } diff --git a/src/app/shared/html-content.service.spec.ts b/src/app/shared/html-content.service.spec.ts index 978813e4b0e..dde2fcaf286 100644 --- a/src/app/shared/html-content.service.spec.ts +++ b/src/app/shared/html-content.service.spec.ts @@ -52,7 +52,7 @@ describe('HtmlContentService', () => { { provide: APP_CONFIG, useValue: { - ui: { nameSpace }, + ui: { nameSpace, baseUrl: `http://localhost:4000${nameSpace}` }, }, }, ], @@ -170,28 +170,36 @@ describe('HtmlContentService', () => { expect(content).toBe(''); }); - it('should build an absolute URL from the injected express REQUEST when rendering on the server', async () => { - setup('/repository', 'server', expressRequest('https', 'dev-6.pc:8603')); + it('should fetch static content from the configured UI origin, not the request Host, during SSR', async () => { + setup('/repository', 'server', expressRequest('https', 'other.example')); - const contentPromise = firstValueFrom(service.getHtmlContent('static-files/about.html')); - - const request = httpMock.expectOne('https://dev-6.pc:8603/repository/static-files/about.html'); - expect(request.request.method).toBe('GET'); - request.flush('
About
'); + const promise = service.getHmtlContentByPathAndLocale('about'); + await settle(); - expect(await contentPromise).toBe('
About
'); + httpMock.expectOne('http://localhost:4000/repository/static-files/about.html').flush('Trusted content'); + expect(await promise).toBe('Trusted content'); }); - it('should keep the relative URL on the server when no REQUEST is available', async () => { + it('should use the configured UI origin on the server also without a REQUEST', async () => { setup('/repository', 'server'); const contentPromise = firstValueFrom(service.getHtmlContent('static-files/about.html')); - httpMock.expectOne('/repository/static-files/about.html').flush('
About
'); + httpMock.expectOne('http://localhost:4000/repository/static-files/about.html').flush('
About
'); expect(await contentPromise).toBe('
About
'); }); + it('should not request a file name that leaves static-files once decoded', async () => { + setup('/repository'); + + const promise = service.getHmtlContentByPathAndLocale('..%2Findex'); + await settle(); + + httpMock.expectNone(() => true); + expect(await promise).toBeUndefined(); + }); + it('should ignore the REQUEST and keep the relative URL in the browser', async () => { setup('/repository', 'browser', expressRequest('https', 'dev-6.pc:8603')); diff --git a/src/app/shared/html-content.service.ts b/src/app/shared/html-content.service.ts index 12cee05c30b..5b4072e02be 100644 --- a/src/app/shared/html-content.service.ts +++ b/src/app/shared/html-content.service.ts @@ -6,7 +6,6 @@ import { import { Inject, Injectable, - Optional, PLATFORM_ID, } from '@angular/core'; import { @@ -19,7 +18,6 @@ import { APP_CONFIG, AppConfig, } from '../../config/app-config.interface'; -import { REQUEST } from '../../express.tokens'; import { LocaleService } from '../core/locale/locale.service'; import { HTML_SUFFIX, @@ -36,7 +34,6 @@ export class HtmlContentService { private localeService: LocaleService, @Inject(APP_CONFIG) protected appConfig?: AppConfig, @Inject(PLATFORM_ID) private platformId?: object, - @Optional() @Inject(REQUEST) private request?: any, ) {} private getNamespacePrefix(): string { @@ -63,17 +60,12 @@ export class HtmlContentService { } private buildRuntimeUrl(path: string): string { - if (!isPlatformServer(this.platformId) || !this.request) { + if (!isPlatformServer(this.platformId)) { return path; } - const protocol = this.request.protocol; - const host = this.request.get?.('host'); - if (!protocol || !host) { - return path; - } - - return `${protocol}://${host}${path}`; + // The request Host header is client-controlled; SSR loads static HTML only from the configured UI origin. + return `${new URL(this.appConfig.ui.baseUrl).origin}${path}`; } getHtmlContent(url: string) { @@ -109,10 +101,26 @@ export class HtmlContentService { return undefined; } + /** + * Whether a file name taken from the URL is still one file name once the server decodes it, + * so it cannot address a file outside `static-files` (e.g. `..%2Findex`). A query part is ignored. + */ + private isPlainFileName(fileName: string): boolean { + try { + return !/[/\\]/.test(decodeURIComponent(fileName.split('?')[0])); + } catch { + // Missing name or malformed percent-encoding: nothing to load. + return false; + } + } + /** * Get the html file content as a string by the file name and the current locale. */ async getHmtlContentByPathAndLocale(fileName: string) { + if (!this.isPlainFileName(fileName)) { + return undefined; + } let url = ''; // Get current language let language = await firstValueFrom(this.localeService.getCurrentLanguageCode()); diff --git a/src/app/shared/ssr-cache-key.util.spec.ts b/src/app/shared/ssr-cache-key.util.spec.ts new file mode 100644 index 00000000000..031d5543530 --- /dev/null +++ b/src/app/shared/ssr-cache-key.util.spec.ts @@ -0,0 +1,21 @@ +import { Request } from 'express'; + +import { LANG_COOKIE } from '../core/locale/locale.service'; +import { getSsrCacheKey } from './ssr-cache-key.util'; + +describe('getSsrCacheKey', () => { + function request(protocol: string, host: string, cookies: Record = {}): Request { + return { url: '/static/about', protocol, get: () => host, cookies } as unknown as Request; + } + + it('should separate renders for different language cookies', () => { + expect(getSsrCacheKey(request('https', 'repo.example', { [LANG_COOKIE]: 'cs' }))) + .not.toEqual(getSsrCacheKey(request('https', 'repo.example', { [LANG_COOKIE]: 'en' }))); + }); + + it('should separate renders for different request origins', () => { + const key = getSsrCacheKey(request('https', 'repo.example')); + expect(getSsrCacheKey(request('https', 'other.example'))).not.toEqual(key); + expect(getSsrCacheKey(request('http', 'repo.example'))).not.toEqual(key); + }); +}); diff --git a/src/app/shared/ssr-cache-key.util.ts b/src/app/shared/ssr-cache-key.util.ts new file mode 100644 index 00000000000..5e62d6c66bf --- /dev/null +++ b/src/app/shared/ssr-cache-key.util.ts @@ -0,0 +1,13 @@ +import { Request } from 'express'; + +import { LANG_COOKIE } from '../core/locale/locale.service'; + +/** + * Key of a server-side rendered page in the SSR page caches (see server.ts). + * Besides path and query, an anonymous render depends on the request origin (protocol and Host header, + * e.g. in `citation_pdf_url`) and on the language cookie, so they are part of the key. + * @param req current request + */ +export function getSsrCacheKey(req: Request): string { + return JSON.stringify([req.protocol, req.get('host'), req.cookies?.[LANG_COOKIE], req.url]); +} From 405293c10622670c0709e0e06a46d41104abbdc7 Mon Sep 17 00:00:00 2001 From: milanmajchrak Date: Mon, 9 Nov 2026 16:05:33 +0100 Subject: [PATCH 2/2] CLARIN-DSpace v9/Simplify SSR cache key doc and spec parameter doc Co-Authored-By: Claude Opus 5.5 --- src/app/shared/html-content.service.spec.ts | 2 +- src/app/shared/ssr-cache-key.util.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/shared/html-content.service.spec.ts b/src/app/shared/html-content.service.spec.ts index dde2fcaf286..3769ff7a814 100644 --- a/src/app/shared/html-content.service.spec.ts +++ b/src/app/shared/html-content.service.spec.ts @@ -38,7 +38,7 @@ describe('HtmlContentService', () => { /** * @param nameSpace value of appConfig.ui.nameSpace * @param platformId 'server' exercises the SSR branch of buildRuntimeUrl - * @param request the express request injected through the REQUEST token + * @param request an express request provided through the REQUEST token; the service ignores it */ function setup(nameSpace: string, platformId: string = 'browser', request?: any): void { TestBed.configureTestingModule({ diff --git a/src/app/shared/ssr-cache-key.util.ts b/src/app/shared/ssr-cache-key.util.ts index 5e62d6c66bf..d17aab24f3d 100644 --- a/src/app/shared/ssr-cache-key.util.ts +++ b/src/app/shared/ssr-cache-key.util.ts @@ -4,8 +4,8 @@ import { LANG_COOKIE } from '../core/locale/locale.service'; /** * Key of a server-side rendered page in the SSR page caches (see server.ts). - * Besides path and query, an anonymous render depends on the request origin (protocol and Host header, - * e.g. in `citation_pdf_url`) and on the language cookie, so they are part of the key. + * Besides path and query, an anonymous render depends on the request origin (protocol and Host header) + * and on the language cookie, so they are part of the key. * @param req current request */ export function getSsrCacheKey(req: Request): string {