From 4fb5d253c6c45480a63a6e7a34db7dd8c41469ca Mon Sep 17 00:00:00 2001 From: Amad Ul Hassan Date: Thu, 22 Oct 2026 16:38:16 +0200 Subject: [PATCH 1/2] fix(static-page): interpolate placeholders from config (ufal/dspace-angular PR 185) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ondřej Košarko (cherry picked from commit 45ab229543442755a3a092c65e7510e35cc0d15f) --- config/config.example.yml | 15 ++ .../static-page/static-page.component.spec.ts | 150 +++++++++++++++++- src/app/static-page/static-page.component.ts | 27 ++++ src/config/app-config.interface.ts | 2 + src/config/config.server.ts | 2 + src/config/config.util.spec.ts | 17 +- src/config/default-app-config.ts | 13 ++ src/config/static-page-config.interface.ts | 13 ++ 8 files changed, 235 insertions(+), 4 deletions(-) create mode 100644 src/config/static-page-config.interface.ts diff --git a/config/config.example.yml b/config/config.example.yml index 8b56711c7d2..fc3ec3ef2bb 100644 --- a/config/config.example.yml +++ b/config/config.example.yml @@ -467,3 +467,18 @@ accessibility: matomo: hostUrl: http://localhost:8135/ siteId: 1 + +# Values substituted for `${key}` placeholders in static pages served from `static-files` +# (e.g. `${dspace.name}` in terms-of-service.html). Values are plain text; HTML is escaped on insert. +# A missing or empty value leaves the `${key}` placeholder as is and logs a warning. +# Placeholders are substituted in text content only. Do not use them inside +# href, src, or other attribute values. +# You can override a single key; the other defaults are kept. +# Keys contain dots, so set them in this YAML file rather than through environment variables. +#staticPage: +# variables: +# dspace.name: LINDAT/CLARIAH-CZ Repository +# lr.description.institution: Institute of Formal and Applied Linguistics +# lr.description.location: Malostranské náměstí 25, 118 00 Praha, Czech Republic +# lr.description.city: Prague +# lr.description.country: Czech Republic diff --git a/src/app/static-page/static-page.component.spec.ts b/src/app/static-page/static-page.component.spec.ts index f62bf4a1756..b5ba6e8d443 100644 --- a/src/app/static-page/static-page.component.spec.ts +++ b/src/app/static-page/static-page.component.spec.ts @@ -1,4 +1,4 @@ -import { TestBed } from '@angular/core/testing'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; import { StaticPageComponent } from './static-page.component'; import { HtmlContentService } from '../shared/html-content.service'; @@ -10,6 +10,7 @@ import { APP_CONFIG } from '../../config/app-config.interface'; import { environment } from '../../environments/environment'; import { ClarinSafeHtmlPipe } from '../shared/utils/clarin-safehtml.pipe'; import { ServerResponseService } from '../core/services/server-response.service'; +import { StaticPageConfig } from '../../config/static-page-config.interface'; describe('StaticPageComponent', () => { function createDeferred() { @@ -26,7 +27,8 @@ describe('StaticPageComponent', () => { html: string | undefined, restBase?: string, contentPromise?: Promise, - route: string = '/static/test-file.html' + route: string = '/static/test-file.html', + staticPage?: StaticPageConfig ) { const htmlContentService = jasmine.createSpyObj('htmlContentService', { fetchHtmlContent: of(html), @@ -49,7 +51,8 @@ describe('StaticPageComponent', () => { rest: { ...(environment as any).rest, baseUrl: restBase - } + }, + staticPage }; await TestBed.configureTestingModule({ @@ -167,6 +170,147 @@ describe('StaticPageComponent', () => { expect(component.htmlContent.value).toBe(otherHtml); }); + describe('variable interpolation', () => { + const allPlaceholdersHtml = '

Welcome to ${dspace.name}, provided by ${lr.description.institution}, ' + + 'located at ${lr.description.location}.

Laws of ${lr.description.country}, court of ${lr.description.city}.

'; + const allVariables = { + 'dspace.name': 'Test Repository', + 'lr.description.institution': 'Test Institute', + 'lr.description.location': 'Test Street 1, 100 00 Test City', + 'lr.description.city': 'Test City', + 'lr.description.country': 'Test Country', + }; + + function setupInterpolationTest(html: string, variables?: { [key: string]: string }, restBase?: string) { + const staticPage = variables === undefined ? undefined : { variables }; + return setupTest(html, restBase, undefined, '/static/test-file.html', staticPage); + } + + async function render(fixture: ComponentFixture) { + fixture.detectChanges(); + await fixture.whenStable(); + fixture.detectChanges(); + } + + let warnSpy: jasmine.Spy; + + beforeEach(() => { + warnSpy = spyOn(console, 'warn'); + }); + + it('should replace all configured placeholders', async () => { + const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, allVariables); + await render(fixture); + + const content = component.htmlContent.value; + Object.values(allVariables).forEach((value) => expect(content).toContain(value)); + expect(content).not.toContain('${'); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('should leave an unknown placeholder literal and warn once', async () => { + const { fixture, component } = await setupInterpolationTest('

${dspace.name} ${foo.bar}

', allVariables); + await render(fixture); + + expect(component.htmlContent.value).toBe('

Test Repository ${foo.bar}

'); + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy).toHaveBeenCalledWith('Static page: unresolved variables', ['foo.bar']); + }); + + it('should treat an empty string value as missing', async () => { + const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { ...allVariables, 'dspace.name': '' }); + await render(fixture); + + expect(component.htmlContent.value).toBe('

${dspace.name}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']); + }); + + it('should treat a null value as missing', async () => { + // A YAML key without a value (`dspace.name:`) is loaded as null + const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { ...allVariables, 'dspace.name': null }); + await render(fixture); + + expect(component.htmlContent.value).toBe('

${dspace.name}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']); + }); + + it('should treat a non-string value as missing', async () => { + // YAML can load a number, e.g. `dspace.name: 123` + const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { ...allVariables, 'dspace.name': 123 } as any); + await render(fixture); + + expect(component.htmlContent.value).toBe('

${dspace.name}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']); + }); + + it('should HTML-escape values', async () => { + const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { 'dspace.name': 'A & B' }); + await render(fixture); + + expect(component.htmlContent.value).toBe('

A & <b>B</b>

'); + const target = fixture.nativeElement.querySelector('#target'); + expect(target.querySelector('b')).toBeNull(); + expect(target.textContent).toBe('A & B'); + }); + + it('should insert values containing replacement patterns literally', async () => { + const { fixture, component } = await setupInterpolationTest( + '

${dspace.name}|${lr.description.city}

', + { 'dspace.name': 'a$&b', 'lr.description.city': 'c$1$`$\'d' } + ); + await render(fixture); + + expect(fixture.nativeElement.querySelector('#target').textContent).toBe('a$&b|c$1$`$\'d'); + expect(component.htmlContent.value).not.toContain('${'); + }); + + it('should leave content unchanged when staticPage config is missing', async () => { + const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, undefined); + await render(fixture); + + expect(component.contentState).toBe('found'); + expect(component.htmlContent.value).toBe(allPlaceholdersHtml); + }); + + it('should leave all placeholders literal and warn once when the variables map is empty', async () => { + const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, {}); + await render(fixture); + + expect(component.htmlContent.value).toBe(allPlaceholdersHtml); + expect(warnSpy).toHaveBeenCalledTimes(1); + expect(warnSpy.calls.mostRecent().args[1]).toEqual(jasmine.arrayWithExactContents(Object.keys(allVariables))); + }); + + it('should not touch other placeholder syntaxes', async () => { + const html = '

$dspace.name {{\'x\' | translate}} $ {dspace.name}

'; + const { fixture, component } = await setupInterpolationTest(html, allVariables); + await render(fixture); + + expect(component.htmlContent.value).toBe(html); + expect(warnSpy).not.toHaveBeenCalled(); + }); + + it('should apply both the OAI link rewrite and variable interpolation', async () => { + const { fixture, component } = await setupInterpolationTest( + '${dspace.name}', + allVariables, + 'https://api.example.org/repository/server' + ); + await render(fixture); + + expect(component.htmlContent.value) + .toBe('Test Repository'); + }); + + it('should not resolve inherited object properties', async () => { + const { fixture, component } = await setupInterpolationTest('

${toString} ${constructor}

', allVariables); + await render(fixture); + + expect(component.htmlContent.value).toBe('

${toString} ${constructor}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['toString', 'constructor']); + }); + }); + describe('contentState behavior', () => { it('should initialize contentState to "loading"', async () => { const { component } = await setupTest('
test
'); diff --git a/src/app/static-page/static-page.component.ts b/src/app/static-page/static-page.component.ts index 6ca77bf955c..bff081043b3 100644 --- a/src/app/static-page/static-page.component.ts +++ b/src/app/static-page/static-page.component.ts @@ -6,6 +6,7 @@ import { isEmpty } from '../shared/empty.util'; import { STATIC_PAGE_PATH } from './static-page-routing-paths'; import { APP_CONFIG, AppConfig } from '../../config/app-config.interface'; import { ServerResponseService } from '../core/services/server-response.service'; +import escapeHtml from 'lodash/escape'; /** * Component which load and show static files from the `static-files` folder. @@ -40,6 +41,7 @@ export class StaticPageComponent implements OnInit { const restBase = this.appConfig?.rest?.baseUrl; const oaiUrl = restBase ? restBase.replace(/\/+$/, '') + '/oai' : '/server/oai'; htmlContent = htmlContent.replace(/href="\/server\/oai/gi, 'href="' + oaiUrl); + htmlContent = this.interpolateVariables(htmlContent); this.htmlContent.next(htmlContent); this.contentState = 'found'; @@ -85,6 +87,31 @@ export class StaticPageComponent implements OnInit { this.redirectToRelativeLink(staticPageBaseUrl, href); } + /** + * Replace `${key}` placeholders with values from `staticPage.variables` in the app config. + * Values are HTML-escaped. Missing, null, non-string, or empty values leave the placeholder unchanged. + * @param html static page content + * @private + */ + private interpolateVariables(html: string): string { + const vars = this.appConfig?.staticPage?.variables ?? {}; + const missing = new Set(); + // Function replacer: `$&`, `$'` etc. in values are inserted literally, not as replacement patterns. + const out = html.replace(/\$\{([\w.-]+)\}/g, (match: string, key: string) => { + // Own-property check, so `${toString}` does not resolve to an inherited member. + const value = Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : undefined; + if (typeof value !== 'string' || value.trim() === '') { + missing.add(key); + return match; + } + return escapeHtml(value); + }); + if (missing.size > 0) { + console.warn('Static page: unresolved variables', [...missing]); + } + return out; + } + private getNamespacePrefix(): string { const nameSpace = this.appConfig?.ui?.nameSpace ?? '/'; return nameSpace === '/' ? '' : nameSpace.replace(/\/$/, ''); diff --git a/src/config/app-config.interface.ts b/src/config/app-config.interface.ts index 96a6f91f8ec..9c104898be1 100644 --- a/src/config/app-config.interface.ts +++ b/src/config/app-config.interface.ts @@ -27,6 +27,7 @@ import { SearchConfig } from './search-page-config.interface'; import { AccessibilitySettingsConfig } from '../app/accessibility/accessibility-settings.config'; import { MatomoConfig } from './matomo-config'; import { StatisticsConfig } from './statistics-config'; +import { StaticPageConfig } from './static-page-config.interface'; interface AppConfig extends Config { ui: UIServerConfig; @@ -59,6 +60,7 @@ interface AppConfig extends Config { signpostingEnabled: boolean; matomo: MatomoConfig; statistics?: StatisticsConfig; + staticPage?: StaticPageConfig; } /** diff --git a/src/config/config.server.ts b/src/config/config.server.ts index 848f5fa4622..aff8ff108dd 100644 --- a/src/config/config.server.ts +++ b/src/config/config.server.ts @@ -287,6 +287,8 @@ export const buildAppConfig = (destConfigPath?: string): AppConfig => { search: appConfig.search, accessibility: appConfig.accessibility, signpostingEnabled: appConfig.signpostingEnabled, + // Static page placeholder values (e.g. terms-of-service.html), needed for client-side rendering + staticPage: appConfig.staticPage, // Matomo analytics - only expose client-side tracking properties ...(appConfig.matomo && { matomo: { diff --git a/src/config/config.util.spec.ts b/src/config/config.util.spec.ts index 4dc2b67260e..d3fc149e274 100644 --- a/src/config/config.util.spec.ts +++ b/src/config/config.util.spec.ts @@ -1,5 +1,5 @@ import { environment } from '../environments/environment.production'; -import { extendEnvironmentWithAppConfig } from './config.util'; +import { extendEnvironmentWithAppConfig, mergeConfig } from './config.util'; import { DefaultAppConfig } from './default-app-config'; import { HandleThemeConfig } from './theme.config'; @@ -57,4 +57,19 @@ describe('Config Util', () => { expect((environment.themes[1] as HandleThemeConfig).handle).toEqual(customTheme.handle); }); }); + + describe('mergeConfig', () => { + it('should override a single static page variable and keep the other defaults', () => { + const appConfig = new DefaultAppConfig(); + const defaults = { ...appConfig.staticPage.variables }; + + mergeConfig(appConfig, { staticPage: { variables: { 'dspace.name': 'X' } } } as any); + + expect(appConfig.staticPage.variables['dspace.name']).toEqual('X'); + Object.keys(defaults) + .filter((key) => key !== 'dspace.name') + .forEach((key) => expect(appConfig.staticPage.variables[key]).toEqual(defaults[key])); + expect(Object.keys(appConfig.staticPage.variables).length).toEqual(5); + }); + }); }); diff --git a/src/config/default-app-config.ts b/src/config/default-app-config.ts index 38cb942e457..87f36cffb55 100644 --- a/src/config/default-app-config.ts +++ b/src/config/default-app-config.ts @@ -26,6 +26,7 @@ import { LiveRegionConfig } from '../app/shared/live-region/live-region.config'; import { SearchConfig } from './search-page-config.interface'; import { AccessibilitySettingsConfig } from '../app/accessibility/accessibility-settings.config'; import { MatomoConfig } from './matomo-config'; +import { StaticPageConfig } from './static-page-config.interface'; export class DefaultAppConfig implements AppConfig { production = false; @@ -456,4 +457,16 @@ export class DefaultAppConfig implements AppConfig { siteId: '1', dimensionId: 1 }; + + // Values substituted for `${key}` placeholders in static pages (e.g. terms-of-service.html). + // Plain text; HTML is escaped on insert. A missing or empty value leaves the placeholder as is. + staticPage: StaticPageConfig = { + variables: { + 'dspace.name': 'LINDAT/CLARIAH-CZ Repository', + 'lr.description.institution': 'Institute of Formal and Applied Linguistics', + 'lr.description.location': 'Malostranské náměstí 25, 118 00 Praha, Czech Republic', + 'lr.description.city': 'Prague', + 'lr.description.country': 'Czech Republic', + } + }; } diff --git a/src/config/static-page-config.interface.ts b/src/config/static-page-config.interface.ts new file mode 100644 index 00000000000..3cca4c6179d --- /dev/null +++ b/src/config/static-page-config.interface.ts @@ -0,0 +1,13 @@ +import { Config } from './config.interface'; + +/** + * Configuration for static pages served from the `static-files` folder. + */ +export class StaticPageConfig implements Config { + /** + * Values substituted for `${key}` placeholders in static page HTML, e.g. `${dspace.name}`. + * Values are plain text; they are HTML-escaped on insert. + * Placeholders are for text content only, not for URL or attribute values. + */ + public variables: { [key: string]: string } = {}; +} From 9b4e58e52d6d23133e08facc29403ecdf87107c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Ko=C5=A1arko?= Date: Thu, 22 Oct 2026 16:38:17 +0200 Subject: [PATCH 2/2] fix(static-page): read ${...} placeholder values from backend config (ufal/dspace-angular PR 188) Fill the Terms of Service placeholders from /api/config/properties instead of a new staticPage UI config section, as XMLUI did. Rename the placeholders to the backend keys (description.*), join comma-split values with ", ", and leave a placeholder as is when the property is missing or fails to load. Requires ufal/clarin-dspace PR 1424. (cherry picked from commit 550ec11fd969c9acb197894433c8b1b4e14ae9b6) --- config/config.example.yml | 15 -- .../static-page/static-page.component.spec.ts | 148 +++++++++--------- src/app/static-page/static-page.component.ts | 56 ++++--- src/config/app-config.interface.ts | 2 - src/config/config.server.ts | 2 - src/config/config.util.spec.ts | 17 +- src/config/default-app-config.ts | 13 -- src/config/static-page-config.interface.ts | 13 -- src/static-files/terms-of-service.html | 4 +- 9 files changed, 119 insertions(+), 151 deletions(-) delete mode 100644 src/config/static-page-config.interface.ts diff --git a/config/config.example.yml b/config/config.example.yml index fc3ec3ef2bb..8b56711c7d2 100644 --- a/config/config.example.yml +++ b/config/config.example.yml @@ -467,18 +467,3 @@ accessibility: matomo: hostUrl: http://localhost:8135/ siteId: 1 - -# Values substituted for `${key}` placeholders in static pages served from `static-files` -# (e.g. `${dspace.name}` in terms-of-service.html). Values are plain text; HTML is escaped on insert. -# A missing or empty value leaves the `${key}` placeholder as is and logs a warning. -# Placeholders are substituted in text content only. Do not use them inside -# href, src, or other attribute values. -# You can override a single key; the other defaults are kept. -# Keys contain dots, so set them in this YAML file rather than through environment variables. -#staticPage: -# variables: -# dspace.name: LINDAT/CLARIAH-CZ Repository -# lr.description.institution: Institute of Formal and Applied Linguistics -# lr.description.location: Malostranské náměstí 25, 118 00 Praha, Czech Republic -# lr.description.city: Prague -# lr.description.country: Czech Republic diff --git a/src/app/static-page/static-page.component.spec.ts b/src/app/static-page/static-page.component.spec.ts index b5ba6e8d443..7feafe91c75 100644 --- a/src/app/static-page/static-page.component.spec.ts +++ b/src/app/static-page/static-page.component.spec.ts @@ -5,12 +5,15 @@ import { HtmlContentService } from '../shared/html-content.service'; import { Router } from '@angular/router'; import { RouterMock } from '../shared/mocks/router.mock'; import { TranslateModule } from '@ngx-translate/core'; -import { of } from 'rxjs'; +import { Observable, of, throwError } from 'rxjs'; import { APP_CONFIG } from '../../config/app-config.interface'; import { environment } from '../../environments/environment'; import { ClarinSafeHtmlPipe } from '../shared/utils/clarin-safehtml.pipe'; import { ServerResponseService } from '../core/services/server-response.service'; -import { StaticPageConfig } from '../../config/static-page-config.interface'; +import { ConfigurationDataService } from '../core/data/configuration-data.service'; +import { ConfigurationProperty } from '../core/shared/configuration-property.model'; +import { RemoteData } from '../core/data/remote-data'; +import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils'; describe('StaticPageComponent', () => { function createDeferred() { @@ -28,13 +31,21 @@ describe('StaticPageComponent', () => { restBase?: string, contentPromise?: Promise, route: string = '/static/test-file.html', - staticPage?: StaticPageConfig + configProperties: { [name: string]: string[] } = {} ) { const htmlContentService = jasmine.createSpyObj('htmlContentService', { fetchHtmlContent: of(html), getHmtlContentByPathAndLocale: contentPromise ?? Promise.resolve(html) }); + // Unknown properties fail with 404, like a property the backend doesn't expose + const configurationService = jasmine.createSpyObj('configurationService', ['findByPropertyName']); + configurationService.findByPropertyName.and.callFake((name: string): Observable> => + Object.prototype.hasOwnProperty.call(configProperties, name) + ? createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), { name, values: configProperties[name] })) + : createFailedRemoteDataObject$('No such configuration property', 404) + ); + const responseService = jasmine.createSpyObj('responseService', { setNotFound: null }); @@ -51,8 +62,7 @@ describe('StaticPageComponent', () => { rest: { ...(environment as any).rest, baseUrl: restBase - }, - staticPage + } }; await TestBed.configureTestingModule({ @@ -64,13 +74,14 @@ describe('StaticPageComponent', () => { { provide: HtmlContentService, useValue: htmlContentService }, { provide: Router, useValue: router }, { provide: ServerResponseService, useValue: responseService }, + { provide: ConfigurationDataService, useValue: configurationService }, { provide: APP_CONFIG, useValue: appConfig } ] }).compileComponents(); const fixture = TestBed.createComponent(StaticPageComponent); const component = fixture.componentInstance; - return { fixture, component, htmlContentService, responseService }; + return { fixture, component, htmlContentService, responseService, configurationService }; } function createLinkEvent(href: string, useNestedTarget = false): Event { @@ -171,19 +182,18 @@ describe('StaticPageComponent', () => { }); describe('variable interpolation', () => { - const allPlaceholdersHtml = '

Welcome to ${dspace.name}, provided by ${lr.description.institution}, ' + - 'located at ${lr.description.location}.

Laws of ${lr.description.country}, court of ${lr.description.city}.

'; - const allVariables = { - 'dspace.name': 'Test Repository', - 'lr.description.institution': 'Test Institute', - 'lr.description.location': 'Test Street 1, 100 00 Test City', - 'lr.description.city': 'Test City', - 'lr.description.country': 'Test Country', + const allPlaceholdersHtml = '

Welcome to ${dspace.name}, provided by ${description.institution}, ' + + 'located at ${description.location}.

Laws of ${description.country}, court of ${description.city}.

'; + const allProperties = { + 'dspace.name': ['Test Repository'], + 'description.institution': ['Test Institute'], + 'description.location': ['Test Street 1', '100 00 Test City'], + 'description.city': ['Test City'], + 'description.country': ['Test Country'], }; - function setupInterpolationTest(html: string, variables?: { [key: string]: string }, restBase?: string) { - const staticPage = variables === undefined ? undefined : { variables }; - return setupTest(html, restBase, undefined, '/static/test-file.html', staticPage); + function setupInterpolationTest(html: string, configProperties: { [name: string]: string[] } = {}, restBase?: string) { + return setupTest(html, restBase, undefined, '/static/test-file.html', configProperties); } async function render(fixture: ComponentFixture) { @@ -198,53 +208,76 @@ describe('StaticPageComponent', () => { warnSpy = spyOn(console, 'warn'); }); - it('should replace all configured placeholders', async () => { - const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, allVariables); + it('should replace all placeholders with backend configuration properties', async () => { + const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, allProperties); await render(fixture); - const content = component.htmlContent.value; - Object.values(allVariables).forEach((value) => expect(content).toContain(value)); - expect(content).not.toContain('${'); + expect(component.htmlContent.value).toBe('

Welcome to Test Repository, provided by Test Institute, ' + + 'located at Test Street 1, 100 00 Test City.

Laws of Test Country, court of Test City.

'); expect(warnSpy).not.toHaveBeenCalled(); }); - it('should leave an unknown placeholder literal and warn once', async () => { - const { fixture, component } = await setupInterpolationTest('

${dspace.name} ${foo.bar}

', allVariables); + it('should join a value the backend split on commas', async () => { + // How the backend returns `dspace.name = A (B), C, D` + const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { + 'dspace.name': ['LINDAT/CLARIAH-CZ digital library at the Institute of Formal and Applied Linguistics (ÚFAL)', + 'Faculty of Mathematics and Physics', 'Charles University'], + }); await render(fixture); - expect(component.htmlContent.value).toBe('

Test Repository ${foo.bar}

'); - expect(warnSpy).toHaveBeenCalledTimes(1); - expect(warnSpy).toHaveBeenCalledWith('Static page: unresolved variables', ['foo.bar']); + expect(component.htmlContent.value).toBe('

LINDAT/CLARIAH-CZ digital library at the Institute of Formal and Applied ' + + 'Linguistics (ÚFAL), Faculty of Mathematics and Physics, Charles University

'); }); - it('should treat an empty string value as missing', async () => { - const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { ...allVariables, 'dspace.name': '' }); + it('should request each property once', async () => { + const { fixture, configurationService } = await setupInterpolationTest('

${dspace.name} ${dspace.name} ${description.city}

', allProperties); await render(fixture); - expect(component.htmlContent.value).toBe('

${dspace.name}

'); - expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']); + expect(configurationService.findByPropertyName).toHaveBeenCalledTimes(2); + expect(configurationService.findByPropertyName).toHaveBeenCalledWith('dspace.name'); + expect(configurationService.findByPropertyName).toHaveBeenCalledWith('description.city'); }); - it('should treat a null value as missing', async () => { - // A YAML key without a value (`dspace.name:`) is loaded as null - const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { ...allVariables, 'dspace.name': null }); + it('should not request any property when the page has no placeholders', async () => { + const html = '

No placeholders here

'; + const { fixture, component, configurationService } = await setupInterpolationTest(html, allProperties); await render(fixture); - expect(component.htmlContent.value).toBe('

${dspace.name}

'); - expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']); + expect(component.htmlContent.value).toBe(html); + expect(configurationService.findByPropertyName).not.toHaveBeenCalled(); + expect(warnSpy).not.toHaveBeenCalled(); }); - it('should treat a non-string value as missing', async () => { - // YAML can load a number, e.g. `dspace.name: 123` - const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { ...allVariables, 'dspace.name': 123 } as any); + it('should leave an unknown or unexposed placeholder literal and warn once', async () => { + const { fixture, component } = await setupInterpolationTest('

${dspace.name} ${foo.bar}

', allProperties); await render(fixture); + expect(component.htmlContent.value).toBe('

Test Repository ${foo.bar}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['foo.bar']); + }); + + it('should treat an empty value as missing', async () => { + const { fixture, component } = await setupInterpolationTest('

${dspace.name} ${description.city}

', + { 'dspace.name': [''], 'description.city': [] }); + await render(fixture); + + expect(component.htmlContent.value).toBe('

${dspace.name} ${description.city}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name', 'description.city']); + }); + + it('should still show the page when a property request errors', async () => { + const { fixture, component, configurationService, responseService } = await setupInterpolationTest('

${dspace.name}

'); + configurationService.findByPropertyName.and.returnValue(throwError(() => new Error('backend down'))); + await render(fixture); + + expect(component.contentState).toBe('found'); expect(component.htmlContent.value).toBe('

${dspace.name}

'); + expect(responseService.setNotFound).not.toHaveBeenCalled(); expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']); }); it('should HTML-escape values', async () => { - const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { 'dspace.name': 'A & B' }); + const { fixture, component } = await setupInterpolationTest('

${dspace.name}

', { 'dspace.name': ['A & B'] }); await render(fixture); expect(component.htmlContent.value).toBe('

A & <b>B</b>

'); @@ -255,8 +288,8 @@ describe('StaticPageComponent', () => { it('should insert values containing replacement patterns literally', async () => { const { fixture, component } = await setupInterpolationTest( - '

${dspace.name}|${lr.description.city}

', - { 'dspace.name': 'a$&b', 'lr.description.city': 'c$1$`$\'d' } + '

${dspace.name}|${description.city}

', + { 'dspace.name': ['a$&b'], 'description.city': ['c$1$`$\'d'] } ); await render(fixture); @@ -264,36 +297,19 @@ describe('StaticPageComponent', () => { expect(component.htmlContent.value).not.toContain('${'); }); - it('should leave content unchanged when staticPage config is missing', async () => { - const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, undefined); - await render(fixture); - - expect(component.contentState).toBe('found'); - expect(component.htmlContent.value).toBe(allPlaceholdersHtml); - }); - - it('should leave all placeholders literal and warn once when the variables map is empty', async () => { - const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, {}); - await render(fixture); - - expect(component.htmlContent.value).toBe(allPlaceholdersHtml); - expect(warnSpy).toHaveBeenCalledTimes(1); - expect(warnSpy.calls.mostRecent().args[1]).toEqual(jasmine.arrayWithExactContents(Object.keys(allVariables))); - }); - it('should not touch other placeholder syntaxes', async () => { const html = '

$dspace.name {{\'x\' | translate}} $ {dspace.name}

'; - const { fixture, component } = await setupInterpolationTest(html, allVariables); + const { fixture, component, configurationService } = await setupInterpolationTest(html, allProperties); await render(fixture); expect(component.htmlContent.value).toBe(html); - expect(warnSpy).not.toHaveBeenCalled(); + expect(configurationService.findByPropertyName).not.toHaveBeenCalled(); }); it('should apply both the OAI link rewrite and variable interpolation', async () => { const { fixture, component } = await setupInterpolationTest( '${dspace.name}', - allVariables, + allProperties, 'https://api.example.org/repository/server' ); await render(fixture); @@ -301,14 +317,6 @@ describe('StaticPageComponent', () => { expect(component.htmlContent.value) .toBe('Test Repository'); }); - - it('should not resolve inherited object properties', async () => { - const { fixture, component } = await setupInterpolationTest('

${toString} ${constructor}

', allVariables); - await render(fixture); - - expect(component.htmlContent.value).toBe('

${toString} ${constructor}

'); - expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['toString', 'constructor']); - }); }); describe('contentState behavior', () => { diff --git a/src/app/static-page/static-page.component.ts b/src/app/static-page/static-page.component.ts index bff081043b3..d0e10e19104 100644 --- a/src/app/static-page/static-page.component.ts +++ b/src/app/static-page/static-page.component.ts @@ -1,11 +1,13 @@ import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core'; import { HtmlContentService } from '../shared/html-content.service'; -import { BehaviorSubject } from 'rxjs'; +import { BehaviorSubject, firstValueFrom } from 'rxjs'; import { Router } from '@angular/router'; import { isEmpty } from '../shared/empty.util'; import { STATIC_PAGE_PATH } from './static-page-routing-paths'; import { APP_CONFIG, AppConfig } from '../../config/app-config.interface'; import { ServerResponseService } from '../core/services/server-response.service'; +import { ConfigurationDataService } from '../core/data/configuration-data.service'; +import { getFirstCompletedRemoteData } from '../core/shared/operators'; import escapeHtml from 'lodash/escape'; /** @@ -26,6 +28,7 @@ export class StaticPageComponent implements OnInit { private router: Router, private responseService: ServerResponseService, private changeDetector: ChangeDetectorRef, + private configurationService: ConfigurationDataService, @Inject(APP_CONFIG) protected appConfig?: AppConfig) { } async ngOnInit(): Promise { @@ -41,7 +44,7 @@ export class StaticPageComponent implements OnInit { const restBase = this.appConfig?.rest?.baseUrl; const oaiUrl = restBase ? restBase.replace(/\/+$/, '') + '/oai' : '/server/oai'; htmlContent = htmlContent.replace(/href="\/server\/oai/gi, 'href="' + oaiUrl); - htmlContent = this.interpolateVariables(htmlContent); + htmlContent = await this.interpolateVariables(htmlContent); this.htmlContent.next(htmlContent); this.contentState = 'found'; @@ -88,28 +91,45 @@ export class StaticPageComponent implements OnInit { } /** - * Replace `${key}` placeholders with values from `staticPage.variables` in the app config. - * Values are HTML-escaped. Missing, null, non-string, or empty values leave the placeholder unchanged. + * Replace `${key}` placeholders with the value of the backend configuration property `key`, e.g. `${dspace.name}`. + * The property must be listed in `rest.properties.exposed` on the backend. + * Values are HTML-escaped. A property that is not exposed, not set, empty, or fails to load leaves the placeholder unchanged. * @param html static page content * @private */ - private interpolateVariables(html: string): string { - const vars = this.appConfig?.staticPage?.variables ?? {}; - const missing = new Set(); + private async interpolateVariables(html: string): Promise { + const keys = [...new Set((html.match(/\$\{[\w.-]+\}/g) ?? []).map((placeholder) => placeholder.slice(2, -1)))]; + if (keys.length === 0) { + return html; + } + const loaded = await Promise.all(keys.map((key) => this.getConfigValue(key))); + const values = new Map(keys.map((key, i) => [key, loaded[i]])); + const missing = keys.filter((key) => values.get(key) === undefined); + if (missing.length > 0) { + console.warn('Static page: unresolved variables', missing); + } // Function replacer: `$&`, `$'` etc. in values are inserted literally, not as replacement patterns. - const out = html.replace(/\$\{([\w.-]+)\}/g, (match: string, key: string) => { - // Own-property check, so `${toString}` does not resolve to an inherited member. - const value = Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : undefined; - if (typeof value !== 'string' || value.trim() === '') { - missing.add(key); - return match; - } - return escapeHtml(value); + return html.replace(/\$\{([\w.-]+)\}/g, (match: string, key: string) => { + const value = values.get(key); + return value === undefined ? match : escapeHtml(value); }); - if (missing.size > 0) { - console.warn('Static page: unresolved variables', [...missing]); + } + + /** + * Load a configuration property from the backend. + * @param key property name + * @returns the property value, or `undefined` if it is missing, empty, or fails to load + * @private + */ + private async getConfigValue(key: string): Promise { + try { + const response = await firstValueFrom(this.configurationService.findByPropertyName(key).pipe(getFirstCompletedRemoteData())); + // The backend splits a value on commas into several values; join them back. + const value = response.hasSucceeded ? response.payload?.values?.join(', ').trim() : undefined; + return isEmpty(value) ? undefined : value; + } catch (error) { + return undefined; } - return out; } private getNamespacePrefix(): string { diff --git a/src/config/app-config.interface.ts b/src/config/app-config.interface.ts index 9c104898be1..96a6f91f8ec 100644 --- a/src/config/app-config.interface.ts +++ b/src/config/app-config.interface.ts @@ -27,7 +27,6 @@ import { SearchConfig } from './search-page-config.interface'; import { AccessibilitySettingsConfig } from '../app/accessibility/accessibility-settings.config'; import { MatomoConfig } from './matomo-config'; import { StatisticsConfig } from './statistics-config'; -import { StaticPageConfig } from './static-page-config.interface'; interface AppConfig extends Config { ui: UIServerConfig; @@ -60,7 +59,6 @@ interface AppConfig extends Config { signpostingEnabled: boolean; matomo: MatomoConfig; statistics?: StatisticsConfig; - staticPage?: StaticPageConfig; } /** diff --git a/src/config/config.server.ts b/src/config/config.server.ts index aff8ff108dd..848f5fa4622 100644 --- a/src/config/config.server.ts +++ b/src/config/config.server.ts @@ -287,8 +287,6 @@ export const buildAppConfig = (destConfigPath?: string): AppConfig => { search: appConfig.search, accessibility: appConfig.accessibility, signpostingEnabled: appConfig.signpostingEnabled, - // Static page placeholder values (e.g. terms-of-service.html), needed for client-side rendering - staticPage: appConfig.staticPage, // Matomo analytics - only expose client-side tracking properties ...(appConfig.matomo && { matomo: { diff --git a/src/config/config.util.spec.ts b/src/config/config.util.spec.ts index d3fc149e274..4dc2b67260e 100644 --- a/src/config/config.util.spec.ts +++ b/src/config/config.util.spec.ts @@ -1,5 +1,5 @@ import { environment } from '../environments/environment.production'; -import { extendEnvironmentWithAppConfig, mergeConfig } from './config.util'; +import { extendEnvironmentWithAppConfig } from './config.util'; import { DefaultAppConfig } from './default-app-config'; import { HandleThemeConfig } from './theme.config'; @@ -57,19 +57,4 @@ describe('Config Util', () => { expect((environment.themes[1] as HandleThemeConfig).handle).toEqual(customTheme.handle); }); }); - - describe('mergeConfig', () => { - it('should override a single static page variable and keep the other defaults', () => { - const appConfig = new DefaultAppConfig(); - const defaults = { ...appConfig.staticPage.variables }; - - mergeConfig(appConfig, { staticPage: { variables: { 'dspace.name': 'X' } } } as any); - - expect(appConfig.staticPage.variables['dspace.name']).toEqual('X'); - Object.keys(defaults) - .filter((key) => key !== 'dspace.name') - .forEach((key) => expect(appConfig.staticPage.variables[key]).toEqual(defaults[key])); - expect(Object.keys(appConfig.staticPage.variables).length).toEqual(5); - }); - }); }); diff --git a/src/config/default-app-config.ts b/src/config/default-app-config.ts index 87f36cffb55..38cb942e457 100644 --- a/src/config/default-app-config.ts +++ b/src/config/default-app-config.ts @@ -26,7 +26,6 @@ import { LiveRegionConfig } from '../app/shared/live-region/live-region.config'; import { SearchConfig } from './search-page-config.interface'; import { AccessibilitySettingsConfig } from '../app/accessibility/accessibility-settings.config'; import { MatomoConfig } from './matomo-config'; -import { StaticPageConfig } from './static-page-config.interface'; export class DefaultAppConfig implements AppConfig { production = false; @@ -457,16 +456,4 @@ export class DefaultAppConfig implements AppConfig { siteId: '1', dimensionId: 1 }; - - // Values substituted for `${key}` placeholders in static pages (e.g. terms-of-service.html). - // Plain text; HTML is escaped on insert. A missing or empty value leaves the placeholder as is. - staticPage: StaticPageConfig = { - variables: { - 'dspace.name': 'LINDAT/CLARIAH-CZ Repository', - 'lr.description.institution': 'Institute of Formal and Applied Linguistics', - 'lr.description.location': 'Malostranské náměstí 25, 118 00 Praha, Czech Republic', - 'lr.description.city': 'Prague', - 'lr.description.country': 'Czech Republic', - } - }; } diff --git a/src/config/static-page-config.interface.ts b/src/config/static-page-config.interface.ts deleted file mode 100644 index 3cca4c6179d..00000000000 --- a/src/config/static-page-config.interface.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Config } from './config.interface'; - -/** - * Configuration for static pages served from the `static-files` folder. - */ -export class StaticPageConfig implements Config { - /** - * Values substituted for `${key}` placeholders in static page HTML, e.g. `${dspace.name}`. - * Values are plain text; they are HTML-escaped on insert. - * Placeholders are for text content only, not for URL or attribute values. - */ - public variables: { [key: string]: string } = {}; -} diff --git a/src/static-files/terms-of-service.html b/src/static-files/terms-of-service.html index dd699238b15..47db90066c1 100644 --- a/src/static-files/terms-of-service.html +++ b/src/static-files/terms-of-service.html @@ -7,7 +7,7 @@

CLARIN Terms of Service (v1.0)

Preamble

-

Welcome to ${dspace.name}. This repository service is provided to you by ${lr.description.institution}, located at ${lr.description.location}, hereinafter referred to as CLARIN Centre. The mission of CLARIN is to provide as wide access as possible to language research materials and tools around Europe. To archive this goal, we set some ground rules in this document. By accessing or using, and in consideration of the CLARIN Services provided to you, you agree to abide by the Terms of Use below, which can be updated or modified according to article 9.

+

Welcome to ${dspace.name}. This repository service is provided to you by ${description.institution}, located at ${description.location}, hereinafter referred to as CLARIN Centre. The mission of CLARIN is to provide as wide access as possible to language research materials and tools around Europe. To archive this goal, we set some ground rules in this document. By accessing or using, and in consideration of the CLARIN Services provided to you, you agree to abide by the Terms of Use below, which can be updated or modified according to article 9.

1. Governing Terms

@@ -134,7 +134,7 @@

5. Availability of Services

6. Governing Law and Entire Agreement

- These Terms are governed by the laws of ${lr.description.country} without regard to the rules of conflict of law that may cause the laws of another jurisdiction to apply. The User agrees to the sole and exclusive jurisdiction and venue of the ${lr.description.city} District Court of Law in the event of any dispute of any kind arising from or relating to the CLARIN Services, or the User’s use or review of it. However, CLARIN has the right to use the laws of another jurisdiction to get injunctive measures against the misuse of the CLARIN Service. + These Terms are governed by the laws of ${description.country} without regard to the rules of conflict of law that may cause the laws of another jurisdiction to apply. The User agrees to the sole and exclusive jurisdiction and venue of the ${description.city} District Court of Law in the event of any dispute of any kind arising from or relating to the CLARIN Services, or the User’s use or review of it. However, CLARIN has the right to use the laws of another jurisdiction to get injunctive measures against the misuse of the CLARIN Service.