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:
@@ -4,21 +4,14 @@
|
||||
|
||||
## Архитектура
|
||||
|
||||
- **Backend**: Fastify + TypeScript
|
||||
- **Frontend**: React + Vite + TypeScript
|
||||
- **Backend**: Fastify + TypeScript (прокси-сервер к True API)
|
||||
- **Frontend**: React + Vite + TypeScript (SPA с интеграцией КриптоПро Browser Plugin)
|
||||
- **Docker**: docker-compose (2 сервиса: backend, frontend)
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
```bash
|
||||
# Клонировать и перейти в директорию
|
||||
cd chestno-api
|
||||
|
||||
# Настроить окружение
|
||||
cp backend/.env.example backend/.env
|
||||
# Отредактировать backend/.env — указать thumbprint сертификата
|
||||
|
||||
# Запустить
|
||||
docker-compose up --build
|
||||
```
|
||||
|
||||
@@ -30,14 +23,10 @@ docker-compose up --build
|
||||
|
||||
```bash
|
||||
# Backend
|
||||
cd backend
|
||||
npm install
|
||||
npm run dev
|
||||
cd backend && npm install && npm run dev
|
||||
|
||||
# Frontend (в отдельном терминале)
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
cd frontend && npm install && npm run dev
|
||||
```
|
||||
|
||||
## Структура проекта
|
||||
@@ -47,39 +36,34 @@ backend/
|
||||
src/
|
||||
config.ts # Конфигурация
|
||||
index.ts # Точка входа Fastify
|
||||
routes/
|
||||
auth.ts # GET /auth/key, POST /auth/signin, GET /auth/status
|
||||
cises.ts # POST /api/check-codes/public, /api/check-codes/auth
|
||||
upd.ts # POST /api/upload-upd
|
||||
services/
|
||||
auth-service.ts # True API аутентификация + подпись через КриптоПро
|
||||
cises-service.ts # Проверка КМ (публичная / авторизованная)
|
||||
token-cache.ts # Кеширование токена (node-cache, TTL 10ч)
|
||||
upd-parser.ts # Парсинг XML УПД (формат Приказа №970)
|
||||
types/
|
||||
index.ts # TypeScript типы
|
||||
routes/auth.ts # GET /auth/key, POST /auth/simpleSignIn, GET /auth/status, POST /auth/logout
|
||||
routes/cises.ts # POST /api/check-codes/public, POST /api/check-codes/auth
|
||||
routes/upd.ts # POST /api/upload-upd
|
||||
services/auth-service.ts # Прокси к True API auth
|
||||
services/cises-service.ts # Проверка КМ (публичная / авторизованная)
|
||||
services/token-cache.ts # Кеширование токена (node-cache, TTL 10ч)
|
||||
services/upd-parser.ts # Парсинг XML УПД (формат Приказа №970)
|
||||
types/index.ts
|
||||
|
||||
frontend/
|
||||
src/
|
||||
App.tsx # Корневой компонент с навигацией
|
||||
pages/
|
||||
AuthPage.tsx # Авторизация
|
||||
CheckCodesPage.tsx# Проверка кодов
|
||||
UploadUpdPage.tsx # Загрузка УПД
|
||||
components/
|
||||
ResultsTable.tsx # Таблица результатов с цветовой индикацией
|
||||
services/
|
||||
api.ts # HTTP-клиент к backend
|
||||
types/
|
||||
index.ts # TypeScript типы
|
||||
App.tsx
|
||||
pages/AuthPage.tsx # Авторизация через КриптоПро Browser Plugin
|
||||
pages/CheckCodesPage.tsx # Проверка кодов
|
||||
pages/UploadUpdPage.tsx # Загрузка УПД
|
||||
components/ResultsTable.tsx
|
||||
services/api.ts # HTTP-клиент
|
||||
services/cadesplugin.ts # Интеграция с КриптоПро Browser Plugin
|
||||
types/index.ts
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Аутентификация
|
||||
- `GET /auth/key` — получение UUID + data для подписи
|
||||
- `POST /auth/signin` — отправка подписи, получение токена
|
||||
- `POST /auth/simpleSignIn` — отправка подписи, получение токена
|
||||
- `GET /auth/status` — статус авторизации
|
||||
- `POST /auth/logout` — сброс токена
|
||||
|
||||
### Проверка кодов
|
||||
- `POST /api/check-codes/public` — публичная проверка (без авторизации)
|
||||
@@ -96,14 +80,14 @@ frontend/
|
||||
| `HOST` | Хост | `0.0.0.0` |
|
||||
| `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` |
|
||||
| `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
|
||||
```
|
||||
> Подпись выполняется **на стороне клиента** — закрытый ключ УКЭП не покидает устройство пользователя.
|
||||
|
||||
@@ -2,4 +2,4 @@ PORT=3001
|
||||
HOST=0.0.0.0
|
||||
TRUE_API_URL=https://markirovka.sandbox.crptech.ru/api/v3/true-api
|
||||
PUBLIC_CHECK_URL=https://mobile.api.crpt.ru/mobile/check
|
||||
CERT_THUMBPRINT=your-certificate-thumbprint-here
|
||||
CORS_ORIGIN=*
|
||||
|
||||
@@ -2,6 +2,8 @@ export const config = {
|
||||
port: parseInt(process.env.PORT || '3001', 10),
|
||||
host: process.env.HOST || '0.0.0.0',
|
||||
|
||||
corsOrigin: process.env.CORS_ORIGIN || '*',
|
||||
|
||||
trueApi: {
|
||||
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',
|
||||
@@ -10,5 +12,7 @@ export const config = {
|
||||
codesCheckPath: '/codes/check',
|
||||
batchSize: 1000,
|
||||
tokenTTL: 10 * 60 * 60 * 1000,
|
||||
maxRetries: 3,
|
||||
publicCheckConcurrency: 10,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -8,8 +8,14 @@ import { updRoutes } from './routes/upd.js'
|
||||
|
||||
const app = Fastify({ logger: true })
|
||||
|
||||
await app.register(cors, { origin: true })
|
||||
await app.register(multipart)
|
||||
await app.register(cors, { origin: config.corsOrigin })
|
||||
await app.register(multipart, {
|
||||
limits: {
|
||||
fileSize: 10 * 1024 * 1024,
|
||||
files: 1,
|
||||
},
|
||||
throwFileSizeLimit: true,
|
||||
})
|
||||
|
||||
await app.register(authRoutes)
|
||||
await app.register(cisesRoutes)
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { getAuthKey, signIn } from '../services/auth-service.js'
|
||||
import { getTokenTTL, hasToken } from '../services/token-cache.js'
|
||||
import { getAuthKey, signIn, clearToken, isAuthenticated } from '../services/auth-service.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> {
|
||||
app.get('/auth/key', async () => {
|
||||
@@ -8,18 +19,23 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
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 result = await signIn({ uuid, data })
|
||||
return result
|
||||
})
|
||||
|
||||
app.get('/auth/status', async () => {
|
||||
const authenticated = hasToken()
|
||||
const authenticated = isAuthenticated()
|
||||
const ttl = getTokenTTL()
|
||||
return {
|
||||
authenticated,
|
||||
tokenExpiresAt: ttl ? new Date(ttl).toISOString() : null,
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/auth/logout', async () => {
|
||||
clearToken()
|
||||
return { success: true }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,13 +1,35 @@
|
||||
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'
|
||||
|
||||
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> {
|
||||
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)
|
||||
})
|
||||
|
||||
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', async (request) => {
|
||||
return checkCodesAuth(request.body)
|
||||
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', { schema: checkCodesSchema }, async (request, reply) => {
|
||||
try {
|
||||
return await checkCodesAuth(request.body)
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) {
|
||||
return reply.status(err.statusCode).send({ error: err.message })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
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> {
|
||||
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 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) {
|
||||
return reply.status(400).send({ error: 'No marking codes found in UPD' })
|
||||
}
|
||||
|
||||
try {
|
||||
const checkResults = await checkCodesAuth({ codes: parsed.codes })
|
||||
|
||||
return {
|
||||
@@ -32,5 +38,11 @@ export async function updRoutes(app: FastifyInstance): Promise<void> {
|
||||
codesFound: parsed.codes.length,
|
||||
results: checkResults,
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) {
|
||||
return reply.status(err.statusCode).send({ error: err.message })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import got from 'got'
|
||||
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'
|
||||
|
||||
const authClient = got.extend({
|
||||
@@ -21,29 +21,14 @@ export async function signIn(body: AuthSignInRequest): Promise<AuthSignInRespons
|
||||
return response
|
||||
}
|
||||
|
||||
export async function getValidToken(): Promise<string> {
|
||||
const cached = getToken()
|
||||
if (cached) return cached
|
||||
|
||||
const { uuid, data } = await getAuthKey()
|
||||
const signature = await signData(data)
|
||||
const { token } = await signIn({ uuid, data: signature })
|
||||
return token
|
||||
export function getCachedToken(): string | undefined {
|
||||
return getToken()
|
||||
}
|
||||
|
||||
async function signData(data: string): Promise<string> {
|
||||
try {
|
||||
const { execSync } = await import('child_process')
|
||||
|
||||
const thumbprint = process.env.CERT_THUMBPRINT
|
||||
if (!thumbprint) throw new Error('CERT_THUMBPRINT not set')
|
||||
|
||||
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}`)
|
||||
export function clearToken(): void {
|
||||
invalidateToken()
|
||||
}
|
||||
|
||||
export function isAuthenticated(): boolean {
|
||||
return !!getToken()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import got from 'got'
|
||||
import { config } from '../config.js'
|
||||
import { getValidToken } from './auth-service.js'
|
||||
import { getCachedToken, clearToken } from './auth-service.js'
|
||||
import type {
|
||||
CisInfoResponse,
|
||||
PublicCheckResponse,
|
||||
@@ -16,12 +16,15 @@ const apiClient = got.extend({
|
||||
|
||||
export async function checkCodesPublic(body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||
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 {
|
||||
const { body: response } = await got.get<PublicCheckResponse>(
|
||||
`${config.trueApi.publicCheckUrl}?code=${encodeURIComponent(code)}`,
|
||||
{ responseType: 'json' }
|
||||
{ responseType: 'json', timeout: { request: 10000 } }
|
||||
)
|
||||
results.push({
|
||||
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)
|
||||
}
|
||||
|
||||
function getToken(): string {
|
||||
const token = getCachedToken()
|
||||
if (!token) throw new AppError('Not authenticated', 401)
|
||||
return token
|
||||
}
|
||||
|
||||
export async function checkCodesAuth(body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||
const token = await getValidToken()
|
||||
const token = getToken()
|
||||
const results: SingleCodeResult[] = []
|
||||
|
||||
for (let i = 0; i < body.codes.length; i += config.trueApi.batchSize) {
|
||||
const batch = body.codes.slice(i, i + config.trueApi.batchSize)
|
||||
try {
|
||||
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 {
|
||||
const { body: response } = await apiClient.post<CisInfoResponse>(
|
||||
config.trueApi.cisesInfoPath,
|
||||
{
|
||||
json: { cisList: batch },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: { request: 30000 },
|
||||
}
|
||||
)
|
||||
|
||||
@@ -71,20 +116,45 @@ export async function checkCodesAuth(body: CheckCodesRequest): Promise<CheckCode
|
||||
ownerName: item.ownerName,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
for (const code of batch) {
|
||||
results.push({
|
||||
code,
|
||||
found: false,
|
||||
valid: false,
|
||||
status: 'ERROR',
|
||||
error: 'Auth API error',
|
||||
})
|
||||
} catch (err) {
|
||||
if (is401(err)) {
|
||||
throw new AppError('Token expired', 401)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
return buildResponse(results)
|
||||
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 {
|
||||
|
||||
@@ -23,3 +23,7 @@ export function hasToken(): boolean {
|
||||
export function getTokenTTL(): number | undefined {
|
||||
return cache.getTtl(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function invalidateToken(): void {
|
||||
cache.del(TOKEN_KEY)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ export interface ParsedUpd {
|
||||
|
||||
export async function parseUpdXml(xmlContent: string, fileName: string): Promise<ParsedUpd> {
|
||||
const parsed = await parseStringPromise(xmlContent, {
|
||||
explicitArray: false,
|
||||
ignoreAttrs: false,
|
||||
mergeAttrs: true,
|
||||
})
|
||||
@@ -21,42 +20,44 @@ export async function parseUpdXml(xmlContent: string, fileName: string): Promise
|
||||
return {
|
||||
codes,
|
||||
fileName,
|
||||
documentNumber: extractField(parsed, 'Документ', 'НомерДок'),
|
||||
documentDate: extractField(parsed, 'Документ', 'ДатаДок'),
|
||||
sellerName: extractField(parsed, 'Документ', 'ТаблСчФакт', 'СведПрод', 'НаимОрг'),
|
||||
buyerName: extractField(parsed, 'Документ', 'ТаблСчФакт', 'СведПокуп', 'НаимОрг'),
|
||||
documentNumber: extractField(parsed, ['Документ', 'НомерДок']),
|
||||
documentDate: extractField(parsed, ['Документ', 'ДатаДок']),
|
||||
sellerName: extractField(parsed, ['Документ', 'ТаблСчФакт', 'СведПрод', 'НаимОрг']),
|
||||
buyerName: extractField(parsed, ['Документ', 'ТаблСчФакт', 'СведПокуп', 'НаимОрг']),
|
||||
}
|
||||
}
|
||||
|
||||
function extractCodes(obj: Record<string, unknown>): string[] {
|
||||
const codes: string[] = []
|
||||
const documents = asArray<Record<string, unknown>>(obj['Документ'])
|
||||
|
||||
for (const document of documents) {
|
||||
try {
|
||||
const document = obj['Документ'] as Record<string, unknown>
|
||||
const table = document['ТаблСчФакт'] as Record<string, unknown>
|
||||
const items = table['СведТов'] as Record<string, unknown>[]
|
||||
const table = document['ТаблСчФакт'] as Record<string, unknown> | undefined
|
||||
if (!table) continue
|
||||
const items = asArray<Record<string, unknown>>(table['СведТов'])
|
||||
|
||||
if (Array.isArray(items)) {
|
||||
for (const item of items) {
|
||||
const extInfo = item['ДопСведТов'] as Record<string, unknown>
|
||||
if (extInfo) {
|
||||
const kmCodes = extInfo['НомСредИдентТов']
|
||||
if (Array.isArray(kmCodes)) {
|
||||
const extInfo = asArray<Record<string, unknown>>(item['ДопСведТов'])
|
||||
for (const info of extInfo) {
|
||||
const kmCodes = asArray<string>(info['НомСредИдентТов'])
|
||||
codes.push(...kmCodes.filter(Boolean))
|
||||
} else if (typeof kmCodes === 'string') {
|
||||
codes.push(kmCodes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// XML structure may vary; return what we found
|
||||
console.warn('upd-parser: failed to extract codes from a document')
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
for (const key of keys) {
|
||||
if (current && typeof current === 'object') {
|
||||
|
||||
Generated
+7
@@ -8,6 +8,7 @@
|
||||
"name": "chestny-znak-api-frontend",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"crypto-pro": "^2.3.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
@@ -1725,6 +1726,12 @@
|
||||
"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": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"crypto-pro": "^2.3.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
},
|
||||
@@ -18,8 +19,8 @@
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"eslint": "^9.19.0",
|
||||
"typescript": "^5.7.3",
|
||||
"vite": "^6.1.0",
|
||||
"eslint": "^9.19.0"
|
||||
"vite": "^6.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
+40
-5
@@ -1,7 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { AuthPage } from './pages/AuthPage'
|
||||
import { CheckCodesPage } from './pages/CheckCodesPage'
|
||||
import { UploadUpdPage } from './pages/UploadUpdPage'
|
||||
import { setOnUnauthorized, logout as apiLogout } from './services/api'
|
||||
|
||||
type Page = 'auth' | 'check' | 'upload'
|
||||
|
||||
@@ -9,6 +10,24 @@ export default function App() {
|
||||
const [page, setPage] = useState<Page>('auth')
|
||||
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 (
|
||||
<div style={{ minHeight: '100vh', background: '#f5f5f5' }}>
|
||||
<header style={{
|
||||
@@ -26,21 +45,37 @@ export default function App() {
|
||||
Авторизация
|
||||
</button>
|
||||
<button onClick={() => setPage('check')}
|
||||
style={navBtnStyle(page === 'check')}>
|
||||
style={navBtnStyle(page === 'check')}
|
||||
disabled={!authenticated}>
|
||||
Проверка кода
|
||||
</button>
|
||||
<button onClick={() => setPage('upload')}
|
||||
style={navBtnStyle(page === 'upload')}>
|
||||
style={navBtnStyle(page === 'upload')}
|
||||
disabled={!authenticated}>
|
||||
Загрузка УПД
|
||||
</button>
|
||||
</nav>
|
||||
<div style={{ marginLeft: 'auto', fontSize: 13 }}>
|
||||
<div style={{ marginLeft: 'auto', fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{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>
|
||||
</header>
|
||||
|
||||
<main style={{ padding: 24, maxWidth: 960, margin: '0 auto' }}>
|
||||
{page === 'auth' && <AuthPage onAuth={() => setAuthenticated(true)} />}
|
||||
{page === 'auth' && <AuthPage onAuth={handleAuth} />}
|
||||
{page === 'check' && <CheckCodesPage />}
|
||||
{page === 'upload' && <UploadUpdPage />}
|
||||
</main>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { getAuthStatus, getAuthKey, signIn } from '../services/api'
|
||||
import { isCadesPluginAvailable, listCertificates, signWithCadesPlugin } from '../services/cadesplugin'
|
||||
import type { CertInfo } from '../services/cadesplugin'
|
||||
|
||||
interface Props {
|
||||
onAuth: () => void
|
||||
@@ -7,27 +9,25 @@ interface Props {
|
||||
|
||||
export function AuthPage({ onAuth }: Props) {
|
||||
const [status, setStatus] = useState<{ authenticated: boolean; tokenExpiresAt: string | null } | null>(null)
|
||||
const [uuid, setUuid] = useState('')
|
||||
const [dataToSign, setDataToSign] = useState('')
|
||||
const [signature, setSignature] = useState('')
|
||||
const [hasPlugin, setHasPlugin] = useState<boolean | null>(null)
|
||||
const [certs, setCerts] = useState<CertInfo[]>([])
|
||||
const [selectedThumbprint, setSelectedThumbprint] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
getAuthStatus().then(setStatus).catch(() => {})
|
||||
checkPlugin()
|
||||
}, [])
|
||||
|
||||
async function handleGetKey() {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
async function checkPlugin() {
|
||||
const available = await isCadesPluginAvailable()
|
||||
setHasPlugin(available)
|
||||
if (available) {
|
||||
try {
|
||||
const { uuid, data } = await getAuthKey()
|
||||
setUuid(uuid)
|
||||
setDataToSign(data)
|
||||
} catch (err) {
|
||||
setError(String(err))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
const certList = await listCertificates()
|
||||
setCerts(certList)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,12 +35,14 @@ export function AuthPage({ onAuth }: Props) {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const { uuid, data } = await getAuthKey()
|
||||
const signature = await signWithCadesPlugin(data, selectedThumbprint || undefined)
|
||||
await signIn(uuid, signature)
|
||||
const s = await getAuthStatus()
|
||||
setStatus(s)
|
||||
if (s.authenticated) onAuth()
|
||||
} catch (err) {
|
||||
setError(String(err))
|
||||
setError(String(err instanceof Error ? err.message : err))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
@@ -50,64 +52,83 @@ export function AuthPage({ onAuth }: Props) {
|
||||
<div>
|
||||
<h2>Авторизация в True API</h2>
|
||||
|
||||
{status && (
|
||||
{hasPlugin === false && (
|
||||
<div style={{
|
||||
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,
|
||||
marginBottom: 16,
|
||||
}}>
|
||||
<strong>Статус:</strong>{' '}
|
||||
{status.authenticated ? '✅ Авторизован' : '❌ Не авторизован'}
|
||||
{status.tokenExpiresAt && (
|
||||
<strong>✅ Авторизован</strong>
|
||||
<div style={{ fontSize: 13, marginTop: 4 }}>
|
||||
Токен истекает: {new Date(status.tokenExpiresAt).toLocaleString()}
|
||||
Токен истекает: {new Date(status.tokenExpiresAt!).toLocaleString()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 500 }}>
|
||||
<button onClick={handleGetKey} disabled={loading}
|
||||
style={btnStyle}>
|
||||
{loading ? 'Загрузка...' : '1. Получить ключ авторизации'}
|
||||
</button>
|
||||
|
||||
{dataToSign && (
|
||||
<div style={{ background: '#f5f5f5', padding: 8, borderRadius: 4, fontSize: 12, wordBreak: 'break-all' }}>
|
||||
<strong>Данные для подписи:</strong><br />
|
||||
{dataToSign}
|
||||
{hasPlugin && certs.length > 0 && (
|
||||
<div>
|
||||
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||
Сертификат:
|
||||
</label>
|
||||
<select
|
||||
value={selectedThumbprint}
|
||||
onChange={e => setSelectedThumbprint(e.target.value)}
|
||||
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>
|
||||
)}
|
||||
|
||||
{uuid && (
|
||||
<>
|
||||
<textarea
|
||||
placeholder="Вставьте подпись (base64) из КриптоПро..."
|
||||
value={signature}
|
||||
onChange={e => setSignature(e.target.value)}
|
||||
rows={4}
|
||||
style={inputStyle}
|
||||
/>
|
||||
|
||||
<button onClick={handleSignIn} disabled={loading || !signature}
|
||||
style={btnStyle}>
|
||||
{loading ? 'Подписание...' : '2. Отправить подпись'}
|
||||
</button>
|
||||
</>
|
||||
{certs.length === 0 && hasPlugin && (
|
||||
<div style={{ color: '#e65100', fontSize: 13 }}>
|
||||
Нет доступных сертификатов. Установите УКЭП в систему.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleSignIn}
|
||||
disabled={loading || !hasPlugin || (hasPlugin && certs.length === 0)}
|
||||
style={btnStyle}
|
||||
>
|
||||
{loading ? 'Подписание...' : 'Подписать и войти'}
|
||||
</button>
|
||||
|
||||
{error && (
|
||||
<div style={{ color: '#c62828', fontSize: 14 }}>Ошибка: {error}</div>
|
||||
<div style={{ color: '#c62828', fontSize: 14, marginTop: 8 }}>Ошибка: {error}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 24, fontSize: 13, color: '#666' }}>
|
||||
<h4>Инструкция:</h4>
|
||||
<h4>Процесс авторизации:</h4>
|
||||
<ol>
|
||||
<li>Нажмите «Получить ключ авторизации» — система получит UUID и случайные данные для подписи</li>
|
||||
<li>Подпишите полученные данные в КриптоПро (CAdES-BES, присоединённая подпись, base64)</li>
|
||||
<li>Вставьте подпись в поле выше и нажмите «Отправить подпись»</li>
|
||||
<li>Выберите сертификат УКЭП из списка (или будет использован первый доступный)</li>
|
||||
<li>Нажмите «Подписать и войти»</li>
|
||||
<li>КриптоПро подпишет данные и отправит их на сервер</li>
|
||||
<li>Сервер кеширует токен доступа к True API (действует 10 часов)</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
@@ -124,12 +145,11 @@ const btnStyle: React.CSSProperties = {
|
||||
fontSize: 14,
|
||||
}
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
const selectStyle: React.CSSProperties = {
|
||||
padding: 8,
|
||||
border: '1px solid #ccc',
|
||||
borderRadius: 4,
|
||||
fontSize: 13,
|
||||
fontFamily: 'monospace',
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { uploadUpd } from '../services/api'
|
||||
import { ResultsTable } from '../components/ResultsTable'
|
||||
import type { UpdUploadResponse } from '../types'
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||
|
||||
export function UploadUpdPage() {
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [response, setResponse] = useState<UpdUploadResponse | null>(null)
|
||||
@@ -11,6 +13,16 @@ export function UploadUpdPage() {
|
||||
const [dragging, setDragging] = useState(false)
|
||||
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() {
|
||||
if (!file) return
|
||||
setLoading(true)
|
||||
@@ -28,8 +40,7 @@ export function UploadUpdPage() {
|
||||
function handleDrop(e: React.DragEvent) {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
const f = e.dataTransfer.files[0]
|
||||
if (f) setFile(f)
|
||||
setFileIfValid(e.dataTransfer.files[0] || null)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -69,9 +80,9 @@ export function UploadUpdPage() {
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".xml"
|
||||
accept=".xml,.XML"
|
||||
hidden
|
||||
onChange={e => setFile(e.target.files?.[0] || null)}
|
||||
onChange={e => setFileIfValid(e.target.files?.[0] || null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,11 +2,27 @@ import type { AuthStatus, CheckCodesResponse, UpdUploadResponse } from '../types
|
||||
|
||||
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> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
|
||||
if (options?.headers) {
|
||||
Object.assign(headers, options.headers)
|
||||
}
|
||||
|
||||
const res = await fetch(`${BASE_URL}${url}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
headers,
|
||||
...options,
|
||||
})
|
||||
|
||||
if (res.status === 401 && onUnauthorized) {
|
||||
onUnauthorized()
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: res.statusText }))
|
||||
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 }> {
|
||||
return request('/auth/signin', {
|
||||
return request('/auth/simpleSignIn', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ uuid, data }),
|
||||
})
|
||||
@@ -29,6 +45,10 @@ export async function getAuthStatus(): Promise<AuthStatus> {
|
||||
return request('/auth/status')
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await request('/auth/logout', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function checkCodesPublic(codes: string[]): Promise<CheckCodesResponse> {
|
||||
return request('/api/check-codes/public', {
|
||||
method: 'POST',
|
||||
@@ -52,6 +72,10 @@ export async function uploadUpd(file: File): Promise<UpdUploadResponse> {
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (res.status === 401 && onUnauthorized) {
|
||||
onUnauthorized()
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: res.statusText }))
|
||||
throw new Error(err.error || `HTTP ${res.status}`)
|
||||
|
||||
@@ -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 @@
|
||||
{"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"}
|
||||
Reference in New Issue
Block a user