Files
pipu-music/packages/core/src/server.ts
T
mrleo1nidandClaude Opus 5.5 4fa1add80d
ci / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 48s
ci / api (push) Successful in 51s
ci / recommender (push) Canceled after 2s
ci / ts (packages + web) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (apps/web/Dockerfile, web, ) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (services/api/Dockerfile, api, api) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (services/api/Dockerfile, storage-agent, storage-agent) (push) Canceled after 0s
ci / docker (образы собираются — их сервер собирает сам при обновлении) (services/recommender/Dockerfile, recommender, ) (push) Canceled after 0s
ci / mobile (Metro-бандл Android) (push) Canceled after 0s
fix: address project review findings
Security and robustness:
- storage-agent rejects an empty INTERNAL_TOKEN (config notEmpty + middleware)
- api takes the client IP only from X-Real-IP (chi RealIP trusted True-Client-IP)
- /readyz reports ok/fail and logs the cause; checks run in parallel with a timeout
- storage-agent shuts down gracefully; shared httpx.NewServer/Serve with IdleTimeout
- goose migrations take a Postgres advisory lock
- recommender readyz: per-check timeout, redis socket timeouts

Clients:
- Android release allows cleartext HTTP for LAN servers (expo-build-properties)
- checkServer times out after 10s; connect button is disabled while checking

Deploy and CI:
- install.sh hands cache/uploads/updates/models to the non-root service users
- update.sh refuses downgrades unless PIPU_ALLOW_DOWNGRADE=1
- recommender/analyzer get only the env they need; required secrets fail fast
- nginx security headers and CSP; strip True-Client-IP
- dev compose binds ports to 127.0.0.1; postgres/redis images pinned
- version.mjs fails on a malformed explicit tag instead of releasing 0.0.0-dev
- contract check catches untracked generated files
- final releases fail without a release keystore; changelog skips rc tags

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 00:46:46 +03:00

67 lines
2.7 KiB
TypeScript

import type { ApiClient, ServerInfo } from '@pipu/api-client';
/**
* Приводит введённый пользователем адрес сервера к виду `https://host[:port][/path]` без завершающего слеша.
* Без схемы подставляется https. Возвращает null, если адрес некорректен.
*/
export function normalizeServerUrl(input: string): string | null {
const raw = input.trim();
if (!raw) return null;
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
let url: URL;
try {
url = new URL(withScheme);
} catch {
return null;
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
if (!url.hostname) return null;
const path = url.pathname.replace(/\/+$/, '');
return `${url.protocol}//${url.host}${path}`;
}
export type ServerCheck =
| { status: 'ok'; info: ServerInfo }
| { status: 'unsupported_app'; info: ServerInfo }
| { status: 'offline'; error: string };
/** Сколько ждать ответа сервера, прежде чем считать его недоступным. */
export const SERVER_CHECK_TIMEOUT_MS = 10_000;
/**
* Проверяет сервер через GET /api/v1/server-info.
* appVersionCode — versionCode Android-клиента; для веба не передаётся.
*/
export async function checkServer(
client: ApiClient,
appVersionCode?: number,
timeoutMs = SERVER_CHECK_TIMEOUT_MS,
): Promise<ServerCheck> {
// Гонка с таймером, а не только abort: не каждая реализация fetch (Hermes, полифилы)
// надёжно прерывает запрос по сигналу. AbortSignal.timeout не используется — его может не быть в Hermes.
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error('timeout'));
}, timeoutMs);
});
try {
const { data, error } = await Promise.race([
client.GET('/api/v1/server-info', { signal: controller.signal }),
timeout,
]);
if (!data) return { status: 'offline', error: error ? error.code : 'unknown' };
if (appVersionCode !== undefined && appVersionCode < data.min_android_version_code) {
return { status: 'unsupported_app', info: data };
}
return { status: 'ok', info: data };
} catch (e) {
if (controller.signal.aborted) return { status: 'offline', error: 'timeout' };
return { status: 'offline', error: e instanceof Error ? e.message : String(e) };
} finally {
clearTimeout(timer);
}
}