feat(api): implement chestny-znak web app with True API integration

- Fastify backend with auth (CryptoPro CAdES-BES), KM check, UPD parsing
- React frontend with auth page, code check, XML upload, results table
- Client-side signing via crypto-pro 2.3.0 (browser plugin)
- Token caching with auto-refresh, retry with exponential backoff
- Input validation schemas, file size limits, global 401 interceptor
- Docker compose with backend + frontend (nginx) services
This commit is contained in:
kislovdm
2026-07-08 16:53:35 +03:00
parent d2819ff03c
commit 70eac33c8c
19 changed files with 501 additions and 240 deletions
+30 -46
View File
@@ -4,21 +4,14 @@
## Архитектура ## Архитектура
- **Backend**: Fastify + TypeScript - **Backend**: Fastify + TypeScript (прокси-сервер к True API)
- **Frontend**: React + Vite + TypeScript - **Frontend**: React + Vite + TypeScript (SPA с интеграцией КриптоПро Browser Plugin)
- **Docker**: docker-compose (2 сервиса: backend, frontend) - **Docker**: docker-compose (2 сервиса: backend, frontend)
## Быстрый старт ## Быстрый старт
```bash ```bash
# Клонировать и перейти в директорию
cd chestno-api cd chestno-api
# Настроить окружение
cp backend/.env.example backend/.env
# Отредактировать backend/.env — указать thumbprint сертификата
# Запустить
docker-compose up --build docker-compose up --build
``` ```
@@ -30,14 +23,10 @@ docker-compose up --build
```bash ```bash
# Backend # Backend
cd backend cd backend && npm install && npm run dev
npm install
npm run dev
# Frontend (в отдельном терминале) # Frontend (в отдельном терминале)
cd frontend cd frontend && npm install && npm run dev
npm install
npm run dev
``` ```
## Структура проекта ## Структура проекта
@@ -47,39 +36,34 @@ backend/
src/ src/
config.ts # Конфигурация config.ts # Конфигурация
index.ts # Точка входа Fastify index.ts # Точка входа Fastify
routes/ routes/auth.ts # GET /auth/key, POST /auth/simpleSignIn, GET /auth/status, POST /auth/logout
auth.ts # GET /auth/key, POST /auth/signin, GET /auth/status routes/cises.ts # POST /api/check-codes/public, POST /api/check-codes/auth
cises.ts # POST /api/check-codes/public, /api/check-codes/auth routes/upd.ts # POST /api/upload-upd
upd.ts # POST /api/upload-upd services/auth-service.ts # Прокси к True API auth
services/ services/cises-service.ts # Проверка КМ (публичная / авторизованная)
auth-service.ts # True API аутентификация + подпись через КриптоПро services/token-cache.ts # Кеширование токена (node-cache, TTL 10ч)
cises-service.ts # Проверка КМ (публичная / авторизованная) services/upd-parser.ts # Парсинг XML УПД (формат Приказа №970)
token-cache.ts # Кеширование токена (node-cache, TTL 10ч) types/index.ts
upd-parser.ts # Парсинг XML УПД (формат Приказа №970)
types/
index.ts # TypeScript типы
frontend/ frontend/
src/ src/
App.tsx # Корневой компонент с навигацией App.tsx
pages/ pages/AuthPage.tsx # Авторизация через КриптоПро Browser Plugin
AuthPage.tsx # Авторизация pages/CheckCodesPage.tsx # Проверка кодов
CheckCodesPage.tsx# Проверка кодов pages/UploadUpdPage.tsx # Загрузка УПД
UploadUpdPage.tsx # Загрузка УПД components/ResultsTable.tsx
components/ services/api.ts # HTTP-клиент
ResultsTable.tsx # Таблица результатов с цветовой индикацией services/cadesplugin.ts # Интеграция с КриптоПро Browser Plugin
services/ types/index.ts
api.ts # HTTP-клиент к backend
types/
index.ts # TypeScript типы
``` ```
## API Endpoints ## API Endpoints
### Аутентификация ### Аутентификация
- `GET /auth/key` — получение UUID + data для подписи - `GET /auth/key` — получение UUID + data для подписи
- `POST /auth/signin` — отправка подписи, получение токена - `POST /auth/simpleSignIn` — отправка подписи, получение токена
- `GET /auth/status` — статус авторизации - `GET /auth/status` — статус авторизации
- `POST /auth/logout` — сброс токена
### Проверка кодов ### Проверка кодов
- `POST /api/check-codes/public` — публичная проверка (без авторизации) - `POST /api/check-codes/public` — публичная проверка (без авторизации)
@@ -96,14 +80,14 @@ frontend/
| `HOST` | Хост | `0.0.0.0` | | `HOST` | Хост | `0.0.0.0` |
| `TRUE_API_URL` | URL True API | `https://markirovka.sandbox.crptech.ru/api/v3/true-api` | | `TRUE_API_URL` | URL True API | `https://markirovka.sandbox.crptech.ru/api/v3/true-api` |
| `PUBLIC_CHECK_URL` | URL публичного API | `https://mobile.api.crpt.ru/mobile/check` | | `PUBLIC_CHECK_URL` | URL публичного API | `https://mobile.api.crpt.ru/mobile/check` |
| `CERT_THUMBPRINT` | Thumbprint сертификата КриптоПро | — |
## Подпись данных через КриптоПро ## Процесс авторизации
Подпись выполняется через CLI-утилиту `cryptcp` (входит в состав КриптоПро CSP). Установите КриптоПро CSP и укажите thumbprint сертификата в `CERT_THUMBPRINT`. 1. Пользователь нажимает «Подписать и войти» в браузере
2. Frontend получает UUID + data от `GET /auth/key`
3. КриптоПро Browser Plugin подписывает data (CAdES-BES, присоединённая подпись, base64)
4. Подпись отправляется на `POST /auth/simpleSignIn`
5. Backend проксирует запрос в True API, кеширует токен
6. Токен используется для авторизованных запросов (10 часов)
### Получение thumbprint сертификата > Подпись выполняется **на стороне клиента** — закрытый ключ УКЭП не покидает устройство пользователя.
```bash
cryptcp -list
```
+1 -1
View File
@@ -2,4 +2,4 @@ PORT=3001
HOST=0.0.0.0 HOST=0.0.0.0
TRUE_API_URL=https://markirovka.sandbox.crptech.ru/api/v3/true-api TRUE_API_URL=https://markirovka.sandbox.crptech.ru/api/v3/true-api
PUBLIC_CHECK_URL=https://mobile.api.crpt.ru/mobile/check PUBLIC_CHECK_URL=https://mobile.api.crpt.ru/mobile/check
CERT_THUMBPRINT=your-certificate-thumbprint-here CORS_ORIGIN=*
+4
View File
@@ -2,6 +2,8 @@ export const config = {
port: parseInt(process.env.PORT || '3001', 10), port: parseInt(process.env.PORT || '3001', 10),
host: process.env.HOST || '0.0.0.0', host: process.env.HOST || '0.0.0.0',
corsOrigin: process.env.CORS_ORIGIN || '*',
trueApi: { trueApi: {
baseUrl: process.env.TRUE_API_URL || 'https://markirovka.sandbox.crptech.ru/api/v3/true-api', baseUrl: process.env.TRUE_API_URL || 'https://markirovka.sandbox.crptech.ru/api/v3/true-api',
publicCheckUrl: process.env.PUBLIC_CHECK_URL || 'https://mobile.api.crpt.ru/mobile/check', publicCheckUrl: process.env.PUBLIC_CHECK_URL || 'https://mobile.api.crpt.ru/mobile/check',
@@ -10,5 +12,7 @@ export const config = {
codesCheckPath: '/codes/check', codesCheckPath: '/codes/check',
batchSize: 1000, batchSize: 1000,
tokenTTL: 10 * 60 * 60 * 1000, tokenTTL: 10 * 60 * 60 * 1000,
maxRetries: 3,
publicCheckConcurrency: 10,
}, },
} }
+8 -2
View File
@@ -8,8 +8,14 @@ import { updRoutes } from './routes/upd.js'
const app = Fastify({ logger: true }) const app = Fastify({ logger: true })
await app.register(cors, { origin: true }) await app.register(cors, { origin: config.corsOrigin })
await app.register(multipart) await app.register(multipart, {
limits: {
fileSize: 10 * 1024 * 1024,
files: 1,
},
throwFileSizeLimit: true,
})
await app.register(authRoutes) await app.register(authRoutes)
await app.register(cisesRoutes) await app.register(cisesRoutes)
+20 -4
View File
@@ -1,6 +1,17 @@
import type { FastifyInstance } from 'fastify' import type { FastifyInstance } from 'fastify'
import { getAuthKey, signIn } from '../services/auth-service.js' import { getAuthKey, signIn, clearToken, isAuthenticated } from '../services/auth-service.js'
import { getTokenTTL, hasToken } from '../services/token-cache.js' import { getTokenTTL } from '../services/token-cache.js'
const signInSchema = {
body: {
type: 'object',
required: ['uuid', 'data'],
properties: {
uuid: { type: 'string' },
data: { type: 'string' },
},
},
}
export async function authRoutes(app: FastifyInstance): Promise<void> { export async function authRoutes(app: FastifyInstance): Promise<void> {
app.get('/auth/key', async () => { app.get('/auth/key', async () => {
@@ -8,18 +19,23 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
return { uuid: authKey.uuid, data: authKey.data } return { uuid: authKey.uuid, data: authKey.data }
}) })
app.post<{ Body: { uuid: string; data: string } }>('/auth/signin', async (request) => { app.post<{ Body: { uuid: string; data: string } }>('/auth/simpleSignIn', { schema: signInSchema }, async (request) => {
const { uuid, data } = request.body const { uuid, data } = request.body
const result = await signIn({ uuid, data }) const result = await signIn({ uuid, data })
return result return result
}) })
app.get('/auth/status', async () => { app.get('/auth/status', async () => {
const authenticated = hasToken() const authenticated = isAuthenticated()
const ttl = getTokenTTL() const ttl = getTokenTTL()
return { return {
authenticated, authenticated,
tokenExpiresAt: ttl ? new Date(ttl).toISOString() : null, tokenExpiresAt: ttl ? new Date(ttl).toISOString() : null,
} }
}) })
app.post('/auth/logout', async () => {
clearToken()
return { success: true }
})
} }
+26 -4
View File
@@ -1,13 +1,35 @@
import type { FastifyInstance } from 'fastify' import type { FastifyInstance } from 'fastify'
import { checkCodesPublic, checkCodesAuth } from '../services/cises-service.js' import { checkCodesPublic, checkCodesAuth, AppError } from '../services/cises-service.js'
import type { CheckCodesRequest } from '../types/index.js' import type { CheckCodesRequest } from '../types/index.js'
const checkCodesSchema = {
body: {
type: 'object',
required: ['codes'],
properties: {
codes: {
type: 'array',
items: { type: 'string', minLength: 1, maxLength: 256 },
minItems: 1,
maxItems: 10000,
},
},
},
}
export async function cisesRoutes(app: FastifyInstance): Promise<void> { export async function cisesRoutes(app: FastifyInstance): Promise<void> {
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/public', async (request) => { app.post<{ Body: CheckCodesRequest }>('/api/check-codes/public', { schema: checkCodesSchema }, async (request) => {
return checkCodesPublic(request.body) return checkCodesPublic(request.body)
}) })
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', async (request) => { app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', { schema: checkCodesSchema }, async (request, reply) => {
return checkCodesAuth(request.body) try {
return await checkCodesAuth(request.body)
} catch (err) {
if (err instanceof AppError) {
return reply.status(err.statusCode).send({ error: err.message })
}
throw err
}
}) })
} }
+14 -2
View File
@@ -1,6 +1,6 @@
import type { FastifyInstance } from 'fastify' import type { FastifyInstance } from 'fastify'
import { parseUpdXml } from '../services/upd-parser.js' import { parseUpdXml } from '../services/upd-parser.js'
import { checkCodesAuth } from '../services/cises-service.js' import { checkCodesAuth, AppError } from '../services/cises-service.js'
export async function updRoutes(app: FastifyInstance): Promise<void> { export async function updRoutes(app: FastifyInstance): Promise<void> {
app.post('/api/upload-upd', async (request, reply) => { app.post('/api/upload-upd', async (request, reply) => {
@@ -13,12 +13,18 @@ export async function updRoutes(app: FastifyInstance): Promise<void> {
const xmlContent = buffer.toString('utf-8') const xmlContent = buffer.toString('utf-8')
const fileName = data.filename const fileName = data.filename
const parsed = await parseUpdXml(xmlContent, fileName) let parsed
try {
parsed = await parseUpdXml(xmlContent, fileName)
} catch {
return reply.status(400).send({ error: 'Invalid XML file' })
}
if (parsed.codes.length === 0) { if (parsed.codes.length === 0) {
return reply.status(400).send({ error: 'No marking codes found in UPD' }) return reply.status(400).send({ error: 'No marking codes found in UPD' })
} }
try {
const checkResults = await checkCodesAuth({ codes: parsed.codes }) const checkResults = await checkCodesAuth({ codes: parsed.codes })
return { return {
@@ -32,5 +38,11 @@ export async function updRoutes(app: FastifyInstance): Promise<void> {
codesFound: parsed.codes.length, codesFound: parsed.codes.length,
results: checkResults, results: checkResults,
} }
} catch (err) {
if (err instanceof AppError) {
return reply.status(err.statusCode).send({ error: err.message })
}
throw err
}
}) })
} }
+8 -23
View File
@@ -1,6 +1,6 @@
import got from 'got' import got from 'got'
import { config } from '../config.js' import { config } from '../config.js'
import { getToken, setToken } from './token-cache.js' import { getToken, setToken, invalidateToken } from './token-cache.js'
import type { AuthKeyResponse, AuthSignInRequest, AuthSignInResponse } from '../types/index.js' import type { AuthKeyResponse, AuthSignInRequest, AuthSignInResponse } from '../types/index.js'
const authClient = got.extend({ const authClient = got.extend({
@@ -21,29 +21,14 @@ export async function signIn(body: AuthSignInRequest): Promise<AuthSignInRespons
return response return response
} }
export async function getValidToken(): Promise<string> { export function getCachedToken(): string | undefined {
const cached = getToken() return getToken()
if (cached) return cached
const { uuid, data } = await getAuthKey()
const signature = await signData(data)
const { token } = await signIn({ uuid, data: signature })
return token
} }
async function signData(data: string): Promise<string> { export function clearToken(): void {
try { invalidateToken()
const { execSync } = await import('child_process') }
const thumbprint = process.env.CERT_THUMBPRINT export function isAuthenticated(): boolean {
if (!thumbprint) throw new Error('CERT_THUMBPRINT not set') return !!getToken()
const result = execSync(
`cryptcp -sign -detached -base64 -thumbprint "${thumbprint}" -in <(echo -n "${data}")`,
{ encoding: 'utf-8' }
)
return result.trim()
} catch (err) {
throw new Error(`Failed to sign data with CryptoPro: ${err}`)
}
} }
+88 -18
View File
@@ -1,6 +1,6 @@
import got from 'got' import got from 'got'
import { config } from '../config.js' import { config } from '../config.js'
import { getValidToken } from './auth-service.js' import { getCachedToken, clearToken } from './auth-service.js'
import type { import type {
CisInfoResponse, CisInfoResponse,
PublicCheckResponse, PublicCheckResponse,
@@ -16,12 +16,15 @@ const apiClient = got.extend({
export async function checkCodesPublic(body: CheckCodesRequest): Promise<CheckCodesResponse> { export async function checkCodesPublic(body: CheckCodesRequest): Promise<CheckCodesResponse> {
const results: SingleCodeResult[] = [] const results: SingleCodeResult[] = []
const queue = [...body.codes]
for (const code of body.codes) { async function worker() {
while (queue.length > 0) {
const code = queue.shift()!
try { try {
const { body: response } = await got.get<PublicCheckResponse>( const { body: response } = await got.get<PublicCheckResponse>(
`${config.trueApi.publicCheckUrl}?code=${encodeURIComponent(code)}`, `${config.trueApi.publicCheckUrl}?code=${encodeURIComponent(code)}`,
{ responseType: 'json' } { responseType: 'json', timeout: { request: 10000 } }
) )
results.push({ results.push({
code: response.code, code: response.code,
@@ -39,23 +42,65 @@ export async function checkCodesPublic(body: CheckCodesRequest): Promise<CheckCo
}) })
} }
} }
}
const workers = Array.from({ length: config.trueApi.publicCheckConcurrency }, () => worker())
await Promise.all(workers)
return buildResponse(results) return buildResponse(results)
} }
function getToken(): string {
const token = getCachedToken()
if (!token) throw new AppError('Not authenticated', 401)
return token
}
export async function checkCodesAuth(body: CheckCodesRequest): Promise<CheckCodesResponse> { export async function checkCodesAuth(body: CheckCodesRequest): Promise<CheckCodesResponse> {
const token = await getValidToken() const token = getToken()
const results: SingleCodeResult[] = [] const results: SingleCodeResult[] = []
for (let i = 0; i < body.codes.length; i += config.trueApi.batchSize) { try {
const batch = body.codes.slice(i, i + config.trueApi.batchSize) await processBatch(body.codes, token, results, 0)
} catch (err) {
if (err instanceof AppError && err.statusCode === 401) {
clearToken()
throw err
}
for (const code of body.codes) {
if (!results.find(r => r.code === code)) {
results.push({ code, found: false, valid: false, status: 'ERROR', error: 'Auth API error' })
}
}
}
return buildResponse(results)
}
async function processBatch(
codes: string[], token: string, results: SingleCodeResult[], batchIndex: number
): Promise<void> {
if (batchIndex >= codes.length) return
const start = batchIndex
const end = Math.min(start + config.trueApi.batchSize, codes.length)
const batch = codes.slice(start, end)
await retryOnError(batch, token, results)
await processBatch(codes, token, results, end)
}
async function retryOnError(
batch: string[], token: string, results: SingleCodeResult[], attempt = 0
): Promise<void> {
try { try {
const { body: response } = await apiClient.post<CisInfoResponse>( const { body: response } = await apiClient.post<CisInfoResponse>(
config.trueApi.cisesInfoPath, config.trueApi.cisesInfoPath,
{ {
json: { cisList: batch }, json: { cisList: batch },
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: `Bearer ${token}` },
timeout: { request: 30000 },
} }
) )
@@ -71,20 +116,45 @@ export async function checkCodesAuth(body: CheckCodesRequest): Promise<CheckCode
ownerName: item.ownerName, ownerName: item.ownerName,
}) })
} }
} catch { } catch (err) {
for (const code of batch) { if (is401(err)) {
results.push({ throw new AppError('Token expired', 401)
code,
found: false,
valid: false,
status: 'ERROR',
error: 'Auth API error',
})
}
}
} }
return buildResponse(results) const isRetryable = isRetryableError(err)
if (isRetryable && attempt < config.trueApi.maxRetries) {
const delay = Math.pow(2, attempt) * 500
await sleep(delay)
return retryOnError(batch, token, results, attempt + 1)
}
throw err
}
}
function is401(err: unknown): boolean {
if (!err || typeof err !== 'object') return false
return 'response' in err &&
(err as { response?: { statusCode?: number } }).response?.statusCode === 401
}
function isRetryableError(err: unknown): boolean {
if (!err || typeof err !== 'object') return true
const statusCode = (err as { response?: { statusCode?: number } }).response?.statusCode
if (!statusCode) return true
return statusCode === 429 || statusCode >= 500
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
export class AppError extends Error {
statusCode: number
constructor(message: string, statusCode: number) {
super(message)
this.statusCode = statusCode
}
} }
function buildResponse(results: SingleCodeResult[]): CheckCodesResponse { function buildResponse(results: SingleCodeResult[]): CheckCodesResponse {
+4
View File
@@ -23,3 +23,7 @@ export function hasToken(): boolean {
export function getTokenTTL(): number | undefined { export function getTokenTTL(): number | undefined {
return cache.getTtl(TOKEN_KEY) return cache.getTtl(TOKEN_KEY)
} }
export function invalidateToken(): void {
cache.del(TOKEN_KEY)
}
+20 -19
View File
@@ -11,7 +11,6 @@ export interface ParsedUpd {
export async function parseUpdXml(xmlContent: string, fileName: string): Promise<ParsedUpd> { export async function parseUpdXml(xmlContent: string, fileName: string): Promise<ParsedUpd> {
const parsed = await parseStringPromise(xmlContent, { const parsed = await parseStringPromise(xmlContent, {
explicitArray: false,
ignoreAttrs: false, ignoreAttrs: false,
mergeAttrs: true, mergeAttrs: true,
}) })
@@ -21,42 +20,44 @@ export async function parseUpdXml(xmlContent: string, fileName: string): Promise
return { return {
codes, codes,
fileName, fileName,
documentNumber: extractField(parsed, 'Документ', 'НомерДок'), documentNumber: extractField(parsed, ['Документ', 'НомерДок']),
documentDate: extractField(parsed, 'Документ', 'ДатаДок'), documentDate: extractField(parsed, ['Документ', 'ДатаДок']),
sellerName: extractField(parsed, 'Документ', 'ТаблСчФакт', 'СведПрод', 'НаимОрг'), sellerName: extractField(parsed, ['Документ', 'ТаблСчФакт', 'СведПрод', 'НаимОрг']),
buyerName: extractField(parsed, 'Документ', 'ТаблСчФакт', 'СведПокуп', 'НаимОрг'), buyerName: extractField(parsed, ['Документ', 'ТаблСчФакт', 'СведПокуп', 'НаимОрг']),
} }
} }
function extractCodes(obj: Record<string, unknown>): string[] { function extractCodes(obj: Record<string, unknown>): string[] {
const codes: string[] = [] const codes: string[] = []
const documents = asArray<Record<string, unknown>>(obj['Документ'])
for (const document of documents) {
try { try {
const document = obj['Документ'] as Record<string, unknown> const table = document['ТаблСчФакт'] as Record<string, unknown> | undefined
const table = document['ТаблСчФакт'] as Record<string, unknown> if (!table) continue
const items = table['СведТов'] as Record<string, unknown>[] const items = asArray<Record<string, unknown>>(table['СведТов'])
if (Array.isArray(items)) {
for (const item of items) { for (const item of items) {
const extInfo = item['ДопСведТов'] as Record<string, unknown> const extInfo = asArray<Record<string, unknown>>(item['ДопСведТов'])
if (extInfo) { for (const info of extInfo) {
const kmCodes = extInfo['НомСредИдентТов'] const kmCodes = asArray<string>(info['НомСредИдентТов'])
if (Array.isArray(kmCodes)) {
codes.push(...kmCodes.filter(Boolean)) codes.push(...kmCodes.filter(Boolean))
} else if (typeof kmCodes === 'string') {
codes.push(kmCodes)
}
}
} }
} }
} catch { } catch {
// XML structure may vary; return what we found console.warn('upd-parser: failed to extract codes from a document')
}
} }
return codes return codes
} }
function extractField(obj: Record<string, unknown>, ...keys: string[]): string | undefined { function asArray<T>(value: unknown): T[] {
if (value == null) return []
return Array.isArray(value) ? value as T[] : [value as T]
}
function extractField(obj: Record<string, unknown>, keys: string[]): string | undefined {
let current: unknown = obj let current: unknown = obj
for (const key of keys) { for (const key of keys) {
if (current && typeof current === 'object') { if (current && typeof current === 'object') {
+7
View File
@@ -8,6 +8,7 @@
"name": "chestny-znak-api-frontend", "name": "chestny-znak-api-frontend",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"crypto-pro": "^2.3.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0"
}, },
@@ -1725,6 +1726,12 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/crypto-pro": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/crypto-pro/-/crypto-pro-2.3.0.tgz",
"integrity": "sha512-cppYuMRRijEaZ0UKAOW5L1CQIvzQA3DTRp4pARINl6K8Pp1JMhlch5TyWwv6Z4Y3x677A9xxcW62okHD91Veqg==",
"license": "MIT"
},
"node_modules/csstype": { "node_modules/csstype": {
"version": "3.2.3", "version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+3 -2
View File
@@ -11,6 +11,7 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"crypto-pro": "^2.3.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0" "react-dom": "^19.0.0"
}, },
@@ -18,8 +19,8 @@
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0", "@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.19.0",
"typescript": "^5.7.3", "typescript": "^5.7.3",
"vite": "^6.1.0", "vite": "^6.1.0"
"eslint": "^9.19.0"
} }
} }
+40 -5
View File
@@ -1,7 +1,8 @@
import { useState } from 'react' import { useState, useEffect } from 'react'
import { AuthPage } from './pages/AuthPage' import { AuthPage } from './pages/AuthPage'
import { CheckCodesPage } from './pages/CheckCodesPage' import { CheckCodesPage } from './pages/CheckCodesPage'
import { UploadUpdPage } from './pages/UploadUpdPage' import { UploadUpdPage } from './pages/UploadUpdPage'
import { setOnUnauthorized, logout as apiLogout } from './services/api'
type Page = 'auth' | 'check' | 'upload' type Page = 'auth' | 'check' | 'upload'
@@ -9,6 +10,24 @@ export default function App() {
const [page, setPage] = useState<Page>('auth') const [page, setPage] = useState<Page>('auth')
const [authenticated, setAuthenticated] = useState(false) const [authenticated, setAuthenticated] = useState(false)
useEffect(() => {
setOnUnauthorized(() => {
setAuthenticated(false)
apiLogout().catch(() => {})
})
}, [])
function handleAuth() {
setAuthenticated(true)
setPage('check')
}
function handleLogout() {
setAuthenticated(false)
apiLogout().catch(() => {})
setPage('auth')
}
return ( return (
<div style={{ minHeight: '100vh', background: '#f5f5f5' }}> <div style={{ minHeight: '100vh', background: '#f5f5f5' }}>
<header style={{ <header style={{
@@ -26,21 +45,37 @@ export default function App() {
Авторизация Авторизация
</button> </button>
<button onClick={() => setPage('check')} <button onClick={() => setPage('check')}
style={navBtnStyle(page === 'check')}> style={navBtnStyle(page === 'check')}
disabled={!authenticated}>
Проверка кода Проверка кода
</button> </button>
<button onClick={() => setPage('upload')} <button onClick={() => setPage('upload')}
style={navBtnStyle(page === 'upload')}> style={navBtnStyle(page === 'upload')}
disabled={!authenticated}>
Загрузка УПД Загрузка УПД
</button> </button>
</nav> </nav>
<div style={{ marginLeft: 'auto', fontSize: 13 }}> <div style={{ marginLeft: 'auto', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
{authenticated ? '✅ Авторизован' : '❌ Не авторизован'} {authenticated ? '✅ Авторизован' : '❌ Не авторизован'}
{authenticated && (
<button onClick={handleLogout}
style={{
background: 'rgba(255,255,255,0.15)',
color: 'white',
border: '1px solid rgba(255,255,255,0.3)',
borderRadius: 4,
padding: '3px 10px',
cursor: 'pointer',
fontSize: 12,
}}>
Выйти
</button>
)}
</div> </div>
</header> </header>
<main style={{ padding: 24, maxWidth: 960, margin: '0 auto' }}> <main style={{ padding: 24, maxWidth: 960, margin: '0 auto' }}>
{page === 'auth' && <AuthPage onAuth={() => setAuthenticated(true)} />} {page === 'auth' && <AuthPage onAuth={handleAuth} />}
{page === 'check' && <CheckCodesPage />} {page === 'check' && <CheckCodesPage />}
{page === 'upload' && <UploadUpdPage />} {page === 'upload' && <UploadUpdPage />}
</main> </main>
+72 -52
View File
@@ -1,5 +1,7 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { getAuthStatus, getAuthKey, signIn } from '../services/api' import { getAuthStatus, getAuthKey, signIn } from '../services/api'
import { isCadesPluginAvailable, listCertificates, signWithCadesPlugin } from '../services/cadesplugin'
import type { CertInfo } from '../services/cadesplugin'
interface Props { interface Props {
onAuth: () => void onAuth: () => void
@@ -7,27 +9,25 @@ interface Props {
export function AuthPage({ onAuth }: Props) { export function AuthPage({ onAuth }: Props) {
const [status, setStatus] = useState<{ authenticated: boolean; tokenExpiresAt: string | null } | null>(null) const [status, setStatus] = useState<{ authenticated: boolean; tokenExpiresAt: string | null } | null>(null)
const [uuid, setUuid] = useState('') const [hasPlugin, setHasPlugin] = useState<boolean | null>(null)
const [dataToSign, setDataToSign] = useState('') const [certs, setCerts] = useState<CertInfo[]>([])
const [signature, setSignature] = useState('') const [selectedThumbprint, setSelectedThumbprint] = useState('')
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [error, setError] = useState('') const [error, setError] = useState('')
useEffect(() => { useEffect(() => {
getAuthStatus().then(setStatus).catch(() => {}) getAuthStatus().then(setStatus).catch(() => {})
checkPlugin()
}, []) }, [])
async function handleGetKey() { async function checkPlugin() {
setLoading(true) const available = await isCadesPluginAvailable()
setError('') setHasPlugin(available)
if (available) {
try { try {
const { uuid, data } = await getAuthKey() const certList = await listCertificates()
setUuid(uuid) setCerts(certList)
setDataToSign(data) } catch {}
} catch (err) {
setError(String(err))
} finally {
setLoading(false)
} }
} }
@@ -35,12 +35,14 @@ export function AuthPage({ onAuth }: Props) {
setLoading(true) setLoading(true)
setError('') setError('')
try { try {
const { uuid, data } = await getAuthKey()
const signature = await signWithCadesPlugin(data, selectedThumbprint || undefined)
await signIn(uuid, signature) await signIn(uuid, signature)
const s = await getAuthStatus() const s = await getAuthStatus()
setStatus(s) setStatus(s)
if (s.authenticated) onAuth() if (s.authenticated) onAuth()
} catch (err) { } catch (err) {
setError(String(err)) setError(String(err instanceof Error ? err.message : err))
} finally { } finally {
setLoading(false) setLoading(false)
} }
@@ -50,64 +52,83 @@ export function AuthPage({ onAuth }: Props) {
<div> <div>
<h2>Авторизация в True API</h2> <h2>Авторизация в True API</h2>
{status && ( {hasPlugin === false && (
<div style={{ <div style={{
padding: 12, padding: 12,
background: status.authenticated ? '#e8f5e9' : '#fff3e0', background: '#fff3e0',
borderRadius: 6,
marginBottom: 16,
fontSize: 14,
}}>
⚠️ КриптоПро Browser Plugin не обнаружен.
<br />
<a href="https://cryptopro.ru/products/cades/plugin" target="_blank" rel="noopener noreferrer">
Установите расширение для браузера
</a>
</div>
)}
{status?.authenticated && (
<div style={{
padding: 12,
background: '#e8f5e9',
borderRadius: 6, borderRadius: 6,
marginBottom: 16, marginBottom: 16,
}}> }}>
<strong>Статус:</strong>{' '} <strong>✅ Авторизован</strong>
{status.authenticated ? '✅ Авторизован' : '❌ Не авторизован'}
{status.tokenExpiresAt && (
<div style={{ fontSize: 13, marginTop: 4 }}> <div style={{ fontSize: 13, marginTop: 4 }}>
Токен истекает: {new Date(status.tokenExpiresAt).toLocaleString()} Токен истекает: {new Date(status.tokenExpiresAt!).toLocaleString()}
</div> </div>
)}
</div> </div>
)} )}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 500 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 500 }}>
<button onClick={handleGetKey} disabled={loading} {hasPlugin && certs.length > 0 && (
style={btnStyle}> <div>
{loading ? 'Загрузка...' : '1. Получить ключ авторизации'} <label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
</button> Сертификат:
</label>
{dataToSign && ( <select
<div style={{ background: '#f5f5f5', padding: 8, borderRadius: 4, fontSize: 12, wordBreak: 'break-all' }}> value={selectedThumbprint}
<strong>Данные для подписи:</strong><br /> onChange={e => setSelectedThumbprint(e.target.value)}
{dataToSign} style={selectStyle}
>
<option value="">— первый доступный —</option>
{certs.map(c => (
<option key={c.thumbprint} value={c.thumbprint} disabled={!c.valid}>
{c.name} ({c.valid ? `до ${new Date(c.validTo).toLocaleDateString()}` : 'просрочен'})
</option>
))}
</select>
</div> </div>
)} )}
{uuid && ( {certs.length === 0 && hasPlugin && (
<> <div style={{ color: '#e65100', fontSize: 13 }}>
<textarea Нет доступных сертификатов. Установите УКЭП в систему.
placeholder="Вставьте подпись (base64) из КриптоПро..." </div>
value={signature}
onChange={e => setSignature(e.target.value)}
rows={4}
style={inputStyle}
/>
<button onClick={handleSignIn} disabled={loading || !signature}
style={btnStyle}>
{loading ? 'Подписание...' : '2. Отправить подпись'}
</button>
</>
)} )}
<button
onClick={handleSignIn}
disabled={loading || !hasPlugin || (hasPlugin && certs.length === 0)}
style={btnStyle}
>
{loading ? 'Подписание...' : 'Подписать и войти'}
</button>
{error && ( {error && (
<div style={{ color: '#c62828', fontSize: 14 }}>Ошибка: {error}</div> <div style={{ color: '#c62828', fontSize: 14, marginTop: 8 }}>Ошибка: {error}</div>
)} )}
</div> </div>
<div style={{ marginTop: 24, fontSize: 13, color: '#666' }}> <div style={{ marginTop: 24, fontSize: 13, color: '#666' }}>
<h4>Инструкция:</h4> <h4>Процесс авторизации:</h4>
<ol> <ol>
<li>Нажмите «Получить ключ авторизации» — система получит UUID и случайные данные для подписи</li> <li>Выберите сертификат УКЭП из списка (или будет использован первый доступный)</li>
<li>Подпишите полученные данные в КриптоПро (CAdES-BES, присоединённая подпись, base64)</li> <li>Нажмите «Подписать и войти»</li>
<li>Вставьте подпись в поле выше и нажмите «Отправить подпись»</li> <li>КриптоПро подпишет данные и отправит их на сервер</li>
<li>Сервер кеширует токен доступа к True API (действует 10 часов)</li>
</ol> </ol>
</div> </div>
</div> </div>
@@ -124,12 +145,11 @@ const btnStyle: React.CSSProperties = {
fontSize: 14, fontSize: 14,
} }
const inputStyle: React.CSSProperties = { const selectStyle: React.CSSProperties = {
padding: 8, padding: 8,
border: '1px solid #ccc', border: '1px solid #ccc',
borderRadius: 4, borderRadius: 4,
fontSize: 13, fontSize: 13,
fontFamily: 'monospace',
width: '100%', width: '100%',
boxSizing: 'border-box', boxSizing: 'border-box',
} }
+15 -4
View File
@@ -3,6 +3,8 @@ import { uploadUpd } from '../services/api'
import { ResultsTable } from '../components/ResultsTable' import { ResultsTable } from '../components/ResultsTable'
import type { UpdUploadResponse } from '../types' import type { UpdUploadResponse } from '../types'
const MAX_FILE_SIZE = 10 * 1024 * 1024
export function UploadUpdPage() { export function UploadUpdPage() {
const [file, setFile] = useState<File | null>(null) const [file, setFile] = useState<File | null>(null)
const [response, setResponse] = useState<UpdUploadResponse | null>(null) const [response, setResponse] = useState<UpdUploadResponse | null>(null)
@@ -11,6 +13,16 @@ export function UploadUpdPage() {
const [dragging, setDragging] = useState(false) const [dragging, setDragging] = useState(false)
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
function setFileIfValid(f: File | null) {
if (!f) { setFile(null); return }
if (f.size > MAX_FILE_SIZE) {
setError(`Файл слишком большой (максимум 10MB)`)
return
}
setError('')
setFile(f)
}
async function handleUpload() { async function handleUpload() {
if (!file) return if (!file) return
setLoading(true) setLoading(true)
@@ -28,8 +40,7 @@ export function UploadUpdPage() {
function handleDrop(e: React.DragEvent) { function handleDrop(e: React.DragEvent) {
e.preventDefault() e.preventDefault()
setDragging(false) setDragging(false)
const f = e.dataTransfer.files[0] setFileIfValid(e.dataTransfer.files[0] || null)
if (f) setFile(f)
} }
return ( return (
@@ -69,9 +80,9 @@ export function UploadUpdPage() {
<input <input
ref={inputRef} ref={inputRef}
type="file" type="file"
accept=".xml" accept=".xml,.XML"
hidden hidden
onChange={e => setFile(e.target.files?.[0] || null)} onChange={e => setFileIfValid(e.target.files?.[0] || null)}
/> />
</div> </div>
+26 -2
View File
@@ -2,11 +2,27 @@ import type { AuthStatus, CheckCodesResponse, UpdUploadResponse } from '../types
const BASE_URL = '' const BASE_URL = ''
let onUnauthorized: (() => void) | null = null
export function setOnUnauthorized(cb: () => void): void {
onUnauthorized = cb
}
async function request<T>(url: string, options?: RequestInit): Promise<T> { async function request<T>(url: string, options?: RequestInit): Promise<T> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (options?.headers) {
Object.assign(headers, options.headers)
}
const res = await fetch(`${BASE_URL}${url}`, { const res = await fetch(`${BASE_URL}${url}`, {
headers: { 'Content-Type': 'application/json', ...options?.headers }, headers,
...options, ...options,
}) })
if (res.status === 401 && onUnauthorized) {
onUnauthorized()
}
if (!res.ok) { if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText })) const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || `HTTP ${res.status}`) throw new Error(err.error || `HTTP ${res.status}`)
@@ -19,7 +35,7 @@ export async function getAuthKey(): Promise<{ uuid: string; data: string }> {
} }
export async function signIn(uuid: string, data: string): Promise<{ token: string }> { export async function signIn(uuid: string, data: string): Promise<{ token: string }> {
return request('/auth/signin', { return request('/auth/simpleSignIn', {
method: 'POST', method: 'POST',
body: JSON.stringify({ uuid, data }), body: JSON.stringify({ uuid, data }),
}) })
@@ -29,6 +45,10 @@ export async function getAuthStatus(): Promise<AuthStatus> {
return request('/auth/status') return request('/auth/status')
} }
export async function logout(): Promise<void> {
await request('/auth/logout', { method: 'POST' })
}
export async function checkCodesPublic(codes: string[]): Promise<CheckCodesResponse> { export async function checkCodesPublic(codes: string[]): Promise<CheckCodesResponse> {
return request('/api/check-codes/public', { return request('/api/check-codes/public', {
method: 'POST', method: 'POST',
@@ -52,6 +72,10 @@ export async function uploadUpd(file: File): Promise<UpdUploadResponse> {
body: formData, body: formData,
}) })
if (res.status === 401 && onUnauthorized) {
onUnauthorized()
}
if (!res.ok) { if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText })) const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || `HTTP ${res.status}`) throw new Error(err.error || `HTTP ${res.status}`)
+59
View File
@@ -0,0 +1,59 @@
import {
getUserCertificates,
createAttachedSignature,
} from 'crypto-pro'
export interface CertInfo {
name: string
thumbprint: string
issuer: string
validTo: string
valid: boolean
}
export async function isCadesPluginAvailable(): Promise<boolean> {
try {
await getUserCertificates(true)
return true
} catch (err) {
if (err instanceof Error && (
err.message.includes('undefined') || err.message.includes('not defined')
)) return false
throw err
}
}
export async function listCertificates(): Promise<CertInfo[]> {
const certs = await getUserCertificates(true)
const now = Date.now()
return certs.map(c => {
const validTo = new Date(c.validTo)
return {
name: c.name || 'Без имени',
thumbprint: c.thumbprint,
issuer: c.issuerName,
validTo: c.validTo,
valid: validTo.getTime() > now,
}
})
}
export async function signWithCadesPlugin(dataBase64: string, thumbprint?: string): Promise<string> {
const certs = await getUserCertificates(true)
const now = Date.now()
const validCerts = certs.filter(c => c.name && new Date(c.validTo).getTime() > now)
if (validCerts.length === 0) {
throw new Error('Нет доступных сертификатов с действующим сроком')
}
let tp = thumbprint
if (!tp) {
tp = validCerts[0].thumbprint
} else {
const found = validCerts.find(c => c.thumbprint.toUpperCase() === tp!.toUpperCase())
if (!found) throw new Error(`Сертификат с отпечатком ${tp} не найден или просрочен`)
}
return createAttachedSignature(tp, dataBase64)
}
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/main.tsx","./src/components/resultstable.tsx","./src/pages/authpage.tsx","./src/pages/checkcodespage.tsx","./src/pages/uploadupdpage.tsx","./src/services/api.ts","./src/types/index.ts"],"version":"5.9.3"} {"root":["./src/app.tsx","./src/main.tsx","./src/components/resultstable.tsx","./src/pages/authpage.tsx","./src/pages/checkcodespage.tsx","./src/pages/uploadupdpage.tsx","./src/services/api.ts","./src/services/cadesplugin.ts","./src/types/index.ts"],"version":"5.9.3"}