TPTIP-4: серверный профиль и изоляция пользователей
This commit is contained in:
parent
df23da4fce
commit
b859eed8fc
3
eslint.config.js
Normal file
3
eslint.config.js
Normal file
@ -0,0 +1,3 @@
|
||||
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/**']}];
|
||||
2
openspec/changes/tptip-4-private-profile/.openspec.yaml
Normal file
2
openspec/changes/tptip-4-private-profile/.openspec.yaml
Normal file
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-17
|
||||
21
openspec/changes/tptip-4-private-profile/design.md
Normal file
21
openspec/changes/tptip-4-private-profile/design.md
Normal file
@ -0,0 +1,21 @@
|
||||
## Context
|
||||
Основная ветка содержит шаблон без приложения и настроенных проверок. В общей папке работают другие сессии; реализация ведётся в отдельном worktree.
|
||||
|
||||
## Goals / Non-Goals
|
||||
Цель: полностью рабочий приватный профиль и вычисляемое питание. Не переносить чужие незавершённые задачи.
|
||||
|
||||
## Decisions
|
||||
- Node.js 24 LTS и встроенный SQLite: транзакции, изоляция пользователей и минимум зависимостей. Файл в DATA_DIR на постоянном томе; не localStorage.
|
||||
- Пароль: scrypt с индивидуальной солью; вход по имени и паролю, непрозрачная серверная сессия, HttpOnly SameSite=Strict cookie, срок 7 дней. Проверять Origin у мутаций, ограничить размер тела и частоту попыток.
|
||||
- При регистрации и каждом входе рост 100–250 см и вес 25–350 кг обязательны. Возраст 18–100, пол для формулы и активность пользователь выбирает самостоятельно, без предустановок. Формула Mifflin–St Jeor с коэффициентом активности; белок 1.6 г/кг. Это ориентир для здоровых взрослых, не медицинское назначение.
|
||||
- GET/PUT /api/profile не принимают идентификатор другого пользователя. Меню вычисляется на сервере из сохранённого профиля при каждом чтении, порции масштабируются под калории. Пароли и измерения не логируются.
|
||||
- Все тексты и названия блюд в i18n.json (ru/kk/en), ключи ошибок переводит клиент. Статические файлы доступны строго по белому списку.
|
||||
- Sentry включается только при DSN, с release/environment и без PII.
|
||||
|
||||
## Risks / Trade-offs
|
||||
- Один экземпляр сервера → SQLite достаточен, несколько реплик потребуют общей БД.
|
||||
- Потеря тома → регулярная резервная копия data/profile.sqlite средствами платформы; не удалять том при обновлении.
|
||||
- Будущая интеграция TPTIP-8 → сохранение server.js и index.html потребует разрешения конфликтов; собственные файлы профиля изолированы в profile/.
|
||||
|
||||
## Migration Plan
|
||||
Создание таблиц при старте. Профили не заполняются фиктивными данными. Откат образа сохраняет том; резервная копия перед миграциями.
|
||||
20
openspec/changes/tptip-4-private-profile/proposal.md
Normal file
20
openspec/changes/tptip-4-private-profile/proposal.md
Normal file
@ -0,0 +1,20 @@
|
||||
TPTIP-4 — https://peppa.telecom.quest — личные данные вместо подставленного роста и веса.
|
||||
|
||||
## Why
|
||||
В основной ветке только шаблон: сохранённого tasks.md и приложения нет. Нужен работающий личный профиль, на данных которого можно строить питание.
|
||||
|
||||
## What Changes
|
||||
- Регистрация и вход с обязательными ростом и весом, без заполненных заранее значений.
|
||||
- Закрытый профиль с редактированием и пересчётом нормы и порций меню.
|
||||
- Проверки значений и тексты на русском, казахском и английском.
|
||||
|
||||
## Capabilities
|
||||
### New Capabilities
|
||||
- `private-profile`: авторизация, личные измерения, расчёт питания.
|
||||
### Modified Capabilities
|
||||
Нет.
|
||||
|
||||
## Impact
|
||||
Новый небольшой Node.js сервер, SQLite, браузерный интерфейс, проверки и контейнер. Ветки TPTIP-8 и TPTIP-6 ещё не в main; их изменения не включаются. Вне scope: журнал тренировок, фотографии, восстановление пароля, лечебные рекомендации.
|
||||
|
||||
Открытые вопросы к PM: нет.
|
||||
@ -0,0 +1,44 @@
|
||||
## Purpose
|
||||
Личный профиль хранит введённые пользователем измерения и позволяет рассчитывать питание без подставленных данных.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Обязательные измерения
|
||||
Система SHALL требовать рост 100–250 см и вес 25–350 кг при регистрации и входе, без значений по умолчанию, с проверками в браузере и на сервере.
|
||||
|
||||
#### Scenario: Регистрация с измерениями
|
||||
- **GIVEN** новый пользователь открыл регистрацию
|
||||
- **WHEN** он вводит рост 182, вес 81 и остальные обязательные данные
|
||||
- **THEN** открывается его профиль с ростом 182 и весом 81
|
||||
|
||||
#### Scenario: Пустое или неверное измерение
|
||||
- **GIVEN** пользователь открыл вход
|
||||
- **WHEN** он оставляет рост пустым или вводит вес «abc»
|
||||
- **THEN** продолжить нельзя и показана подсказка исправить данные
|
||||
|
||||
### Requirement: Изменение и расчёт
|
||||
Система SHALL сохранять изменения профиля и вычислять норму калорий, белка и порции меню по введённым данным при каждом чтении; без полного профиля расчёт недоступен.
|
||||
|
||||
#### Scenario: Пересчёт после изменения
|
||||
- **GIVEN** пользователь вошёл с ростом 182 и весом 81
|
||||
- **WHEN** он сохраняет вес 84
|
||||
- **THEN** профиль показывает вес 84, обновлённые калории, белок и порции меню
|
||||
- **AND** обновление страницы сохраняет результат
|
||||
|
||||
#### Scenario: Ошибка редактирования
|
||||
- **GIVEN** пользователь вошёл с весом 81
|
||||
- **WHEN** он пытается сохранить вес 0
|
||||
- **THEN** показана подсказка допустимого диапазона и сохранён вес 81
|
||||
|
||||
### Requirement: Приватность
|
||||
Система SHALL отдавать профиль и питание только владельцу после входа, сохранять данные на сервере и прекращать доступ после выхода.
|
||||
|
||||
#### Scenario: Два пользователя
|
||||
- **GIVEN** у Анны вес 81, а у Бориса 92 в отдельных учётных записях
|
||||
- **WHEN** Борис открывает профиль
|
||||
- **THEN** он видит только вес 92
|
||||
|
||||
#### Scenario: Доступ без входа
|
||||
- **GIVEN** пользователь вышел из учётной записи
|
||||
- **WHEN** он запрашивает профиль повторно
|
||||
- **THEN** данные не возвращаются и требуется войти
|
||||
9
openspec/changes/tptip-4-private-profile/tasks.md
Normal file
9
openspec/changes/tptip-4-private-profile/tasks.md
Normal file
@ -0,0 +1,9 @@
|
||||
## 1. Личный профиль
|
||||
- [x] 1.1 Реализовать серверную регистрацию, вход, выход, приватное хранение и редактирование, расчёт питания; проверить интеграционными тестами границы, изоляцию и пересчёт.
|
||||
## 2. Интерфейс
|
||||
- [ ] 2.1 Создать форму входа и регистрации, профиль и меню с пустыми полями, переводами ru/kk/en и словарём; проверить сценарии в браузере.
|
||||
## 3. Доставка
|
||||
- [ ] 3.1 Настроить контейнер, постоянный том, Sentry и команды проверок; описать запуск и проверить /healthz.
|
||||
- [ ] 3.2 Запустить проверки через peppa-check, сверить видимые тексты со словарём, выполнить openspec validate.
|
||||
## Workflow follow-up
|
||||
- Архивировать, записать память, открыть PR и передать в review после зелёных проверок.
|
||||
1628
package-lock.json
generated
Normal file
1628
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
package.json
Normal file
1
package.json
Normal file
@ -0,0 +1 @@
|
||||
{"name":"tptip-profile","private":true,"type":"module","engines":{"node":">=24"},"scripts":{"start":"node server.js","lint":"eslint .","test":"node --test tests/*.test.js","build":"node --check server.js && node --check profile/app.js"},"dependencies":{"@sentry/node":"^11.13.0"},"devDependencies":{"@eslint/js":"^10.0.1","eslint":"^10.15.0","globals":"^17.14.0","playwright":"^1.65.1"}}
|
||||
86
profile/service.js
Normal file
86
profile/service.js
Normal file
@ -0,0 +1,86 @@
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { randomBytes, scrypt as derive, timingSafeEqual, createHash } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
const scrypt = promisify(derive);
|
||||
export class InputError extends Error {
|
||||
constructor(key, status = 400) { super(key); this.status = status; }
|
||||
}
|
||||
export function validateProfile(input) {
|
||||
const out = {};
|
||||
for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) {
|
||||
const value = input[key];
|
||||
if (!['number','string'].includes(typeof value) || !/^\d+(?:[.,]\d+)?$/.test(String(value))) throw new InputError(key);
|
||||
out[key] = Number(String(value).replace(',', '.'));
|
||||
if (!Number.isFinite(out[key]) || out[key] < min || out[key] > max) throw new InputError(key);
|
||||
}
|
||||
if (!Number.isInteger(out.age)) throw new InputError('age');
|
||||
if (!['male','female'].includes(input.sex)) throw new InputError('sex');
|
||||
out.sex = input.sex;
|
||||
if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity');
|
||||
out.activity = Number(input.activity);
|
||||
return out;
|
||||
}
|
||||
export function nutrition(profile) {
|
||||
const p = validateProfile(profile);
|
||||
const calories = Math.round((10*p.weight + 6.25*p.height - 5*p.age + (p.sex === 'male' ? 5 : -161))*p.activity);
|
||||
const protein = Math.round(p.weight*1.6);
|
||||
// One illustrative day: proportions sum to the daily energy estimate.
|
||||
const menu = [
|
||||
{ name: 'breakfast', share: .3, kcal100: 130, protein100: 7 },
|
||||
{ name: 'lunch', share: .4, kcal100: 150, protein100: 12 },
|
||||
{ name: 'dinner', share: .3, kcal100: 140, protein100: 11 },
|
||||
].map(m => ({name:m.name, grams: Math.round(calories*m.share/m.kcal100*100), calories: Math.round(calories*m.share), protein: Math.round(calories*m.share/m.kcal100*m.protein100)}));
|
||||
return { calories, protein, menu };
|
||||
}
|
||||
const hash = value => createHash('sha256').update(value).digest('hex');
|
||||
export class ProfileService {
|
||||
constructor(file, {now = () => Date.now()} = {}) {
|
||||
this.now = now;
|
||||
this.db = new DatabaseSync(file);
|
||||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;
|
||||
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, salt TEXT NOT NULL, password TEXT NOT NULL, profile TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS sessions (token TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), expires INTEGER NOT NULL);`);
|
||||
}
|
||||
credentials(input) {
|
||||
if (typeof input.username !== 'string' || !/^[a-zA-Z0-9_-]{3,40}$/.test(input.username)) throw new InputError('username');
|
||||
if (typeof input.password !== 'string' || input.password.length < 12 || input.password.length > 128) throw new InputError('password');
|
||||
return input.username.toLowerCase();
|
||||
}
|
||||
async authenticate(input, register) {
|
||||
const username = this.credentials(input);
|
||||
const profile = validateProfile(input);
|
||||
const user = this.db.prepare('SELECT * FROM users WHERE username=?').get(username);
|
||||
const salt = register || !user ? randomBytes(16).toString('hex') : user.salt;
|
||||
const password = Buffer.from(await scrypt(input.password, salt, 64));
|
||||
let id;
|
||||
if (register) {
|
||||
if (user) throw new InputError('credentials', 409);
|
||||
id = this.db.prepare('INSERT INTO users(username,salt,password,profile) VALUES(?,?,?,?)').run(username,salt,password.toString('hex'),JSON.stringify(profile)).lastInsertRowid;
|
||||
} else {
|
||||
if (!user || !timingSafeEqual(password, Buffer.from(user.password,'hex'))) throw new InputError('credentials',401);
|
||||
id = user.id;
|
||||
this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile), id);
|
||||
}
|
||||
this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(this.now());
|
||||
const token = randomBytes(32).toString('hex');
|
||||
this.db.prepare('INSERT INTO sessions VALUES(?,?,?)').run(hash(token),id,this.now()+7*86400000);
|
||||
return token;
|
||||
}
|
||||
user(token) {
|
||||
if (!token) throw new InputError('signin',401);
|
||||
const user = this.db.prepare('SELECT users.* FROM users JOIN sessions ON user_id=users.id WHERE token=? AND expires>?').get(hash(token),this.now());
|
||||
if (!user) throw new InputError('signin',401);
|
||||
return user;
|
||||
}
|
||||
read(token) {
|
||||
const user = this.user(token), profile = JSON.parse(user.profile);
|
||||
return {username:user.username,profile,nutrition:nutrition(profile)};
|
||||
}
|
||||
update(token,input) {
|
||||
const user = this.user(token), profile = validateProfile(input);
|
||||
this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile),user.id);
|
||||
return this.read(token);
|
||||
}
|
||||
logout(token) { this.db.prepare('DELETE FROM sessions WHERE token=?').run(hash(token || '')); }
|
||||
close() { this.db.close(); }
|
||||
}
|
||||
63
server.js
Normal file
63
server.js
Normal file
@ -0,0 +1,63 @@
|
||||
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/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();
|
||||
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'; 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 (!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'});
|
||||
}
|
||||
});
|
||||
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');
|
||||
69
tests/profile.test.js
Normal file
69
tests/profile.test.js
Normal file
@ -0,0 +1,69 @@
|
||||
import {test} from 'node:test';
|
||||
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';
|
||||
const profile = {height:182,weight:81,age:32,sex:'male',activity:1.375};
|
||||
const account = {username:'anna',password:'a-long-private-password',...profile};
|
||||
test('Пустое или неверное измерение; границы диапазонов',() => {
|
||||
for (const [key,values] of Object.entries({height:['',null,'abc','1e2',[],true,99,251],weight:['',null,'abc',0,351],age:[17,101,20.5],sex:['','unknown'],activity:['',99]})) {
|
||||
for (const value of values) assert.throws(()=>validateProfile({...profile,[key]:value}));
|
||||
}
|
||||
for (const p of [{height:100,weight:25,age:18},{height:250,weight:350,age:100}]) assert.doesNotThrow(()=>validateProfile({...profile,...p}));
|
||||
assert.equal(validateProfile({...profile,weight:'81,5'}).weight,81.5);
|
||||
assert.equal(nutrition(profile).calories,2465);
|
||||
assert.equal(nutrition(profile).protein,130);
|
||||
});
|
||||
test('Регистрация с измерениями; два пользователя; пересчёт; ошибка редактирования; доступ без входа',async t => {
|
||||
const server = createApp({database:':memory:'});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
t.after(()=>new Promise(r=>server.close(r)));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const call = async(path,method='GET',body,cookie,headers={}) => {
|
||||
const response = await fetch(origin+path,{method,headers:{origin,'Content-Type':'application/json',...(cookie?{cookie}:{}),...headers},body:body===undefined?undefined:JSON.stringify(body)});
|
||||
return {status:response.status,body:await response.json(),cookie:response.headers.get('set-cookie'),headers:response.headers};
|
||||
};
|
||||
assert.equal((await call('/api/profile')).status,401);
|
||||
assert.equal((await call('/api/register','POST',{...account,height:''})).status,400);
|
||||
const anna = await call('/api/register','POST',account);
|
||||
assert.equal(anna.status,200);assert.equal(anna.body.profile.height,182);
|
||||
assert.match(anna.cookie,/HttpOnly/);assert.match(anna.cookie,/SameSite=Strict/);
|
||||
assert.equal(anna.headers.get('cache-control'),'no-store');
|
||||
assert.equal(JSON.stringify(anna.body).includes('password'),false);
|
||||
const boris = await call('/api/register','POST',{...account,username:'boris',weight:92});
|
||||
const own = await call('/api/profile?username=anna','GET',undefined,boris.cookie);
|
||||
assert.equal(own.body.profile.weight,92);
|
||||
const updated = await call('/api/profile','PUT',{...profile,weight:84,user_id:2},anna.cookie);
|
||||
assert.equal(updated.body.profile.weight,84);
|
||||
assert.notEqual(updated.body.nutrition.calories,anna.body.nutrition.calories);
|
||||
assert.notEqual(updated.body.nutrition.protein,anna.body.nutrition.protein);
|
||||
assert.notEqual(updated.body.nutrition.menu[0].grams,anna.body.nutrition.menu[0].grams);
|
||||
assert.equal((await call('/api/profile','GET',undefined,anna.cookie)).body.profile.weight,84);
|
||||
assert.equal((await call('/api/profile','PUT',{...profile,weight:0},anna.cookie)).status,400);
|
||||
assert.equal((await call('/api/profile','GET',undefined,anna.cookie)).body.profile.weight,84);
|
||||
assert.equal((await call('/api/profile','PUT',profile,anna.cookie,{origin:'https://attacker.example'})).status,403);
|
||||
assert.equal((await call('/api/profile','PUT',profile,anna.cookie,{origin:''})).status,403);
|
||||
assert.equal((await call('/api/login','POST',{...account,password:'wrong-password-long'})).status,401);
|
||||
assert.equal((await call('/api/login','POST',{...account,weight:''})).status,400);
|
||||
const login = await call('/api/login','POST',{...account,weight:86});
|
||||
assert.equal(login.body.profile.weight,86);
|
||||
assert.equal((await call('/api/logout','POST',{},login.cookie)).status,200);
|
||||
assert.equal((await call('/api/profile','GET',undefined,login.cookie)).status,401);
|
||||
for (let n=0;n<21;n++) await call('/api/login','POST',account);
|
||||
assert.equal((await call('/api/login','POST',account)).status,429);
|
||||
assert.equal((await fetch(origin+'/.peppa/project.json')).status,404);
|
||||
assert.equal((await fetch(origin+'/healthz')).status,200);
|
||||
});
|
||||
test('Сохранение после перезапуска и истечение срока входа',async t=>{
|
||||
const dir = await mkdtemp(join(tmpdir(),'tptip-test-'));
|
||||
t.after(()=>rm(dir,{recursive:true,force:true}));
|
||||
let now = Date.now();
|
||||
let service = new ProfileService(join(dir,'profile.sqlite'),{now:()=>now});
|
||||
const token = await service.authenticate(account,true);
|
||||
service.close();service = new ProfileService(join(dir,'profile.sqlite'),{now:()=>now});
|
||||
assert.equal(service.read(token).profile.weight,81);
|
||||
now += 8*86400000;
|
||||
assert.throws(()=>service.read(token));service.close();
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user