diff --git a/AGENTS.md b/AGENTS.md
index d6b1091..56b6a02 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -290,6 +290,8 @@ make deploy APP=http_example HOST=timeweb SKIP=caddy,cron
* **Перетаскивание собрано на `mousedown` и `mouseup`.** `Actions.dragAndDrop` в Selenium эмулирует мышь, а события HTML5 `dragstart` и `drop` браузер на неё не шлёт, поэтому `draggable` пример молча не срабатывал бы.
* **Сессия это подписанная кука с путём курса, и курс записан в её значении.** Урок про куки сохраняет их после входа, открывает страницу в новом браузере, подкладывает куки руками и идёт в закрытый раздел. Кука одного курса не открывает раздел другого, неподписанное значение не открывает ничего.
* **Учётки напечатаны на страницах входа и в уроках.** Их смена это правка курсов.
+* **Дополнительные учётки и тексты обязательных полей задаются конфигом.** `extraAccounts` даёт вторую роль со своим разделом и заблокированную учётку, `usernameRequired` и `passwordRequired` включают отдельные сообщения о пустых полях. У приложения без этих ключей вход ведёт себя как раньше.
+* **API и раздел сотрудника `/python-playwright` написаны руками** в `custom-server/src/python-playwright.ts`, спецификации на TypeSpec у них нет. Урок про API читает только эти поля и коды, и правило «Набор данных не меняется» на них тоже действует.
## Набор данных не меняется
diff --git a/README.md b/README.md
index 432398e..1ce2ac1 100644
--- a/README.md
+++ b/README.md
@@ -47,8 +47,16 @@
| Путь | Сценарий |
| --- | --- |
-| `/python-playwright` | табло `#departures`, время вылета печатается в часовом поясе браузера, на узком экране строки складываются в карточки |
-| `/python-playwright/login` → `/trips` | вход пассажира `passenger` / `flight123`, «My trips» |
+| `/python-playwright` | табло `#departures` грузит рейсы запросом `api/departures`, время вылета печатается в часовом поясе браузера, часы `current-time`, на узком экране строки складываются в карточки, ссылки шапки уходят за кнопку «Navigation», блок «Travel alerts» прячется |
+| `/python-playwright/login` → `/trips` | вход пассажира `passenger` / `flight123`, «My trips», «Flight updates», токен `auth_token` в localStorage, выход по бездействию через пять минут на `/session-expired` |
+| `/python-playwright/login` → `/staff` | вход сотрудника `agent` / `staff123`, «Passenger list», пассажиру отвечает 403 «Access denied» |
+| `/python-playwright/login` | `blocked` / `flight123` заблокирован, пустые поля дают «Username is required.» и «Password is required.» |
+| `/python-playwright/packing` | список вещей вместо todomvc: поле «What do you need to pack?», `item`, `item-title`, счётчик `items-left` |
+| `/python-playwright/check-in` | форма регистрации: подписи, `select` и множественный `select`, кастомный список «Meal», radio, чекбоксы, загрузка файлов, теневой DOM; «Checked in» появляется через секунду |
+| `/python-playwright/boarding-pass` | `confirm` и `prompt`, «Airport map» в новой вкладке, оплата во фрейме `#payment`, скачивания `boarding-pass.pdf` и `trips.csv`, диалог выбора файла по «Attach visa» |
+| `/python-playwright/extras` | доп. услуги `.extra` со счётчиком `extras-count`, промокод `WINTER26` действует до 1 января 2027 года по часам браузера |
+
+API курса лежит под тем же префиксом и набор данных не меняет. `GET api/departures` фильтруется параметром `status`. `POST api/login` отдаёт токен `<учётка>-token` и открывает сессию браузера. `api/bookings` закрыт заголовком `Authorization: Bearer <токен>`: GET списка и записи, POST отвечает 201 (без `flight` или `passenger` 422), PUT и PATCH отвечают изменённой записью, DELETE отвечает 204.
У всех трёх одинаковое устройство входа. Форма `#login` с полями `#username` и `#password` и кнопкой `button.primary[data-test=login-button]`, флеш-сообщение `#flash`, выход по `/<курс>/logout`. Приложения описаны конфигом `apps` в `custom-server/src/ui-pages.ts`, страницы лежат фрагментами в `custom-server/assets/ui-pages/<курс>/`, префикс в них записан как `{{prefix}}`.
diff --git a/custom-server/assets/ui-pages/python-playwright/airport-map.html b/custom-server/assets/ui-pages/python-playwright/airport-map.html
new file mode 100644
index 0000000..1668907
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/airport-map.html
@@ -0,0 +1,9 @@
+
+ Airport map
+ Terminal 1: gates A1 to A12. Terminal 2: gates B1 to C9.
+ Close
+
+
diff --git a/custom-server/assets/ui-pages/python-playwright/boarding-pass.html b/custom-server/assets/ui-pages/python-playwright/boarding-pass.html
new file mode 100644
index 0000000..214bc04
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/boarding-pass.html
@@ -0,0 +1,33 @@
+
+ Boarding pass
+ Anna Berg, flight SK 204 to Lisbon, seat 14A.
+ Download boarding pass
+ Export trips (CSV)
+ Airport map
+ Add companion
+
+ Attach visa
+
+
+ Seat upgrade
+
+ Cancel check-in
+
+
+
diff --git a/custom-server/assets/ui-pages/python-playwright/check-in.html b/custom-server/assets/ui-pages/python-playwright/check-in.html
new file mode 100644
index 0000000..f31ba30
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/check-in.html
@@ -0,0 +1,95 @@
+
+ Online check-in
+
+
+ Accept the terms to check in.
+
+
+
diff --git a/custom-server/assets/ui-pages/python-playwright/extras.html b/custom-server/assets/ui-pages/python-playwright/extras.html
new file mode 100644
index 0000000..d6b8757
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/extras.html
@@ -0,0 +1,40 @@
+
+ Extras
+ Selected extras: 0
+
+
+
+
+
diff --git a/custom-server/assets/ui-pages/python-playwright/index.html b/custom-server/assets/ui-pages/python-playwright/index.html
index 08182de..4adbb50 100644
--- a/custom-server/assets/ui-pages/python-playwright/index.html
+++ b/custom-server/assets/ui-pages/python-playwright/index.html
@@ -1,23 +1,60 @@
- My trips
Departures
Times are shown in your time zone.
+ Airport time:
+
- Flight Destination Time Status
+ Flight Destination Time Status Gate
-
- SK 204 Lisbon On time
- SK 318 Oslo Boarding
- SK 527 Istanbul Delayed
-
+
+ No departures right now.
+ Departures are unavailable. Try again later.
+
diff --git a/custom-server/assets/ui-pages/python-playwright/logo.svg b/custom-server/assets/ui-pages/python-playwright/logo.svg
new file mode 100644
index 0000000..ac71260
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/logo.svg
@@ -0,0 +1 @@
+
diff --git a/custom-server/assets/ui-pages/python-playwright/packing.html b/custom-server/assets/ui-pages/python-playwright/packing.html
new file mode 100644
index 0000000..5477c79
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/packing.html
@@ -0,0 +1,37 @@
+
+ Packing list
+
+
+ Nothing to pack yet
+
+
diff --git a/custom-server/assets/ui-pages/python-playwright/payment.html b/custom-server/assets/ui-pages/python-playwright/payment.html
new file mode 100644
index 0000000..5981ea0
--- /dev/null
+++ b/custom-server/assets/ui-pages/python-playwright/payment.html
@@ -0,0 +1,25 @@
+
+
+
+
+ Payment
+
+
+
+
+ Payment accepted
+
+
+
diff --git a/custom-server/assets/ui-pages/style.css b/custom-server/assets/ui-pages/style.css
index c453d6b..464754c 100644
--- a/custom-server/assets/ui-pages/style.css
+++ b/custom-server/assets/ui-pages/style.css
@@ -28,3 +28,30 @@ iframe { width: 100%; height: 200px; border: 1px solid #9ca6b4; border-radius: 6
#departures tr { display: block; margin-bottom: 12px; padding: 8px; border: 1px solid #d5dbe3; border-radius: 8px; }
#departures td { display: block; border: 0; padding: 2px 0; }
}
+/* Шапка Departures: на широком экране ссылки в ряд, на узком за кнопкой. */
+header { display: flex; align-items: center; gap: 16px; margin: 16px 0; }
+header ul { display: flex; gap: 16px; margin: 0; padding: 0; list-style: none; }
+#nav-toggle { display: none; margin: 0; }
+aside { margin-top: 24px; padding: 12px 16px; background: #f1f4f9; border-radius: 8px; }
+@media (max-width: 600px) {
+ #nav-toggle { display: inline-block; }
+ #nav-links { display: none; }
+ #nav-links.open { display: flex; flex-direction: column; }
+ aside { display: none; }
+}
+select { display: block; box-sizing: border-box; width: 100%; margin-top: 8px; padding: 12px; font: inherit; }
+fieldset { margin-top: 16px; border: 1px solid #9ca6b4; border-radius: 6px; }
+.label { display: block; margin-top: 16px; }
+label.choice { display: flex; align-items: center; gap: 8px; }
+label.choice input { display: inline; width: auto; margin: 0; }
+.dropdown [role="listbox"] { margin: 4px 0 0; padding: 0; list-style: none; border: 1px solid #9ca6b4; border-radius: 6px; }
+.dropdown [role="option"] { padding: 8px 12px; cursor: pointer; }
+.dropdown [role="option"]:hover { background: #eef2fb; }
+.error { color: rgb(200, 30, 30); }
+#items li { display: flex; align-items: center; gap: 12px; }
+#items input { display: inline; width: auto; margin: 0; }
+#items button { margin: 0; padding: 4px 12px; }
+#items .packed label { text-decoration: line-through; }
+.extra { margin-top: 12px; }
+#passengers { width: 100%; border-collapse: collapse; }
+#passengers td, #passengers th { padding: 8px; text-align: left; border-bottom: 1px solid #d5dbe3; }
diff --git a/custom-server/src/index.ts b/custom-server/src/index.ts
index 76f2881..6941c5c 100644
--- a/custom-server/src/index.ts
+++ b/custom-server/src/index.ts
@@ -12,6 +12,7 @@ import rawConfig from '../../app.config.json' with { type: 'json' };
import setUpRpc from './rpc.ts';
import setUpBodyExamples from './body-examples.ts';
import setUpUiPages from './ui-pages.ts';
+import setUpPythonPlaywright from './python-playwright.ts';
import setUpSessionCacheExamples from './session-cache-examples.ts';
import setUpWebhookExamples from './webhook-examples.ts';
import setUpReliabilityExamples from './reliability-examples.ts';
@@ -118,6 +119,7 @@ export default async (app: FastifyInstance, _options: unknown) => {
await app.register(setUpBodyExamples);
await app.register(setUpUiPages);
+ await app.register(setUpPythonPlaywright);
await app.register(setUpSessionCacheExamples);
await app.register(setUpWebhookExamples);
await app.register(setUpReliabilityExamples);
diff --git a/custom-server/src/python-playwright.ts b/custom-server/src/python-playwright.ts
new file mode 100644
index 0000000..3a6e51f
--- /dev/null
+++ b/custom-server/src/python-playwright.ts
@@ -0,0 +1,196 @@
+import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
+
+import {
+ apps,
+ currentAccount,
+ endSession,
+ findAccount,
+ html,
+ layout,
+ redirectWithFlash,
+ startSession,
+} from './ui-pages.ts';
+
+// Всё, что у курса Playwright на Python есть помимо страниц: API табло и
+// бронирований, вход через API, раздел сотрудника, скачивания. Уроки цитируют
+// поля ответов и надписи дословно, поэтому данные здесь это текст курса.
+//
+// Набор данных не меняется, как и у остального сервера: POST, PUT, PATCH и
+// DELETE отвечают так, будто изменение случилось, но следующий GET отдаёт
+// прежний набор. Стенд общий, и запрос одного студента не должен менять то,
+// что видит другой.
+
+const prefix = '/python-playwright';
+const app = apps['python-playwright'];
+
+export const departures = [
+ { flight: 'SK 204', destination: 'Lisbon', departure: '2026-01-15T08:30:00Z', status: 'On time', gate: 'B12' },
+ { flight: 'SK 318', destination: 'Oslo', departure: '2026-01-15T09:10:00Z', status: 'Boarding', gate: 'A3' },
+ { flight: 'SK 527', destination: 'Istanbul', departure: '2026-01-15T11:45:00Z', status: 'Delayed', gate: 'C7' },
+ { flight: 'SK 611', destination: 'Rome', departure: '2026-01-15T13:20:00Z', status: 'Cancelled', gate: 'B4' },
+];
+
+export const bookings = [
+ { id: 1, flight: 'SK 204', passenger: 'Anna Berg', seat: '14A', status: 'confirmed' },
+ { id: 2, flight: 'SK 318', passenger: 'Mark Olsen', seat: '3C', status: 'confirmed' },
+];
+
+// Токен пишется в уроке, поэтому он постоянный: имя учётки и суффикс.
+const tokenOf = (username: string) => `${username}-token`;
+
+const passengers = [
+ { name: 'Anna Berg', flight: 'SK 204', seat: '14A' },
+ { name: 'Mark Olsen', flight: 'SK 318', seat: '3C' },
+ { name: 'Lena Novak', flight: 'SK 527', seat: '21F' },
+];
+
+// Минимальный PDF из одной пустой страницы: браузер скачивает его как файл, а
+// урок проверяет имя и непустой размер.
+const boardingPassPdf = `%PDF-1.4
+1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
+3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 144] >> endobj
+trailer << /Root 1 0 R >>
+%%EOF
+`;
+
+const tripsCsv = `flight,destination,seat
+SK 204,Lisbon,14A
+`;
+
+const authorized = (req: FastifyRequest) => {
+ const header = req.headers.authorization ?? '';
+ const accounts = [app.credentials, ...(app.extraAccounts ?? []).filter((account) => !account.locked)];
+ return accounts.some((account) => header === `Bearer ${tokenOf(account.username)}`);
+};
+
+const requireToken = (req: FastifyRequest, res: FastifyReply) => {
+ if (authorized(req)) return true;
+ res.code(401).send({ error: 'Missing or invalid token' });
+ return false;
+};
+
+const findBooking = (req: FastifyRequest, res: FastifyReply) => {
+ const { id } = req.params as { id: string };
+ const booking = bookings.find((item) => String(item.id) === id);
+ if (!booking) res.code(404).send({ error: 'Booking not found' });
+ return booking;
+};
+
+const page = (body: string) => layout(app, prefix, body);
+
+export default async function setUpPythonPlaywright(server: FastifyInstance) {
+ // Табло грузит рейсы этим запросом, и урок про моки подменяет именно его.
+ server.get(`${prefix}/api/departures`, (req) => {
+ const { status } = req.query as { status?: string };
+ if (!status) return departures;
+ return departures.filter((item) => item.status.toLowerCase() === status.toLowerCase());
+ });
+
+ server.post(`${prefix}/api/login`, (req, res) => {
+ const { username = '', password = '' } = (req.body ?? {}) as Record;
+ const account = findAccount(app, username, password);
+ if (!account || account.locked) {
+ return res.code(401).send({ error: 'Wrong username or password' });
+ }
+ // Вход через API открывает и сессию браузера: урок переносит куки из
+ // APIRequestContext в контекст браузера через storage_state.
+ startSession(res, account.username, prefix);
+ return { token: tokenOf(account.username) };
+ });
+
+ server.get(`${prefix}/api/bookings`, (req, res) => {
+ if (!requireToken(req, res)) return res;
+ return bookings;
+ });
+
+ server.get(`${prefix}/api/bookings/:id`, (req, res) => {
+ if (!requireToken(req, res)) return res;
+ return findBooking(req, res) ?? res;
+ });
+
+ server.post(`${prefix}/api/bookings`, (req, res) => {
+ if (!requireToken(req, res)) return res;
+ const body = (req.body ?? {}) as Record;
+ if (!body.flight || !body.passenger) {
+ return res.code(422).send({ error: 'Fields flight and passenger are required' });
+ }
+ return res.code(201).send({ id: bookings.length + 1, seat: null, ...body, status: 'confirmed' });
+ });
+
+ for (const method of ['put', 'patch'] as const) {
+ server[method](`${prefix}/api/bookings/:id`, (req, res) => {
+ if (!requireToken(req, res)) return res;
+ const booking = findBooking(req, res);
+ if (!booking) return res;
+ return { ...booking, ...(req.body as object), id: booking.id };
+ });
+ }
+
+ server.delete(`${prefix}/api/bookings/:id`, (req, res) => {
+ if (!requireToken(req, res)) return res;
+ if (!findBooking(req, res)) return res;
+ return res.code(204).send();
+ });
+
+ server.get(`${prefix}/staff`, (req, res) => {
+ const account = currentAccount(req, app, prefix);
+ if (!account) {
+ return redirectWithFlash(res, prefix, '/login', 'error', app.texts.mustLogIn);
+ }
+ if (account.username !== 'agent') {
+ return html(
+ res.code(403),
+ page(
+ ` \n Access denied \n Only airline staff can see the passenger list.
\n `,
+ ),
+ );
+ }
+ const rows = passengers
+ .map(
+ (item) =>
+ ` ${item.name} ${item.flight} ${item.seat} Remove `,
+ )
+ .join('\n');
+ return html(
+ res,
+ page(`
+ Passenger list
+
+
+ Passenger Flight Seat
+
+
+${rows}
+
+
+ Logout
+
+ `),
+ );
+ });
+
+ server.get(`${prefix}/session-expired`, (_req, res) => {
+ endSession(res, prefix);
+ return redirectWithFlash(res, prefix, '/login', 'error', 'Your session expired.');
+ });
+
+ server.get(`${prefix}/boarding-pass.pdf`, (_req, res) =>
+ res
+ .type('application/pdf')
+ .header('content-disposition', 'attachment; filename="boarding-pass.pdf"')
+ .send(boardingPassPdf),
+ );
+
+ server.get(`${prefix}/trips.csv`, (_req, res) =>
+ res
+ .type('text/csv; charset=utf-8')
+ .header('content-disposition', 'attachment; filename="trips.csv"')
+ .send(tripsCsv),
+ );
+}
diff --git a/custom-server/src/ui-pages.ts b/custom-server/src/ui-pages.ts
index d1ffd34..17ce093 100644
--- a/custom-server/src/ui-pages.ts
+++ b/custom-server/src/ui-pages.ts
@@ -18,9 +18,19 @@ interface Page {
bare?: boolean;
}
+// Учётка помимо основной: вторая роль со своим разделом или заблокированный
+// пользователь, на котором уроки показывают сообщение об ошибке входа.
+interface Account {
+ username: string;
+ password: string;
+ home: string;
+ locked?: boolean;
+}
+
interface UiApp {
title: string;
credentials: { username: string; password: string };
+ extraAccounts?: Account[];
securePath: string;
texts: {
loginHeading: string;
@@ -29,11 +39,17 @@ interface UiApp {
invalid: string;
mustLogIn: string;
loggedOut: string;
+ // Без этих текстов пустое поле считается неверной учёткой, как раньше.
+ usernameRequired?: string;
+ passwordRequired?: string;
+ locked?: string;
};
secureBody: string;
// Выхода в меню нет: ссылка на /logout на странице одна, и find_element по
// href не находит скрытый пункт меню раньше видимой кнопки.
menu: { label: string; path: string }[];
+ // Шапка приложения над содержимым каждой страницы, кроме фреймов.
+ header?: string;
pages: Record;
}
@@ -98,6 +114,10 @@ export const apps: Record = {
'python-playwright': {
title: 'Departures',
credentials: { username: 'passenger', password: 'flight123' },
+ extraAccounts: [
+ { username: 'agent', password: 'staff123', home: '/staff' }, // betterleaks:allow учебная учётка, напечатана в уроках
+ { username: 'blocked', password: 'flight123', home: '/trips', locked: true }, // betterleaks:allow учебная учётка, напечатана в уроках
+ ],
securePath: '/trips',
texts: {
loginHeading: 'Passenger login',
@@ -106,27 +126,80 @@ export const apps: Record = {
invalid: 'Wrong username or password.',
mustLogIn: 'Log in to see your trips.',
loggedOut: 'You logged out.',
+ usernameRequired: 'Username is required.',
+ passwordRequired: 'Password is required.',
+ locked: 'This account is locked.',
},
+ // Токен в localStorage нужен уроку про storage_state: снимок состояния
+ // уносит и куки, и localStorage. Выход по бездействию через пять минут
+ // показывает page.clock: без перемотки времени тест ждал бы по-настоящему.
secureBody: `
SK 204 to Lisbon, seat 14A
- `,
+
+ Flight updates
+
+ Check-in is open
+ Gate changed to B12
+ Boarding starts at 08:00
+
+ `,
menu: [{ label: 'Departures', path: '' }],
+ header: `
+
+ Navigation
+
+
+
+
+ `,
pages: {
'': { file: 'index.html' },
+ '/packing': { file: 'packing.html' },
+ '/check-in': { file: 'check-in.html' },
+ '/boarding-pass': { file: 'boarding-pass.html' },
+ '/airport-map': { file: 'airport-map.html' },
+ '/payment': { file: 'payment.html', bare: true },
+ '/extras': { file: 'extras.html' },
},
},
};
const sessionCookie = 'ui-session';
const flashCookie = 'ui-flash';
-const cookieOptionsFor = (prefix: string) => ({ path: prefix, httpOnly: true, sameSite: 'lax' }) as const;
+export const cookieOptionsFor = (prefix: string) => ({ path: prefix, httpOnly: true, sameSite: 'lax' }) as const;
const assetsDir = path.join(import.meta.dirname, '../assets/ui-pages');
const escape = (text: string) =>
text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
-const layout = (app: UiApp, prefix: string, body: string) => `
+const withPrefix = (text: string, prefix: string) => text.replaceAll('{{prefix}}', prefix);
+
+export const layout = (app: UiApp, prefix: string, body: string) =>
+ withPrefix(
+ `
@@ -136,10 +209,12 @@ const layout = (app: UiApp, prefix: string, body: string) => `
${app.title}
-${body}
+${app.header ? ` ${app.header}\n` : ''}${body}
-`;
+`,
+ prefix,
+ );
const flashBlock = (flash: { kind: string; message: string } | undefined) =>
flash ? ` ${escape(flash.message)}
\n` : '';
@@ -152,7 +227,7 @@ const takeFlash = (req: FastifyRequest, res: FastifyReply, prefix: string) => {
return { kind, message };
};
-const redirectWithFlash = (
+export const redirectWithFlash = (
res: FastifyReply,
prefix: string,
url: string,
@@ -160,26 +235,42 @@ const redirectWithFlash = (
message: string,
) => res.setCookie(flashCookie, `${kind}:${message}`, cookieOptionsFor(prefix)).redirect(`${prefix}${url}`);
+const accountsOf = (app: UiApp): Account[] => [
+ { ...app.credentials, home: app.securePath },
+ ...(app.extraAccounts ?? []),
+];
+
// В значении сессии стоит курс: урок про куки подкладывает их руками, и кука
// одного курса не должна открывать закрытый раздел другого.
-const sessionValue = (app: UiApp, prefix: string) => `${app.credentials.username}@${prefix}`;
+const sessionValue = (username: string, prefix: string) => `${username}@${prefix}`;
+
+export const startSession = (res: FastifyReply, username: string, prefix: string) =>
+ res.setCookie(sessionCookie, sessionValue(username, prefix), { ...cookieOptionsFor(prefix), signed: true });
+
+export const endSession = (res: FastifyReply, prefix: string) =>
+ res.clearCookie(sessionCookie, cookieOptionsFor(prefix));
-const isLoggedIn = (req: FastifyRequest, app: UiApp, prefix: string) => {
+// Учётка, под которой открыта сессия, или undefined без сессии.
+export const currentAccount = (req: FastifyRequest, app: UiApp, prefix: string) => {
const raw = req.cookies[sessionCookie];
- if (!raw) return false;
+ if (!raw) return undefined;
const { valid, value } = req.unsignCookie(raw);
- return valid && value === sessionValue(app, prefix);
+ if (!valid) return undefined;
+ return accountsOf(app).find((account) => !account.locked && sessionValue(account.username, prefix) === value);
};
-const html = (res: FastifyReply, body: string) => res.type('text/html; charset=utf-8').send(body);
+// Учётка по имени и паролю, как их проверяет форма входа.
+export const findAccount = (app: UiApp, username: string, password: string) =>
+ accountsOf(app).find((account) => account.username === username && account.password === password);
+
+export const html = (res: FastifyReply, body: string) => res.type('text/html; charset=utf-8').send(body);
const setUpApp = (server: FastifyInstance, course: string, app: UiApp) => {
const prefix = `/${course}`;
- const cookieOptions = cookieOptionsFor(prefix);
const { credentials, texts } = app;
for (const [route, page] of Object.entries(app.pages)) {
- const fragment = readFileSync(path.join(assetsDir, course, page.file), 'utf8').replaceAll('{{prefix}}', prefix);
+ const fragment = withPrefix(readFileSync(path.join(assetsDir, course, page.file), 'utf8'), prefix);
const body = page.bare ? fragment : layout(app, prefix, fragment);
server.get(`${prefix}${route}`, (_req, res) => html(res, body));
}
@@ -196,9 +287,9 @@ const setUpApp = (server: FastifyInstance, course: string, app: UiApp) => {
Use ${credentials.username} and ${credentials.password} to log in.
`,
@@ -207,16 +298,19 @@ const setUpApp = (server: FastifyInstance, course: string, app: UiApp) => {
});
server.post(`${prefix}/authenticate`, (req, res) => {
- const { username, password } = (req.body ?? {}) as Record;
- if (username !== credentials.username || password !== credentials.password) {
- return redirectWithFlash(res, prefix, '/login', 'error', texts.invalid);
- }
- res.setCookie(sessionCookie, sessionValue(app, prefix), { ...cookieOptions, signed: true });
- return redirectWithFlash(res, prefix, app.securePath, 'success', texts.loggedIn);
+ const { username = '', password = '' } = (req.body ?? {}) as Record;
+ const fail = (message: string) => redirectWithFlash(res, prefix, '/login', 'error', message);
+ if (!username && texts.usernameRequired) return fail(texts.usernameRequired);
+ if (!password && texts.passwordRequired) return fail(texts.passwordRequired);
+ const account = findAccount(app, username, password);
+ if (!account) return fail(texts.invalid);
+ if (account.locked) return fail(texts.locked ?? texts.invalid);
+ startSession(res, account.username, prefix);
+ return redirectWithFlash(res, prefix, account.home, 'success', texts.loggedIn);
});
server.get(`${prefix}${app.securePath}`, (req, res) => {
- if (!isLoggedIn(req, app, prefix)) {
+ if (!currentAccount(req, app, prefix)) {
return redirectWithFlash(res, prefix, '/login', 'error', texts.mustLogIn);
}
const flash = takeFlash(req, res, prefix);
@@ -250,7 +344,7 @@ ${menu}
});
server.get(`${prefix}/logout`, (_req, res) => {
- res.clearCookie(sessionCookie, cookieOptions);
+ endSession(res, prefix);
return redirectWithFlash(res, prefix, '/login', 'success', texts.loggedOut);
});
};
diff --git a/test/python-playwright.test.ts b/test/python-playwright.test.ts
new file mode 100644
index 0000000..5fd6974
--- /dev/null
+++ b/test/python-playwright.test.ts
@@ -0,0 +1,238 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import type { FastifyInstance } from 'fastify';
+
+import { bookings, departures } from '../custom-server/src/python-playwright.ts';
+import { apps } from '../custom-server/src/ui-pages.ts';
+import { buildApp, createClient } from './helpers.ts';
+
+let app: FastifyInstance;
+let client: ReturnType;
+
+beforeAll(async () => {
+ app = await buildApp();
+ client = createClient(app);
+});
+
+afterAll(() => app.close());
+
+const prefix = '/python-playwright';
+
+// Учётки берутся из конфига, как в ui-pages.test.ts: пароль литералом в тесте
+// сканер секретов принимает за утечку.
+const { credentials, extraAccounts = [] } = apps['python-playwright'];
+const [staff, blocked] = extraAccounts;
+
+const cookieHeader = (headers: Record) =>
+ [headers['set-cookie']]
+ .flat()
+ .filter(Boolean)
+ .map((cookie: string) => cookie.split(';')[0])
+ .join('; ');
+
+const logIn = (username: string, password: string) =>
+ client.send(`${prefix}/authenticate`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ payload: new URLSearchParams({ username, password }).toString(),
+ });
+
+const flashAfter = async (headers: Record) =>
+ (await client.send(`${prefix}/login`, { headers: { cookie: cookieHeader(headers) } })).body as string;
+
+const bearer = (username: string) => ({ authorization: `Bearer ${username}-token` });
+
+// Уроки курса Playwright на Python ищут эти элементы и надписи дословно.
+const pages: [string, string[]][] = [
+ [
+ '',
+ [
+ 'id="departures"',
+ 'data-testid="current-time"',
+ 'title="Flights today"',
+ '',
+ 'No departures right now.
',
+ `fetch('${prefix}/api/departures')`,
+ ],
+ ],
+ ['/packing', ['placeholder="What do you need to pack?"', 'data-testid="item-title"', 'data-testid="items-left"']],
+ [
+ '/check-in',
+ [
+ 'First name ',
+ 'placeholder="name@example.com"',
+ 'Seat preference ',
+ '',
+ 'aria-haspopup="listbox"',
+ 'Vegetarian ',
+ 'Cabin class ',
+ 'I accept the terms',
+ 'Passport scan ',
+ 'data-testid="check-in"',
+ 'Baggage allowance: 23 kg',
+ ],
+ ],
+ [
+ '/boarding-pass',
+ [
+ '>Download boarding pass',
+ '>Export trips (CSV)',
+ 'target="_blank">Airport map',
+ "confirm('Cancel your check-in?')",
+ "prompt('Companion name')",
+ `