TPTIP-4: совместить приватный профиль с дневником и планом тренировок
This commit is contained in:
parent
a2620d437b
commit
c984a7c14e
@ -2,7 +2,7 @@ FROM node:24-alpine
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY server.js ./
|
||||
COPY profile-server.mjs server.js index.html gym-plan.i18n.js manifest.webmanifest sw.js icon.svg about.html about.i18n.json ./
|
||||
COPY profile ./profile
|
||||
RUN npm run build && npm prune --omit=dev
|
||||
RUN mkdir /data && chown node:node /data
|
||||
@ -10,4 +10,4 @@ ENV NODE_ENV=production DATA_DIR=/data PORT=3000
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=3s CMD node -e "fetch('http://127.0.0.1:'+process.env.PORT+'/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
||||
CMD ["node","server.js"]
|
||||
CMD ["node","profile-server.mjs"]
|
||||
|
||||
@ -4,7 +4,7 @@
|
||||
|
||||
## Личный профиль (TPTIP-4)
|
||||
|
||||
Node.js 24+, `npm ci`, `npm run build`, `npm start`; откройте http://localhost:3000.
|
||||
Node.js 24.15+, `npm ci`, `npm run build`, `npm start`; откройте http://localhost:3000.
|
||||
`PORT` задаёт порт, `DATA_DIR` — каталог SQLite (по умолчанию `data/`).
|
||||
Проверки: `bash .gitea/peppa-check.sh lint`, `test`, `build`.
|
||||
Среда запуска агента может содержать NODE_TEST_CONTEXT: команда проверки удаляет эту переменную, иначе Node пропускает тесты.
|
||||
@ -22,3 +22,5 @@ Node.js 24+, `npm ci`, `npm run build`, `npm start`; откройте http://loc
|
||||
Проверка доступности: `curl http://localhost:3000/healthz`.
|
||||
|
||||
Браузерный SDK: `PUBLIC_SENTRY_DSN` (публичный DSN, отдельный от серверного), release и environment те же. `npm run build` собирает SDK в profile/telemetry.js; без DSN отправки нет.
|
||||
|
||||
Основной сервер: `profile-server.mjs`. CommonJS `server.js` сохранён как совместимый статический сервер для прежних тестов, рабочий запуск идёт через `npm start`. Дневник доступен по `/tracker` после входа. Нормы берутся из серверного профиля; профиль редактируется на `/`. Измерения не сохраняются в localStorage, дневник разделён по имени пользователя. Старая общая запись tpt.v1 автоматически не переносится, чтобы не раскрыть чужие данные. Личные страницы и ответы не кэшируются сервис-воркером; для них нужен интернет.
|
||||
|
||||
@ -40,3 +40,4 @@
|
||||
| Вход | войти, создать учётную запись, выйти, имя пользователя, пароль | логиниться, сессия, auth | Имя выбирает пользователь |
|
||||
| Питание | ориентир на день, калории, белок, пример меню, порция | TDEE, BMR, макросы | Расчёт для здоровых взрослых |
|
||||
| Параметры расчёта | пол для расчёта, активность | коэффициент, multiplier | Пользователь выбирает самостоятельно |
|
||||
| Ежедневные записи | дневник | логи | Питание и тренировки пользователя |
|
||||
|
||||
@ -2,10 +2,14 @@
|
||||
|
||||
17.11.2026: серверные сценарии прошли на Node.js 26 локально и Node.js 24 в собранном контейнере. Проверены пустые значения, обе границы диапазонов, неверные типы, дробный вес, неверный пароль, два пользователя, попытка указать чужой идентификатор, запрет чужого Origin, выход, истечение сессии и сохранение после перезапуска SQLite.
|
||||
|
||||
Chromium, 390×844 и 1280×900: пустые поля, обязательность ввода, регистрация, редактирование, пересчёт калорий/белка/порций, обновление страницы, выход, переключение ru/kk/en. Ошибок JavaScript нет. `node tests/browser-check.js` повторяет проверку после `npm run build` и `npx playwright install chromium`.
|
||||
Chromium, 390×844 и 1280×900: пустые поля, обязательность ввода, регистрация, редактирование, пересчёт калорий/белка/порций, обновление страницы, выход, переключение ru/kk/en. Ошибок JavaScript нет. `node tests/browser-check.mjs` повторяет проверку после `npm run build` и `npx playwright install chromium`.
|
||||
|
||||
Видимые тексты выписаны при браузерной проверке (`/tmp/tptip4-visible-texts.json`). Проверены все подписи, кнопки, подсказки и сообщения в `profile/i18n.json`; русские термины соответствуют `docs/glossary.md`, обращение только на «вы», технические идентификаторы и суммы не показываются. На экранах входа: название, вводные инструкции, имя, пароль, рост, вес, возраст, пол, активность, кнопки входа/создания записи и сообщение о приватности. В профиле: измерения, сохранение/выход, ориентир калорий и белка, блюда и порции, пояснение примерного расчёта. Ошибки состоят из причины и действия.
|
||||
|
||||
Моки не используются. Sentry проверен в режиме без DSN; реальная доставка событий требует настроенных SENTRY_DSN/PUBLIC_SENTRY_DSN. Это необязательный сбор ошибок, работа профиля от него не зависит.
|
||||
|
||||
Контейнер `tptip-4-profile` собран, запущен с PORT=3000; /healthz вернул 200. Постоянное хранилище настроено именованным томом compose. Изменения checks/deploy нужны, потому что main до задачи содержал только шаблон без приложения и проверок.
|
||||
|
||||
После rebase на main: сохранены дневник, рецепты и готовый план тренировок. 37 тестов пройдены. Chromium дополнительно проверяет авторизованный переход в дневник, те же вычисленные нормы, четыре дня плана, запрет доступа после выхода и отсутствие личных страниц/ответов в CacheStorage. Общая прежняя запись localStorage не переносится между учётными записями.
|
||||
|
||||
После обновления main строгая проверка всех OpenSpec нашла два унаследованных предупреждения: Purpose-заглушки в deploy и tracker. Эти требования не менялись в TPTIP-4. Строгая проверка private-profile проходит; они не влияют на проверки приложения.
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
export default [js.configs.recommended,{files:['**/*.js'],languageOptions:{globals:{...globals.node,...globals.browser}},rules:{'no-unused-vars':['error',{argsIgnorePattern:'^_'}]}},{ignores:['node_modules/**','profile/telemetry.js']}];
|
||||
@ -1,6 +1,8 @@
|
||||
import js from '@eslint/js';
|
||||
import globals from 'globals';
|
||||
export default [
|
||||
{ ignores: ['profile/telemetry.js'] },
|
||||
js.configs.recommended,
|
||||
{ files: ['**/*.{js,mjs}'], languageOptions: { globals: { ...globals.browser, ...globals.node, ...globals.serviceworker } } }
|
||||
{ files: ['**/*.{js,mjs}'], languageOptions: { sourceType: 'commonjs', globals: { ...globals.browser, ...globals.node, ...globals.serviceworker } } }
|
||||
, { files: ['**/*.mjs','profile/*.js'], languageOptions: { sourceType: 'module' } }
|
||||
];
|
||||
|
||||
28
index.html
28
index.html
@ -130,7 +130,7 @@ input:focus,select:focus,textarea:focus,button:focus-visible{outline:2px solid v
|
||||
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
|
||||
===================================================================== */
|
||||
/* LOGIC:START */
|
||||
const STORAGE_KEY = 'tpt.v1';
|
||||
const STORAGE_KEY = typeof window !== 'undefined' && window.TPTProfile ? 'tpt.user.' + window.TPTProfile.username : 'tpt.v1';
|
||||
const MEAL_TYPES = [['breakfast', 'Завтрак'], ['lunch', 'Обед'], ['dinner', 'Ужин'], ['snack', 'Перекус']];
|
||||
const WORKOUT_TYPES = [['strength', 'Силовая'], ['cardio', 'Кардио'], ['stretch', 'Растяжка'], ['other', 'Другое']];
|
||||
const GOALS = [['lose', 'Похудение'], ['maintain', 'Поддержание'], ['gain', 'Набор']];
|
||||
@ -143,7 +143,7 @@ function defaultData() {
|
||||
v: 1,
|
||||
settings: {
|
||||
goal: 'maintain', kcal: 2000, protein: 120, fat: 65, carbs: 230, water: 2000, workoutsPerWeek: 3,
|
||||
profile: { sex: 'm', age: 30, height: 175, weight: 75, activity: 1.375 },
|
||||
profile: { sex: null, age: null, height: null, weight: null, activity: null },
|
||||
plan: ['', '', '', '', '', '', ''], // план тренировок по дням недели, индекс = Date.getDay() (0 — воскресенье)
|
||||
reminders: { on: false, water: true, waterEvery: 2, dinner: true, dinnerTime: '20:00', workout: true, workoutTime: '18:00' },
|
||||
theme: 'auto', onboarded: false
|
||||
@ -420,6 +420,15 @@ function dueReminders(data, now, fired) {
|
||||
ХРАНЕНИЕ
|
||||
===================================================================== */
|
||||
let db = load();
|
||||
function applyPrivateProfile() {
|
||||
if (!window.TPTProfile) return;
|
||||
const personal = window.TPTProfile;
|
||||
db.settings.profile = { ...personal.profile, sex: personal.profile.sex === 'male' ? 'm' : 'f' };
|
||||
Object.assign(db.settings, suggestNorms(db.settings.goal, db.settings.profile), { onboarded: true });
|
||||
db.settings.kcal = personal.nutrition.calories;
|
||||
db.settings.protein = personal.nutrition.protein;
|
||||
}
|
||||
applyPrivateProfile();
|
||||
|
||||
function load() {
|
||||
try {
|
||||
@ -430,7 +439,8 @@ function load() {
|
||||
}
|
||||
let saveFailed = false;
|
||||
function save() {
|
||||
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(db)); saveFailed = false; }
|
||||
applyPrivateProfile();
|
||||
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(window.TPTProfile ? { ...db, settings: { ...db.settings, profile: defaultData().settings.profile } } : db)); saveFailed = false; }
|
||||
catch (e) { if (!saveFailed) toast('Не удалось сохранить: память браузера недоступна или заполнена.'); saveFailed = true; }
|
||||
}
|
||||
|
||||
@ -1177,19 +1187,12 @@ function goalChips(get, set) {
|
||||
|
||||
function viewSettings() {
|
||||
const s = db.settings;
|
||||
let goal = s.goal;
|
||||
const calc = calcFields(s.profile), norms = normFields(s);
|
||||
const calcNote = h('div', { class: 'small muted' });
|
||||
const themeSel = selectField('Тема', [['auto', 'Как в системе'], ['light', 'Светлая'], ['dark', 'Тёмная']], s.theme, ev => { s.theme = ev.target.value; save(); applyTheme(); });
|
||||
const fileIn = h('input', { type: 'file', accept: 'application/json,.json', hidden: true, onchange: onImport });
|
||||
const catalog = (title, items, del) => h('div', { class: 'card' }, h('h3', null, title),
|
||||
items.length ? items.map(x => h('div', { class: 'item' }, h('div', { class: 'main' }, x.label), h('button', { class: 'ghost icon', 'aria-label': 'Удалить ' + x.label, onclick: () => confirmBox('Убрать «' + x.label + '» из справочника? Записи в дневнике останутся.', 'Убрать', () => { del(x); save(); render(); }) }, '🗑'))) : h('div', { class: 'empty' }, 'Справочник пуст'));
|
||||
return h('div', null,
|
||||
h('div', { class: 'card' }, h('h3', null, 'Цель'), h('div', { style: 'margin-top:8px' }, goalChips(() => goal, k => { goal = k; }))),
|
||||
h('div', { class: 'card' }, h('h3', null, 'Калькулятор нормы'), h('p', { class: 'small muted' }, 'Формула Миффлина–Сан Жеора. Результат можно поправить вручную ниже.'), calc.el,
|
||||
h('button', { onclick: () => { const p = calc.read(); if (!p) return; const n = suggestNorms(goal, p); norms.fill(n); calcNote.textContent = 'Базовый обмен ' + mifflin(p).bmr + ' ккал, с активностью ' + mifflin(p).tdee + ' ккал. Нормы подставлены ниже — нажмите «Сохранить».'; } }, 'Рассчитать'), calcNote),
|
||||
h('div', { class: 'card' }, h('h3', null, 'Нормы в день'), norms.el,
|
||||
h('button', { class: 'primary', style: 'width:100%', onclick: () => { const n = norms.read(), p = calc.read(); if (!n || !p) return; Object.assign(s, n, { goal, profile: p }); save(); render(); toast('Настройки сохранены'); } }, 'Сохранить')),
|
||||
h('div', { class: 'card' }, h('a', { href: '/?lang=' + (new URLSearchParams(location.search).get('lang') || 'ru') }, window.TPTProfileText || '')),
|
||||
h('div', { class: 'card' }, themeSel),
|
||||
planCard(), remindersCard(), installCard(),
|
||||
h('div', { class: 'card stack' }, h('h3', null, 'Данные'),
|
||||
@ -1257,6 +1260,7 @@ function onImport(ev) {
|
||||
|
||||
/** Мастер первого запуска: шаг 1 — цель и данные, шаг 2 — нормы. */
|
||||
function startWizard() {
|
||||
if (window.TPTProfile) { applyPrivateProfile(); render(); return; }
|
||||
let goal = db.settings.goal;
|
||||
// Чужие числа по умолчанию не подставляем: поля пустые, в них только подсказка.
|
||||
const calc = calcFields(Object.assign({}, db.settings.profile, { age: null, height: null, weight: null }),
|
||||
@ -1293,7 +1297,7 @@ function checkReminders() {
|
||||
}
|
||||
setInterval(checkReminders, 30000);
|
||||
if ('serviceWorker' in navigator && /^https?:$/.test(location.protocol)) {
|
||||
navigator.serviceWorker.register('sw.js').then(r => { swReg = r; }).catch(() => { /* без офлайн-режима */ });
|
||||
navigator.serviceWorker.register('/sw.js').then(r => { swReg = r; }).catch(() => { /* без офлайн-режима */ });
|
||||
}
|
||||
|
||||
render();
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
## Context
|
||||
Основная ветка содержит шаблон без приложения и настроенных проверок. В общей папке работают другие сессии; реализация ведётся в отдельном worktree.
|
||||
В основной ветке теперь есть дневник и готовый план тренировок TPTIP-5/8, статический сервер TPTIP-6 и CommonJS-тесты. Реализация совместима с ними и ведётся в отдельном worktree.
|
||||
|
||||
## Goals / Non-Goals
|
||||
Цель: полностью рабочий приватный профиль и вычисляемое питание. Не переносить чужие незавершённые задачи.
|
||||
@ -15,7 +15,9 @@
|
||||
## Risks / Trade-offs
|
||||
- Один экземпляр сервера → SQLite достаточен, несколько реплик потребуют общей БД.
|
||||
- Потеря тома → регулярная резервная копия data/profile.sqlite средствами платформы; не удалять том при обновлении.
|
||||
- Будущая интеграция TPTIP-8 → сохранение server.js и index.html потребует разрешения конфликтов; собственные файлы профиля изолированы в profile/.
|
||||
- Интеграция дневника: production entry profile-server.mjs, /tracker требует входа, HTML получает только профиль владельца; script hashes разрешают существующий inline-скрипт. Старый статический server.js сохранён для совместимых тестов.
|
||||
- localStorage: дневник разделён по пользователям, измерения профиля при сохранении заменяются пустыми. Старое общее хранилище не импортируется автоматически. Офлайн-кэш содержит только публичные ресурсы, личные страницы и API требуют сети.
|
||||
- Профиль и нормы меняются только на /, прежний локальный калькулятор в настройках заменён ссылкой на приватный профиль. При фокусе дневник проверяет владельца и обновляет нормы.
|
||||
|
||||
## Migration Plan
|
||||
Создание таблиц при старте. Профили не заполняются фиктивными данными. Откат образа сохраняет том; резервная копия перед миграциями.
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
TPTIP-4 — https://peppa.telecom.quest — личные данные вместо подставленного роста и веса.
|
||||
|
||||
## Why
|
||||
В основной ветке только шаблон: сохранённого tasks.md и приложения нет. Нужен работающий личный профиль, на данных которого можно строить питание.
|
||||
Дневник использовал локальный профиль с подставленными измерениями. Нужен приватный профиль с обязательным вводом и общими для дневника расчётами.
|
||||
|
||||
## What Changes
|
||||
- Регистрация и вход с обязательными ростом и весом, без заполненных заранее значений.
|
||||
@ -15,6 +15,6 @@ TPTIP-4 — https://peppa.telecom.quest — личные данные вмест
|
||||
Нет.
|
||||
|
||||
## Impact
|
||||
Новый небольшой Node.js сервер, SQLite, браузерный интерфейс, проверки и контейнер. Ветки TPTIP-8 и TPTIP-6 ещё не в main; их изменения не включаются. Вне scope: журнал тренировок, фотографии, восстановление пароля, лечебные рекомендации.
|
||||
Новый небольшой Node.js сервер, SQLite, браузерный интерфейс, проверки и контейнер. Существующий дневник и план тренировок сохранены; /tracker использует данные приватного профиля. Вне scope: журнал тренировок, фотографии, восстановление пароля, лечебные рекомендации.
|
||||
|
||||
Открытые вопросы к PM: нет.
|
||||
|
||||
335
package-lock.json
generated
335
package-lock.json
generated
@ -14,6 +14,7 @@
|
||||
"esbuild": "^0.28.2",
|
||||
"eslint": "^10.15.0",
|
||||
"globals": "^17.14.0",
|
||||
"jsdom": "^31.0.1",
|
||||
"playwright": "^1.65.1"
|
||||
},
|
||||
"engines": {
|
||||
@ -614,6 +615,24 @@
|
||||
"node": "^20.19.0 || ^22.13.0 || >=24"
|
||||
}
|
||||
},
|
||||
"node_modules/@exodus/bytes": {
|
||||
"version": "1.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
|
||||
"integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@noble/hashes": "^1.8.0 || ^2.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@noble/hashes": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@humanfs/core": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
|
||||
@ -1312,6 +1331,33 @@
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/bcp-47": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz",
|
||||
"integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-alphabetical": "^2.0.0",
|
||||
"is-alphanumerical": "^2.0.0",
|
||||
"is-decimal": "^2.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/bcp-47-match": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz",
|
||||
"integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.13",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz",
|
||||
@ -1353,6 +1399,20 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/data-urls": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz",
|
||||
"integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-mimetype": "^5.0.0",
|
||||
"whatwg-url": "^17.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.14.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
@ -1371,6 +1431,13 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js": {
|
||||
"version": "10.6.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
|
||||
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/deep-is": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
|
||||
@ -1390,6 +1457,19 @@
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/entities": {
|
||||
"version": "9.0.0",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz",
|
||||
"integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
|
||||
@ -1730,6 +1810,19 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/html-encoding-sniffer": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz",
|
||||
"integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@exodus/bytes": "^1.15.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
@ -1750,6 +1843,43 @@
|
||||
"node": ">=0.8.19"
|
||||
}
|
||||
},
|
||||
"node_modules/is-alphabetical": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
|
||||
"integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/is-alphanumerical": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
|
||||
"integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"is-alphabetical": "^2.0.0",
|
||||
"is-decimal": "^2.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/is-decimal": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
|
||||
"integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wooorm"
|
||||
}
|
||||
},
|
||||
"node_modules/is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
@ -1773,6 +1903,13 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-potential-custom-element-name": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
|
||||
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
@ -1780,6 +1917,44 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/jsdom": {
|
||||
"version": "31.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz",
|
||||
"integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@exodus/bytes": "^1.16.0",
|
||||
"bcp-47": "^2.1.2",
|
||||
"bcp-47-match": "^2.0.3",
|
||||
"data-urls": "^8.0.0",
|
||||
"decimal.js": "^10.6.0",
|
||||
"html-encoding-sniffer": "^7.0.0",
|
||||
"is-potential-custom-element-name": "^1.0.1",
|
||||
"lru-cache": "^11.5.3",
|
||||
"parse5": "^8.1.0",
|
||||
"parse5-parser-stream": "^8.1.0",
|
||||
"saxes": "^6.0.0",
|
||||
"tough-cookie": "^6.0.2",
|
||||
"undici": "^8.12.3",
|
||||
"w3c-xmlserializer": "^6.0.0",
|
||||
"webidl-conversions": "^8.0.1",
|
||||
"whatwg-mimetype": "^5.0.0",
|
||||
"whatwg-url": "^17.3.0",
|
||||
"xml-name-validator": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@napi-rs/canvas": "^1.0.13"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@napi-rs/canvas": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/json-schema-traverse": {
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
|
||||
@ -1977,6 +2152,32 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/parse5": {
|
||||
"version": "8.1.1",
|
||||
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz",
|
||||
"integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"entities": "^9.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/parse5-parser-stream": {
|
||||
"version": "8.1.1",
|
||||
"resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz",
|
||||
"integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"parse5": "^8.1.1"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
@ -2082,6 +2283,19 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"xmlchars": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=v12.22.7"
|
||||
}
|
||||
},
|
||||
"node_modules/sentry": {
|
||||
"version": "0.49.0",
|
||||
"resolved": "https://registry.npmjs.org/sentry/-/sentry-0.49.0.tgz",
|
||||
@ -2117,6 +2331,52 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/tldts": {
|
||||
"version": "7.5.4",
|
||||
"resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.4.tgz",
|
||||
"integrity": "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tldts-core": "^7.5.4"
|
||||
},
|
||||
"bin": {
|
||||
"tldts": "bin/cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/tldts-core": {
|
||||
"version": "7.5.4",
|
||||
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.4.tgz",
|
||||
"integrity": "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tough-cookie": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz",
|
||||
"integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tldts": "^7.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/tr46": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz",
|
||||
"integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"punycode": "^2.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.14.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
@ -2130,6 +2390,16 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/undici": {
|
||||
"version": "8.12.4",
|
||||
"resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz",
|
||||
"integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=22.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uri-js": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
@ -2140,12 +2410,60 @@
|
||||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/w3c-xmlserializer": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz",
|
||||
"integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xml-name-validator": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/web-vitals": {
|
||||
"version": "6.2.3",
|
||||
"resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.2.3.tgz",
|
||||
"integrity": "sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
|
||||
"integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-mimetype": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
|
||||
"integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "17.3.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz",
|
||||
"integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@exodus/bytes": "^1.16.0",
|
||||
"tr46": "^7.0.0",
|
||||
"webidl-conversions": "^8.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.14.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
@ -2172,6 +2490,23 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlchars": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
|
||||
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
|
||||
11
package.json
11
package.json
@ -1,15 +1,15 @@
|
||||
{
|
||||
"name": "tptip-profile",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"type": "commonjs",
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"start": "node profile-server.mjs",
|
||||
"lint": "eslint .",
|
||||
"test": "node --test tests/*.test.js",
|
||||
"build": "esbuild profile/telemetry-source.js --bundle --format=esm --minify --outfile=profile/telemetry.js && node --check server.js && node --check profile/app.js"
|
||||
"test": "env -u NODE_TEST_CONTEXT node --test tests/*.test.js tests/*.test.mjs",
|
||||
"build": "esbuild profile/telemetry-source.js --bundle --format=esm --minify --outfile=profile/telemetry.js && node --check profile-server.mjs && node --input-type=module --check < profile/app.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sentry/browser": "^11.13.0",
|
||||
@ -20,6 +20,7 @@
|
||||
"esbuild": "^0.28.2",
|
||||
"eslint": "^10.15.0",
|
||||
"globals": "^17.14.0",
|
||||
"playwright": "^1.65.1"
|
||||
"playwright": "^1.65.1",
|
||||
"jsdom": "^31.0.1"
|
||||
}
|
||||
}
|
||||
|
||||
88
profile-server.mjs
Normal file
88
profile-server.mjs
Normal file
@ -0,0 +1,88 @@
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ProfileService, InputError } from './profile/service.mjs';
|
||||
if (process.env.SENTRY_DSN) Sentry.init({dsn:process.env.SENTRY_DSN,release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev',sendDefaultPii:false,beforeSend(event){ delete event.request; delete event.user; return event; }});
|
||||
const root = fileURLToPath(new URL('.',import.meta.url));
|
||||
const files = new Map([['/profile/tracker-guard.js',['profile/tracker-guard.js','text/javascript']],['/gym-plan.i18n.js',['gym-plan.i18n.js','text/javascript']],['/manifest.webmanifest',['manifest.webmanifest','application/manifest+json']],['/sw.js',['sw.js','text/javascript']],['/icon.svg',['icon.svg','image/svg+xml']],['/about.html',['about.html','text/html']],['/about.i18n.json',['about.i18n.json','application/json']],['/',['profile/index.html','text/html']],['/profile/app.js',['profile/app.js','text/javascript']],['/profile/telemetry.js',['profile/telemetry.js','text/javascript']],['/profile/style.css',['profile/style.css','text/css']],['/profile/i18n.json',['profile/i18n.json','application/json']]]);
|
||||
export function createApp({database,secure = process.env.NODE_ENV === 'production'} = {}) {
|
||||
if (!database) mkdirSync(process.env.DATA_DIR || resolve(root,'data'),{recursive:true,mode:0o700});
|
||||
const service = new ProfileService(database || resolve(process.env.DATA_DIR || resolve(root,'data'),'profile.sqlite'));
|
||||
const attempts = new Map();
|
||||
let telemetryOrigin = '';
|
||||
if (process.env.PUBLIC_SENTRY_DSN) {
|
||||
const url = new URL(process.env.PUBLIC_SENTRY_DSN);
|
||||
if (url.protocol === 'https:') telemetryOrigin = url.origin;
|
||||
}
|
||||
const server = createServer(async (req,res) => {
|
||||
res.setHeader('Cache-Control','no-store');
|
||||
res.setHeader('X-Content-Type-Options','nosniff');
|
||||
res.setHeader('Referrer-Policy','no-referrer');
|
||||
res.setHeader('Content-Security-Policy',`default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self' ${telemetryOrigin}; frame-ancestors 'none'; form-action 'self'; base-uri 'none'`);
|
||||
const send = (status,data) => {res.writeHead(status,{'Content-Type':'application/json; charset=utf-8'});res.end(JSON.stringify(data));};
|
||||
try {
|
||||
const path = new URL(req.url,'http://localhost').pathname;
|
||||
if (req.method === 'GET' && path === '/healthz') return send(200,{ok:true});
|
||||
const token = req.headers.cookie?.match(/(?:^|;\s*)session=([a-f0-9]{64})(?:;|$)/)?.[1];
|
||||
const htmlPolicy = html => {
|
||||
const hashes = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => "'sha256-"+createHash('sha256').update(m[1]).digest('base64')+"'").join(' ');
|
||||
res.setHeader('Content-Security-Policy',`default-src 'self'; script-src 'self' ${hashes}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' ${telemetryOrigin}; frame-ancestors 'none'; form-action 'self'; base-uri 'none'`);
|
||||
};
|
||||
if (req.method === 'GET' && ['/tracker','/index.html'].includes(path)) {
|
||||
let personal;
|
||||
try { personal=service.read(token); } catch { res.writeHead(302,{Location:'/'});res.end();return; }
|
||||
const lang = new URL(req.url,'http://localhost').searchParams.get('lang');
|
||||
const dictionaries = JSON.parse(await readFile(resolve(root,'profile/i18n.json'),'utf8'));
|
||||
const text = (dictionaries[lang] || dictionaries.ru).profile;
|
||||
let html = await readFile(resolve(root,'index.html'),'utf8');
|
||||
html = html.replace('<script>',`<script>window.TPTProfile=${JSON.stringify(personal)};window.TPTProfileText=${JSON.stringify(text)};</script><script>`);
|
||||
html = html.replace('</body>','<script type="module" src="/profile/tracker-guard.js"></script></body>');
|
||||
htmlPolicy(html);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);return;
|
||||
}
|
||||
if (req.method === 'GET' && files.has(path)) {
|
||||
const [file,type] = files.get(path);
|
||||
const content = await readFile(resolve(root,file));
|
||||
if (type === 'text/html') htmlPolicy(content.toString());
|
||||
res.writeHead(200,{'Content-Type':type+'; charset=utf-8'});res.end(content);return;
|
||||
}
|
||||
if (req.method === 'GET' && path === '/api/telemetry') return send(200,{dsn:process.env.PUBLIC_SENTRY_DSN || '',release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev'});
|
||||
if (!path.startsWith('/api/')) throw new InputError('notFound',404);
|
||||
|
||||
if (req.method === 'GET' && path === '/api/profile') return send(200,service.read(token));
|
||||
if (!['POST','PUT'].includes(req.method)) throw new InputError('notFound',404);
|
||||
if (!req.headers.origin || new URL(req.headers.origin).host !== req.headers.host || !['http:','https:'].includes(new URL(req.headers.origin).protocol)) throw new InputError('request',403);
|
||||
if (!req.headers['content-type']?.startsWith('application/json')) throw new InputError('request',415);
|
||||
let body = '';
|
||||
for await (const chunk of req) {body += chunk; if (Buffer.byteLength(body)>8192) throw new InputError('request',413);}
|
||||
let input; try {input = JSON.parse(body);} catch {throw new InputError('request');}
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new InputError('request');
|
||||
if (req.method === 'POST' && ['/api/register','/api/login'].includes(path)) {
|
||||
const now = Date.now();
|
||||
for (const [key,limit] of attempts) if (limit.until<now) attempts.delete(key);
|
||||
const ip = req.socket.remoteAddress;
|
||||
const limit = attempts.get(ip) || {count:0,until:now+60000};
|
||||
if (++limit.count>20) throw new InputError('rate',429);
|
||||
attempts.set(ip,limit);
|
||||
const session = await service.authenticate(input,path === '/api/register');
|
||||
res.setHeader('Set-Cookie',`session=${session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=604800${secure ? '; Secure' : ''}`);
|
||||
return send(200,service.read(session));
|
||||
}
|
||||
if (req.method === 'PUT' && path === '/api/profile') return send(200,service.update(token,input));
|
||||
if (req.method === 'POST' && path === '/api/logout') {
|
||||
service.logout(token);res.setHeader('Set-Cookie',`session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${secure ? '; Secure' : ''}`);return send(200,{ok:true});
|
||||
}
|
||||
throw new InputError('notFound',404);
|
||||
} catch(error) {
|
||||
if (!(error instanceof InputError)) Sentry.captureException(error);
|
||||
send(error instanceof InputError ? error.status : 500,{error:error instanceof InputError ? error.message : 'server'});
|
||||
}
|
||||
});
|
||||
server.requestTimeout = 15000;
|
||||
server.on('close',() => service.close());
|
||||
return server;
|
||||
}
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) createApp().listen(Number(process.env.PORT || 3000),'0.0.0.0');
|
||||
@ -1,6 +1,22 @@
|
||||
import { initTelemetry } from '/profile/telemetry.js';
|
||||
initTelemetry().catch(() => {});
|
||||
const translations = await fetch('/profile/i18n.json').then(r=>r.json());
|
||||
// Activate the network-only policy before any request for personal information.
|
||||
let privateStorageReady = true;
|
||||
if ('serviceWorker' in navigator) {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register('/sw.js',{updateViaCache:'none'});
|
||||
await registration.update();
|
||||
const worker = registration.installing || registration.waiting;
|
||||
if (worker && worker.state !== 'activated') await new Promise((resolve,reject)=>{
|
||||
worker.addEventListener('statechange',()=>{if(worker.state==='activated')resolve();if(worker.state==='redundant')reject(new Error());});
|
||||
});
|
||||
} catch {
|
||||
privateStorageReady = false;
|
||||
if ('caches' in window) for (const key of await caches.keys()) await caches.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
let lang = new URLSearchParams(location.search).get('lang') || navigator.language.slice(0,2);
|
||||
if (!translations[lang]) lang = 'ru';
|
||||
let current, mode = 'login', message = '';
|
||||
@ -59,7 +75,7 @@ function render() {
|
||||
finally {form.removeAttribute('aria-busy');for (const b of form.querySelectorAll('button')) b.disabled=false;}
|
||||
});
|
||||
if (!current) form.querySelector('.actions').append(el('button',{type:'button',onclick:()=>{mode=mode==='login'?'register':'login';message='';render();}},t(mode==='login'?'register':'login')));
|
||||
else form.querySelector('.actions').append(el('button',{type:'button',onclick:async()=>{
|
||||
else form.querySelector('.actions').append(el('a',{class:'btn',href:'/tracker?lang='+lang},t('tracker')),el('button',{type:'button',onclick:async()=>{
|
||||
try{await api('logout','POST',{});current=undefined;message='';render();}catch(err){error.textContent=errorText(err.message);}
|
||||
}},t('logout')));
|
||||
root.append(form,el('p',{class:'hint'},t('privacy')));
|
||||
@ -69,5 +85,12 @@ function render() {
|
||||
}
|
||||
}
|
||||
root.textContent=t('loading');
|
||||
try {current=await api('profile');}catch(error){if(error.status!==401)message=errorText('server');}
|
||||
try {if (!privateStorageReady) throw new Error('server'); current=await api('profile');}catch(error){if(error.status!==401)message=errorText('server');}
|
||||
render();
|
||||
|
||||
addEventListener('pageshow',event=>{if(event.persisted) location.reload();});
|
||||
addEventListener('focus',async()=>{
|
||||
if (!current) return;
|
||||
try {current=await api('profile');render();}
|
||||
catch(error){if(error.status===401){current=undefined;message=errorText('signin');render();}}
|
||||
});
|
||||
|
||||
@ -54,7 +54,8 @@
|
||||
"server": "Не удалось сохранить данные. Попробуйте ещё раз.",
|
||||
"request": "Не удалось выполнить действие. Обновите страницу и повторите.",
|
||||
"notFound": "Страница не найдена. Откройте главную страницу."
|
||||
}
|
||||
},
|
||||
"tracker": "Открыть дневник и тренировки"
|
||||
},
|
||||
"kk": {
|
||||
"app": "Сіздің деректеріңізге сай тамақтану",
|
||||
@ -111,7 +112,8 @@
|
||||
"server": "Деректер сақталмады. Қайта көріңіз.",
|
||||
"request": "Әрекет орындалмады. Бетті жаңартып, қайталаңыз.",
|
||||
"notFound": "Бет табылмады. Басты бетті ашыңыз."
|
||||
}
|
||||
},
|
||||
"tracker": "Күнделік пен жаттығуларды ашу"
|
||||
},
|
||||
"en": {
|
||||
"app": "Nutrition from your data",
|
||||
@ -168,6 +170,7 @@
|
||||
"server": "Could not save your details. Please try again.",
|
||||
"request": "The action failed. Refresh the page and try again.",
|
||||
"notFound": "Page not found. Open the home page."
|
||||
}
|
||||
},
|
||||
"tracker": "Open diary and workouts"
|
||||
}
|
||||
}
|
||||
|
||||
@ -1 +1,2 @@
|
||||
:root{font:16px/1.55 system-ui,sans-serif;color:#18332c;background:#eff4ef;color-scheme:light}*{box-sizing:border-box}body{margin:0}main{max-width:960px;margin:auto;padding:24px}header{display:flex;align-items:center;justify-content:space-between;gap:16px}h1{font-size:clamp(2rem,6vw,3rem);line-height:1.12;margin:28px 0 16px}h2{font-size:1.3rem}p{max-width:64ch;color:#4a6258}.card{background:#fff;border:1px solid #d5dfd5;border-radius:20px;padding:24px;margin:20px 0;box-shadow:0 8px 30px #18332c08}.grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}label{display:flex;flex-direction:column;gap:6px}input,select,button{font:inherit;min-height:46px;padding:10px 14px;border:1px solid #aabeb1;border-radius:9px;background:white;color:inherit}button{cursor:pointer}button.primary{background:#205c47;color:white;border-color:#205c47}button:disabled{opacity:.6;cursor:wait}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #c38824;outline-offset:3px}.actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:22px}.error{color:#9e281c;min-height:1.5em}.hint{font-size:.85rem;color:#52675b}.stats{display:grid;grid-template-columns:1fr 1fr;gap:16px}.stat{background:#edf3e8;border-radius:12px;padding:18px}.stat strong{display:block;font-size:2rem}.meal{border-top:1px solid #d5dfd5;padding:16px 0}.meal h3{margin:0 0 6px;font-size:1rem}.lang{max-width:165px}.eyebrow{letter-spacing:.12em;font-size:.8rem;font-weight:700;color:#496348}.notice{background:#fff5dd;padding:16px;border-radius:12px}form[aria-busy=true]{opacity:.7}@media(max-width:600px){main{padding:16px}.card{padding:18px}.grid{grid-template-columns:1fr}header{align-items:flex-start}.stats{gap:8px}.stat{padding:12px}.stat strong{font-size:1.6rem}}
|
||||
.btn{display:inline-block;padding:10px 14px;border:1px solid #aabeb1;border-radius:9px;color:inherit;text-decoration:none;min-height:46px}
|
||||
|
||||
16
profile/tracker-guard.js
Normal file
16
profile/tracker-guard.js
Normal file
@ -0,0 +1,16 @@
|
||||
import { initTelemetry } from '/profile/telemetry.js';
|
||||
initTelemetry().catch(() => {});
|
||||
async function refreshProfile() {
|
||||
try {
|
||||
const response = await fetch('/api/profile', {cache:'no-store'});
|
||||
if (!response.ok) { document.body.replaceChildren(); location.replace('/'); return; }
|
||||
const personal = await response.json();
|
||||
if (personal.username !== window.TPTProfile.username) { document.body.replaceChildren(); location.replace('/'); return; }
|
||||
window.TPTProfile = personal;
|
||||
window.applyPrivateProfile();
|
||||
window.render();
|
||||
} catch { /* Keep the current view during a temporary connection failure. */ }
|
||||
}
|
||||
addEventListener('focus',refreshProfile);
|
||||
addEventListener('pageshow',event => {if(event.persisted) refreshProfile();});
|
||||
document.addEventListener('visibilitychange',()=>{if(!document.hidden) refreshProfile();});
|
||||
102
server.js
102
server.js
@ -1,69 +1,37 @@
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ProfileService, InputError } from './profile/service.js';
|
||||
if (process.env.SENTRY_DSN) Sentry.init({dsn:process.env.SENTRY_DSN,release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev',sendDefaultPii:false,beforeSend(event){ delete event.request; delete event.user; return event; }});
|
||||
const root = fileURLToPath(new URL('.',import.meta.url));
|
||||
const files = new Map([['/',['profile/index.html','text/html']],['/profile/app.js',['profile/app.js','text/javascript']],['/profile/telemetry.js',['profile/telemetry.js','text/javascript']],['/profile/style.css',['profile/style.css','text/css']],['/profile/i18n.json',['profile/i18n.json','application/json']]]);
|
||||
export function createApp({database,secure = process.env.NODE_ENV === 'production'} = {}) {
|
||||
if (!database) mkdirSync(process.env.DATA_DIR || resolve(root,'data'),{recursive:true,mode:0o700});
|
||||
const service = new ProfileService(database || resolve(process.env.DATA_DIR || resolve(root,'data'),'profile.sqlite'));
|
||||
const attempts = new Map();
|
||||
let telemetryOrigin = '';
|
||||
if (process.env.PUBLIC_SENTRY_DSN) {
|
||||
const url = new URL(process.env.PUBLIC_SENTRY_DSN);
|
||||
if (url.protocol === 'https:') telemetryOrigin = url.origin;
|
||||
}
|
||||
const server = createServer(async (req,res) => {
|
||||
res.setHeader('Cache-Control','no-store');
|
||||
res.setHeader('X-Content-Type-Options','nosniff');
|
||||
res.setHeader('Referrer-Policy','no-referrer');
|
||||
res.setHeader('Content-Security-Policy',`default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self' ${telemetryOrigin}; frame-ancestors 'none'; form-action 'self'; base-uri 'none'`);
|
||||
const send = (status,data) => {res.writeHead(status,{'Content-Type':'application/json; charset=utf-8'});res.end(JSON.stringify(data));};
|
||||
try {
|
||||
const path = new URL(req.url,'http://localhost').pathname;
|
||||
if (req.method === 'GET' && path === '/healthz') return send(200,{ok:true});
|
||||
if (req.method === 'GET' && files.has(path)) {
|
||||
const [file,type] = files.get(path);
|
||||
res.writeHead(200,{'Content-Type':type+'; charset=utf-8'});res.end(await readFile(resolve(root,file)));return;
|
||||
}
|
||||
if (req.method === 'GET' && path === '/api/telemetry') return send(200,{dsn:process.env.PUBLIC_SENTRY_DSN || '',release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev'});
|
||||
if (!path.startsWith('/api/')) throw new InputError('notFound',404);
|
||||
const token = req.headers.cookie?.match(/(?:^|;\s*)session=([a-f0-9]{64})(?:;|$)/)?.[1];
|
||||
if (req.method === 'GET' && path === '/api/profile') return send(200,service.read(token));
|
||||
if (!['POST','PUT'].includes(req.method)) throw new InputError('notFound',404);
|
||||
if (!req.headers.origin || new URL(req.headers.origin).host !== req.headers.host || !['http:','https:'].includes(new URL(req.headers.origin).protocol)) throw new InputError('request',403);
|
||||
if (!req.headers['content-type']?.startsWith('application/json')) throw new InputError('request',415);
|
||||
let body = '';
|
||||
for await (const chunk of req) {body += chunk; if (Buffer.byteLength(body)>8192) throw new InputError('request',413);}
|
||||
let input; try {input = JSON.parse(body);} catch {throw new InputError('request');}
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new InputError('request');
|
||||
if (req.method === 'POST' && ['/api/register','/api/login'].includes(path)) {
|
||||
const now = Date.now();
|
||||
for (const [key,limit] of attempts) if (limit.until<now) attempts.delete(key);
|
||||
const ip = req.socket.remoteAddress;
|
||||
const limit = attempts.get(ip) || {count:0,until:now+60000};
|
||||
if (++limit.count>20) throw new InputError('rate',429);
|
||||
attempts.set(ip,limit);
|
||||
const session = await service.authenticate(input,path === '/api/register');
|
||||
res.setHeader('Set-Cookie',`session=${session}; HttpOnly; SameSite=Strict; Path=/; Max-Age=604800${secure ? '; Secure' : ''}`);
|
||||
return send(200,service.read(session));
|
||||
}
|
||||
if (req.method === 'PUT' && path === '/api/profile') return send(200,service.update(token,input));
|
||||
if (req.method === 'POST' && path === '/api/logout') {
|
||||
service.logout(token);res.setHeader('Set-Cookie',`session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${secure ? '; Secure' : ''}`);return send(200,{ok:true});
|
||||
}
|
||||
throw new InputError('notFound',404);
|
||||
} catch(error) {
|
||||
if (!(error instanceof InputError)) Sentry.captureException(error);
|
||||
send(error instanceof InputError ? error.status : 500,{error:error instanceof InputError ? error.message : 'server'});
|
||||
}
|
||||
// Мини-сервер стенда (TPTIP-6): слушает $PORT, /healthz → 200, отдаёт файлы приложения по белому списку.
|
||||
// Английской страницы-заглушки нет (TPTIP-11): по ссылке всегда открывается трекер.
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const DIR = process.env.APP_DIR || __dirname;
|
||||
const FILES = {
|
||||
'/gym-plan.i18n.js': ['gym-plan.i18n.js', 'text/javascript; charset=utf-8'],
|
||||
'/': ['index.html', 'text/html; charset=utf-8'],
|
||||
'/index.html': ['index.html', 'text/html; charset=utf-8'],
|
||||
'/manifest.webmanifest': ['manifest.webmanifest', 'application/manifest+json'],
|
||||
'/sw.js': ['sw.js', 'text/javascript; charset=utf-8'],
|
||||
'/icon.svg': ['icon.svg', 'image/svg+xml']
|
||||
};
|
||||
|
||||
function send(res, f) {
|
||||
fs.readFile(path.join(DIR, f[0]), (err, buf) => {
|
||||
if (err && err.code === 'ENOENT') { res.writeHead(404); return res.end('not found'); }
|
||||
if (err) { res.writeHead(500); return res.end('error'); }
|
||||
res.writeHead(200, { 'content-type': f[1], 'cache-control': 'no-cache' });
|
||||
res.end(buf);
|
||||
});
|
||||
server.requestTimeout = 15000;
|
||||
server.on('close',() => service.close());
|
||||
return server;
|
||||
}
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) createApp().listen(Number(process.env.PORT || 3000),'0.0.0.0');
|
||||
|
||||
function createServer() {
|
||||
return http.createServer((req, res) => {
|
||||
const url = (req.url || '/').split('?')[0];
|
||||
if (url === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain' }); return res.end('ok'); }
|
||||
const f = FILES[url];
|
||||
if (!f) { res.writeHead(404); return res.end('not found'); }
|
||||
send(res, f);
|
||||
});
|
||||
}
|
||||
|
||||
if (require.main === module) createServer().listen(Number(process.env.PORT) || 3000, '0.0.0.0');
|
||||
module.exports = { createServer };
|
||||
|
||||
10
sw.js
10
sw.js
@ -1,16 +1,16 @@
|
||||
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
||||
const CACHE = 'tpt-v4-wizard';
|
||||
const FILES = ['./', 'index.html', 'gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg'];
|
||||
// Офлайн-кэш только публичных ресурсов; личные страницы и ответы требуют сети.
|
||||
const CACHE = 'tpt-v5-private-profile-wizard';
|
||||
const FILES = ['gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg'];
|
||||
self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(FILES)).then(() => self.skipWaiting())); });
|
||||
self.addEventListener('activate', e => {
|
||||
e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
|
||||
});
|
||||
self.addEventListener('fetch', e => {
|
||||
if (e.request.method !== 'GET') return;
|
||||
if (e.request.method !== 'GET' || !FILES.some(f => new URL(e.request.url).pathname === '/' + f)) return;
|
||||
e.respondWith(fetch(e.request).then(r => {
|
||||
const copy = r.clone();
|
||||
caches.open(CACHE).then(c => c.put(e.request, copy));
|
||||
return r;
|
||||
}).catch(() => caches.match(e.request).then(m => m || caches.match('index.html'))));
|
||||
}).catch(() => caches.match(e.request).then(m => m || Response.error())));
|
||||
});
|
||||
self.addEventListener('notificationclick', e => { e.notification.close(); e.waitUntil(self.clients.openWindow('./')); });
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import {chromium} from 'playwright';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createApp} from '../server.js';
|
||||
import {createApp} from '../profile-server.mjs';
|
||||
import {writeFile} from 'node:fs/promises';
|
||||
const server=createApp({database:':memory:'});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
@ -25,6 +25,15 @@ try {
|
||||
assert.notEqual(await page.locator('.stats').innerText(),before);
|
||||
await page.reload();await page.waitForSelector('[name=weight]');assert.equal(await page.locator('[name=weight]').inputValue(),'84');
|
||||
await page.screenshot({path:'/tmp/tptip4-mobile.png',fullPage:true});
|
||||
await page.getByRole('link',{name:'Открыть дневник и тренировки'}).click();
|
||||
await page.getByRole('button',{name:'План тренировок',exact:true}).waitFor();
|
||||
assert.match(await page.locator('#view').innerText(),/2506/);
|
||||
await page.getByRole('button',{name:'План тренировок',exact:true}).click();
|
||||
assert.equal(await page.locator('#view section').count(),4);
|
||||
const cacheURLs = await page.evaluate(async()=>{const out=[];for(const key of await caches.keys())for(const req of await (await caches.open(key)).keys())out.push(new URL(req.url).pathname);return out;});
|
||||
assert.ok(cacheURLs.every(path=>!['/','/tracker','/index.html'].includes(path)&&!path.startsWith('/api/')));
|
||||
await page.goto(origin+'/?lang=ru');await page.waitForSelector('[name=weight]');
|
||||
|
||||
const visible={ru:await page.locator('main').innerText()};
|
||||
for(const lang of ['kk','en']){
|
||||
await page.locator('.lang').selectOption(lang);assert.equal(await page.locator('html').getAttribute('lang'),lang);
|
||||
@ -35,6 +44,7 @@ try {
|
||||
await page.getByRole('button',{name:'Sign out',exact:true}).click();await page.getByRole('heading',{name:'Start with your details'}).waitFor();
|
||||
assert.equal(await page.locator('[name=weight]').inputValue(),'');
|
||||
assert.equal((await page.request.get(origin+'/api/profile')).status(),401);
|
||||
await page.goto(origin+'/tracker');await page.getByRole('heading',{name:'Start with your details'}).waitFor();
|
||||
visible.auth = await page.locator('main').innerText();
|
||||
await writeFile('/tmp/tptip4-visible-texts.json',JSON.stringify(visible,null,2));
|
||||
assert.deepEqual(errors,[]);console.log('Browser checks passed: blank fields, validation, registration, recalculation, reload, logout, ru/kk/en, mobile/desktop.');
|
||||
@ -3,8 +3,8 @@ import assert from 'node:assert/strict';
|
||||
import {mkdtemp,rm} from 'node:fs/promises';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {createApp} from '../server.js';
|
||||
import {validateProfile,ProfileService,nutrition} from '../profile/service.js';
|
||||
import {createApp} from '../profile-server.mjs';
|
||||
import {validateProfile,ProfileService,nutrition} from '../profile/service.mjs';
|
||||
const profile = {height:182,weight:81,age:32,sex:'male',activity:1.375};
|
||||
const account = {username:'anna',password:'a-long-private-password',...profile};
|
||||
test('Пустое или неверное измерение; границы диапазонов',() => {
|
||||
Loading…
Reference in New Issue
Block a user