Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ describe('AssignmentsController', () => {
await sendEmail({ language: 'en', recipient: 'p@x.org' });
expect(groupsService.findById).not.toHaveBeenCalled();
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }],
links: [{ expiresAt: assignment.expiresAt, url: assignment.url }],
recipient: 'p@x.org',
template: DEFAULT_ASSIGNMENT_EMAIL_TEMPLATE
});
Expand All @@ -150,7 +150,7 @@ describe('AssignmentsController', () => {
assignmentsService.findById.mockResolvedValueOnce({ ...assignment, groupId: null });
await sendEmail({ language: 'en', recipient: 'p@x.org' });
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` }]
links: [{ expiresAt: assignment.expiresAt, url: assignment.url }]
});
});

Expand Down Expand Up @@ -237,7 +237,17 @@ describe('AssignmentsController', () => {
await sendEmail({ language: 'fr', recipient: 'p@x.org' });
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
language: 'fr',
links: [{ url: `${assignment.url}?lang=fr` }]
links: [{ url: assignment.url }]
});
});

it('never re-points the link, so an email in another language cannot override what the link says', async () => {
assignmentsService.findById.mockResolvedValueOnce({ ...assignment, url: `${assignment.url}?lang=en` });
groupsService.findById.mockResolvedValueOnce({ emailTemplates: [] });
await sendEmail({ language: 'fr', recipient: 'p@x.org' });
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
language: 'fr',
links: [{ url: `${assignment.url}?lang=en` }]
});
});

Expand Down Expand Up @@ -329,8 +339,8 @@ describe('AssignmentsController', () => {
expect(mailService.sendAssignmentEmail).toHaveBeenCalledOnce();
expect(mailService.sendAssignmentEmail.mock.lastCall?.[0]).toMatchObject({
links: [
{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=en` },
{ expiresAt: second.expiresAt, url: `${second.url}?lang=en` }
{ expiresAt: assignment.expiresAt, url: assignment.url },
{ expiresAt: second.expiresAt, url: second.url }
],
recipient: 'p@x.org'
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,12 @@ describe('AssignmentsService', () => {
expect(url).toBe(`http://localhost:3500/assignments/${id}`);
});

it('should open the participant link in the language chosen for the assignment', async () => {
await assignmentsService.create({ ...data(), language: 'fr' }, permissiveUser());
const { id, url } = assignmentModel.create.mock.lastCall?.[0].data ?? {};
expect(url).toBe(`http://localhost:3500/assignments/${id}?lang=fr`);
});

it('should point the participant link at the gateway site address in production', async () => {
await compile({
get: (key) => (key === 'NODE_ENV' ? 'production' : undefined),
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/assignments/assignments.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export class AssignmentsController {
language,
links: assignments.map((assignment) => ({
expiresAt: assignment.expiresAt,
url: `${assignment.url}?lang=${language}`
url: assignment.url
})),
recipient,
template: await this.resolveTemplate(groupId ?? null, templateId, ability)
Expand All @@ -156,7 +156,7 @@ export class AssignmentsController {
const assignment = await this.assignmentsService.findById(id, { ability });
const result = await this.mailService.sendAssignmentEmail({
language,
links: [{ expiresAt: assignment.expiresAt, url: `${assignment.url}?lang=${language}` }],
links: [{ expiresAt: assignment.expiresAt, url: assignment.url }],
recipient,
template: await this.resolveTemplate(assignment.groupId ?? null, templateId, ability)
});
Expand Down
12 changes: 10 additions & 2 deletions apps/api/src/assignments/assignments.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
BulkAssignmentIssue,
BulkAssignmentPreflightResult
} from '@opendatacapture/schemas/assignment';
import type { Language } from '@opendatacapture/schemas/core';

import { AuditLogger } from '@/audit/audit.logger';
import { accessibleQuery, forcedAppSubject } from '@/auth/ability.utils';
Expand Down Expand Up @@ -76,7 +77,7 @@ export class AssignmentsService {
}

async create(
{ expiresAt, groupId, instrumentId, redirectUrl, subjectId }: $CreateAssignmentData,
{ expiresAt, groupId, instrumentId, language, redirectUrl, subjectId }: $CreateAssignmentData,
currentUser: RequestUser
): Promise<Assignment> {
if (groupId) {
Expand All @@ -96,6 +97,7 @@ export class AssignmentsService {
expiresAt,
groupId,
instrumentId,
language,
redirectUrl,
subjectId
});
Expand Down Expand Up @@ -350,17 +352,20 @@ export class AssignmentsService {
expiresAt,
groupId,
instrumentId,
language,
redirectUrl,
subjectId
}: {
expiresAt: Date;
groupId?: null | string;
instrumentId: string;
language?: Language;
redirectUrl?: string;
subjectId: string;
}): Promise<{ assignment: Assignment; publicKey: webcrypto.CryptoKey }> {
const { privateKey, publicKey } = await HybridCrypto.generateKeyPair();
const id = crypto.randomUUID();
const link = `${this.assignmentBaseUrl}/assignments/${id}`;
const assignment = await this.assignmentModel.create({
data: {
encryptionKeyPair: {
Expand All @@ -374,7 +379,10 @@ export class AssignmentsService {
redirectUrl,
status: 'OUTSTANDING',
subject: { connect: { id: subjectId } },
url: `${this.assignmentBaseUrl}/assignments/${id}`
// The language is named on the link only when the assignment is created: a link left
// without one is one the subject's own browser decides, and nothing later — an email
// written in another language included — overrides that.
url: language ? `${link}?lang=${language}` : link
}
});
return { assignment, publicKey };
Expand Down
55 changes: 55 additions & 0 deletions apps/gateway/src/lib/__tests__/setup-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,59 @@ describe('resolveLanguage', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(['fr', 'en'])).toBe('en');
});

it('should open a link with no language in the language the browser asks for', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'fr-CA,fr;q=0.9,en;q=0.8')).toBe('fr');
});

it('should fall back to the browser for a link pinned to a language the instance has since turned off', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage('es', 'fr-CA,fr;q=0.9')).toBe('fr');
});

it('should prefer the language the link names over the one the browser asks for', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage('en', 'fr-CA,fr;q=0.9')).toBe('en');
});

it('should take the most wanted language the instance has active, not merely the first listed', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'de;q=0.9,fr;q=0.8,en;q=0.7')).toBe('fr');
});

it('should order by quality rather than by the order the header lists them', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'en;q=0.3,fr;q=0.9')).toBe('fr');
});

it('should ignore a language the browser explicitly refuses with q=0', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'fr;q=0,en;q=0.5')).toBe('en');
});

it('should fall back to the first active language when the browser asks for none it has', () => {
updateSetupState({ activeLanguages: ['fr', 'en'] });
expect(resolveLanguage(undefined, 'de,it')).toBe('fr');
});

it('should fall back to the first active language for a header it cannot read', () => {
updateSetupState({ activeLanguages: ['fr', 'en'] });
expect(resolveLanguage(undefined, ';;;')).toBe('fr');
});

it('should treat an unreadable quality as the strongest preference, since the language was still named', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'fr;q=high,en;q=0.9')).toBe('fr');
});

it('should treat a quality of punctuation alone as the strongest preference rather than dropping the language', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'fr;q=.,en;q=0.9')).toBe('fr');
});

it('should read a quality the client spells with a capital Q, which HTTP allows', () => {
updateSetupState({ activeLanguages: ['en', 'fr'] });
expect(resolveLanguage(undefined, 'fr;Q=0.1,en;Q=0.9')).toBe('en');
});
});
48 changes: 40 additions & 8 deletions apps/gateway/src/lib/setup-state.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
import { $Language, DEFAULT_ACTIVE_LANGUAGES, resolveActiveLanguage } from '@opendatacapture/schemas/core';
import { $Language, DEFAULT_ACTIVE_LANGUAGES } from '@opendatacapture/schemas/core';
import type { ActiveLanguages, Language } from '@opendatacapture/schemas/core';
import type { RemoteSetupState } from '@opendatacapture/schemas/gateway';

/**
* The languages an `Accept-Language` header asks for, most wanted first.
*
* Only the base language is kept, so `fr-CA` counts as a request for French, and a tag with `q=0`
* is dropped because that is how a client says it does not want one. An unreadable quality is
* treated as the default of 1 rather than discarded, since a client that sends one still wants the
* language it named. A parameter name is matched either case, as HTTP does not distinguish them.
*/
const parseAcceptLanguage = (header: string): string[] => {
return header
.split(',')
.map((part) => {
const [tag = '', ...parameters] = part.trim().split(';');
const quality = parameters
.map((parameter) => /^\s*q=(?<value>[\d.]+)\s*$/iu.exec(parameter)?.groups?.value)
.find((value) => value !== undefined);
const parsedQuality = quality === undefined ? 1 : Number.parseFloat(quality);
return { quality: Number.isNaN(parsedQuality) ? 1 : parsedQuality, tag: tag.trim() };
})
.filter(({ quality, tag }) => tag.length > 0 && quality > 0)
.sort((a, b) => b.quality - a.quality)
.map(({ tag }) => tag.split('-')[0]!.toLowerCase());
};

/**
* The setup state of the instance this gateway serves, as last pushed by `apps/api`.
*
Expand All @@ -18,16 +42,24 @@ export function getActiveLanguages(): ActiveLanguages {

/**
* The language to render a page in: the one a `?lang=` query asks for when the instance offers it,
* otherwise the first active language. Resolved server-side rather than from `window.location` so
* the SSR pass and the hydration pass agree; anything else renders the page in English and then
* swaps it.
* otherwise the first language the reader's browser asks for that the instance offers, and failing
* both the first active language. Resolved server-side rather than from `window.location` or
* `navigator` so the SSR pass and the hydration pass agree; anything else renders the page in one
* language and then swaps it.
*
* A link created without a language is the common case — an assignment is assigned before anyone
* knows what the subject reads — so the header is what makes that link open in their own language.
*/
export function resolveLanguage(requested: unknown): Language {
export function resolveLanguage(requested: unknown, acceptLanguage?: string): Language {
const activeLanguages = getActiveLanguages();
const requestedLanguage = $Language.safeParse(requested);
return requestedLanguage.success
? resolveActiveLanguage(requestedLanguage.data, activeLanguages)
: activeLanguages[0];
if (requestedLanguage.success && activeLanguages.includes(requestedLanguage.data)) {
return requestedLanguage.data;
}
const accepted = parseAcceptLanguage(acceptLanguage ?? '')
.map((tag) => $Language.safeParse(tag))
.find((parsed) => parsed.success && activeLanguages.includes(parsed.data));
return accepted?.success ? accepted.data : activeLanguages[0];
}

export function updateSetupState(state: RemoteSetupState): void {
Expand Down
17 changes: 15 additions & 2 deletions apps/gateway/src/routers/__tests__/root.router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ function storeAssignment(stored: {
});
}

async function getRootProps(path: string): Promise<RootProps> {
const response = await fetch(`${baseUrl}${path}`);
async function getRootProps(path: string, headers?: { [key: string]: string }): Promise<RootProps> {
const response = await fetch(`${baseUrl}${path}`, { headers });
return response.json();
}

Expand Down Expand Up @@ -111,6 +111,19 @@ describe('rootRouter', () => {
});
});

it('should open a link with no language in the language the browser asks for, which is how most links are created', async () => {
storeAssignment({});
expect(
await getRootProps('/assignments/assignment-1', { 'accept-language': 'fr-CA,fr;q=0.9,en;q=0.8' })
).toMatchObject({ language: 'fr' });
});

it('should name Accept-Language as what the page varies on, so a shared cache cannot serve one subject the language of another', async () => {
storeAssignment({});
const response = await fetch(`${baseUrl}/assignments/assignment-1`);
expect(response.headers.get('vary')).toBe('Accept-Language');
});

it('should hand the page the redirect URL the assignment was created with, so it can send the subject on', async () => {
storeAssignment({ redirectUrl: 'https://example.com/done' });
expect(await getRootProps('/assignments/assignment-1')).toMatchObject({
Expand Down
8 changes: 4 additions & 4 deletions apps/gateway/src/routers/root.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,22 @@ router.get(
id,
initialSeriesIndex,
kind: 'assignment',
language: resolveLanguage(req.query.lang),
language: resolveLanguage(req.query.lang, req.headers['accept-language']),
redirectUrl: assignment.redirectUrl ?? undefined,
target: targetParseResult.data,
token
} satisfies RootProps);
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
res.status(200).set({ 'Content-Type': 'text/html', Vary: 'Accept-Language' }).end(html);
})
);

router.get('/', (req, res) => {
const html = res.locals.loadRoot({
activeLanguages: getActiveLanguages(),
kind: 'landing',
language: resolveLanguage(req.query.lang)
language: resolveLanguage(req.query.lang, req.headers['accept-language'])
} satisfies RootProps);
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
res.status(200).set({ 'Content-Type': 'text/html', Vary: 'Accept-Language' }).end(html);
});

export { router as rootRouter };
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Label, Select } from '@douglasneuroinformatics/libui/components';
import { useTranslation } from '@douglasneuroinformatics/libui/hooks';
import { $Language } from '@opendatacapture/schemas/core';
import type { Language } from '@opendatacapture/schemas/core';

import type { AdministrationChoice } from '@/utils/administration-choice';
import { LANGUAGE_LABELS } from '@/utils/language';

/** Stands in for "no language", which a Select cannot hold as a value of its own. */
const AUTOMATIC = '__automatic__';

type AdministrationOptionsProps = {
choice: AdministrationChoice;
onLanguageChange: (language: Language | undefined) => void;
};

/**
* The language a remote assignment opens in. The default leaves it unset, so the gateway opens the
* link in whatever language the subject's browser asks for; picking one pins the link to it.
*/
export const AdministrationOptions = ({ choice, onLanguageChange }: AdministrationOptionsProps) => {
const { t } = useTranslation();
if (choice.languageOptions.length < 2) {
return null;
}
return (
<div className="flex flex-col gap-2">
<Label htmlFor="administration-language">{t('core.language')}</Label>
<Select
value={choice.language ?? AUTOMATIC}
onValueChange={(next) => onLanguageChange(next === AUTOMATIC ? undefined : $Language.parse(next))}
>
<Select.Trigger className="w-full" data-testid="administration-language" id="administration-language">
<Select.Value />
</Select.Trigger>
<Select.Content>
<Select.Group>
<Select.Item value={AUTOMATIC}>
{t({
en: "The subject's browser language",
es: 'El idioma del navegador del sujeto',
fr: 'La langue du navigateur du client'
})}
</Select.Item>
{choice.languageOptions.map((code) => (
<Select.Item key={code} value={code}>
{t(LANGUAGE_LABELS[code])}
</Select.Item>
))}
</Select.Group>
</Select.Content>
</Select>
</div>
);
};
Loading
Loading