bootstrap
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
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
|
||||
@@ -0,0 +1,14 @@
|
||||
FROM node:20-alpine AS builder
|
||||
WORKDIR /app
|
||||
COPY package.json tsconfig.json ./
|
||||
RUN npm ci
|
||||
COPY src/ ./src/
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS runner
|
||||
WORKDIR /app
|
||||
COPY package.json ./
|
||||
RUN npm ci --production
|
||||
COPY --from=builder /app/dist ./dist
|
||||
EXPOSE 3001
|
||||
CMD ["node", "dist/index.js"]
|
||||
Generated
+2729
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "chestny-znak-api-backend",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"lint": "tsc --noEmit",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.0.1",
|
||||
"@fastify/multipart": "^9.0.3",
|
||||
"fastify": "^5.3.1",
|
||||
"got": "^14.4.6",
|
||||
"node-cache": "^5.1.2",
|
||||
"xml2js": "^0.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.13.1",
|
||||
"@types/xml2js": "^0.4.14",
|
||||
"eslint": "^9.19.0",
|
||||
"tsx": "^4.19.3",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export const config = {
|
||||
port: parseInt(process.env.PORT || '3001', 10),
|
||||
host: process.env.HOST || '0.0.0.0',
|
||||
|
||||
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',
|
||||
authPath: '/auth',
|
||||
cisesInfoPath: '/cises/info',
|
||||
codesCheckPath: '/codes/check',
|
||||
batchSize: 1000,
|
||||
tokenTTL: 10 * 60 * 60 * 1000,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import Fastify from 'fastify'
|
||||
import cors from '@fastify/cors'
|
||||
import multipart from '@fastify/multipart'
|
||||
import { config } from './config.js'
|
||||
import { authRoutes } from './routes/auth.js'
|
||||
import { cisesRoutes } from './routes/cises.js'
|
||||
import { updRoutes } from './routes/upd.js'
|
||||
|
||||
const app = Fastify({ logger: true })
|
||||
|
||||
await app.register(cors, { origin: true })
|
||||
await app.register(multipart)
|
||||
|
||||
await app.register(authRoutes)
|
||||
await app.register(cisesRoutes)
|
||||
await app.register(updRoutes)
|
||||
|
||||
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }))
|
||||
|
||||
try {
|
||||
await app.listen({ port: config.port, host: config.host })
|
||||
console.log(`Server running on http://${config.host}:${config.port}`)
|
||||
} catch (err) {
|
||||
app.log.error(err)
|
||||
process.exit(1)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { getAuthKey, signIn } from '../services/auth-service.js'
|
||||
import { getTokenTTL, hasToken } from '../services/token-cache.js'
|
||||
|
||||
export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get('/auth/key', async () => {
|
||||
const authKey = await getAuthKey()
|
||||
return { uuid: authKey.uuid, data: authKey.data }
|
||||
})
|
||||
|
||||
app.post<{ Body: { uuid: string; data: string } }>('/auth/signin', async (request) => {
|
||||
const { uuid, data } = request.body
|
||||
const result = await signIn({ uuid, data })
|
||||
return result
|
||||
})
|
||||
|
||||
app.get('/auth/status', async () => {
|
||||
const authenticated = hasToken()
|
||||
const ttl = getTokenTTL()
|
||||
return {
|
||||
authenticated,
|
||||
tokenExpiresAt: ttl ? new Date(ttl).toISOString() : null,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { checkCodesPublic, checkCodesAuth } from '../services/cises-service.js'
|
||||
import type { CheckCodesRequest } from '../types/index.js'
|
||||
|
||||
export async function cisesRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/public', async (request) => {
|
||||
return checkCodesPublic(request.body)
|
||||
})
|
||||
|
||||
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', async (request) => {
|
||||
return checkCodesAuth(request.body)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { parseUpdXml } from '../services/upd-parser.js'
|
||||
import { checkCodesAuth } from '../services/cises-service.js'
|
||||
|
||||
export async function updRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.post('/api/upload-upd', async (request, reply) => {
|
||||
const data = await request.file()
|
||||
if (!data) {
|
||||
return reply.status(400).send({ error: 'No file uploaded' })
|
||||
}
|
||||
|
||||
const buffer = await data.toBuffer()
|
||||
const xmlContent = buffer.toString('utf-8')
|
||||
const fileName = data.filename
|
||||
|
||||
const parsed = await parseUpdXml(xmlContent, fileName)
|
||||
|
||||
if (parsed.codes.length === 0) {
|
||||
return reply.status(400).send({ error: 'No marking codes found in UPD' })
|
||||
}
|
||||
|
||||
const checkResults = await checkCodesAuth({ codes: parsed.codes })
|
||||
|
||||
return {
|
||||
document: {
|
||||
number: parsed.documentNumber,
|
||||
date: parsed.documentDate,
|
||||
seller: parsed.sellerName,
|
||||
buyer: parsed.buyerName,
|
||||
fileName: parsed.fileName,
|
||||
},
|
||||
codesFound: parsed.codes.length,
|
||||
results: checkResults,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import got from 'got'
|
||||
import { config } from '../config.js'
|
||||
import { getToken, setToken } from './token-cache.js'
|
||||
import type { AuthKeyResponse, AuthSignInRequest, AuthSignInResponse } from '../types/index.js'
|
||||
|
||||
const authClient = got.extend({
|
||||
prefixUrl: config.trueApi.baseUrl + config.trueApi.authPath,
|
||||
responseType: 'json',
|
||||
})
|
||||
|
||||
export async function getAuthKey(): Promise<AuthKeyResponse> {
|
||||
const { body } = await authClient.get<AuthKeyResponse>('key')
|
||||
return body
|
||||
}
|
||||
|
||||
export async function signIn(body: AuthSignInRequest): Promise<AuthSignInResponse> {
|
||||
const { body: response } = await authClient.post<AuthSignInResponse>('simpleSignIn', {
|
||||
json: body,
|
||||
})
|
||||
setToken(response.token)
|
||||
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
|
||||
}
|
||||
|
||||
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}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import got from 'got'
|
||||
import { config } from '../config.js'
|
||||
import { getValidToken } from './auth-service.js'
|
||||
import type {
|
||||
CisInfoResponse,
|
||||
PublicCheckResponse,
|
||||
CheckCodesRequest,
|
||||
CheckCodesResponse,
|
||||
SingleCodeResult,
|
||||
} from '../types/index.js'
|
||||
|
||||
const apiClient = got.extend({
|
||||
prefixUrl: config.trueApi.baseUrl,
|
||||
responseType: 'json',
|
||||
})
|
||||
|
||||
export async function checkCodesPublic(body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||
const results: SingleCodeResult[] = []
|
||||
|
||||
for (const code of body.codes) {
|
||||
try {
|
||||
const { body: response } = await got.get<PublicCheckResponse>(
|
||||
`${config.trueApi.publicCheckUrl}?code=${encodeURIComponent(code)}`,
|
||||
{ responseType: 'json' }
|
||||
)
|
||||
results.push({
|
||||
code: response.code,
|
||||
found: response.found,
|
||||
valid: response.valid,
|
||||
status: response.status,
|
||||
})
|
||||
} catch {
|
||||
results.push({
|
||||
code,
|
||||
found: false,
|
||||
valid: false,
|
||||
status: 'ERROR',
|
||||
error: 'Public check API error',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return buildResponse(results)
|
||||
}
|
||||
|
||||
export async function checkCodesAuth(body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||
const token = await getValidToken()
|
||||
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 {
|
||||
const { body: response } = await apiClient.post<CisInfoResponse>(
|
||||
config.trueApi.cisesInfoPath,
|
||||
{
|
||||
json: { cisList: batch },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
}
|
||||
)
|
||||
|
||||
for (const item of response.cisInfo) {
|
||||
results.push({
|
||||
code: item.requestedCis,
|
||||
found: !!item.cis,
|
||||
valid: item.status === 'INTRODUCED' || item.status === 'APPLIED' || item.status === 'EMITTED',
|
||||
status: item.status || 'UNKNOWN',
|
||||
gtin: item.gtin,
|
||||
productName: item.productName,
|
||||
producerName: item.producerName,
|
||||
ownerName: item.ownerName,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
for (const code of batch) {
|
||||
results.push({
|
||||
code,
|
||||
found: false,
|
||||
valid: false,
|
||||
status: 'ERROR',
|
||||
error: 'Auth API error',
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return buildResponse(results)
|
||||
}
|
||||
|
||||
function buildResponse(results: SingleCodeResult[]): CheckCodesResponse {
|
||||
return {
|
||||
results,
|
||||
total: results.length,
|
||||
validCount: results.filter(r => r.valid).length,
|
||||
invalidCount: results.filter(r => !r.valid && !r.error).length,
|
||||
errorCount: results.filter(r => !!r.error).length,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import NodeCache from 'node-cache'
|
||||
import { config } from '../config.js'
|
||||
|
||||
const cache = new NodeCache({
|
||||
stdTTL: config.trueApi.tokenTTL / 1000,
|
||||
checkperiod: 600,
|
||||
})
|
||||
|
||||
const TOKEN_KEY = 'true_api_token'
|
||||
|
||||
export function getToken(): string | undefined {
|
||||
return cache.get<string>(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
cache.set(TOKEN_KEY, token)
|
||||
}
|
||||
|
||||
export function hasToken(): boolean {
|
||||
return cache.has(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export function getTokenTTL(): number | undefined {
|
||||
return cache.getTtl(TOKEN_KEY)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { parseStringPromise } from 'xml2js'
|
||||
|
||||
export interface ParsedUpd {
|
||||
codes: string[]
|
||||
fileName: string
|
||||
documentNumber?: string
|
||||
documentDate?: string
|
||||
sellerName?: string
|
||||
buyerName?: string
|
||||
}
|
||||
|
||||
export async function parseUpdXml(xmlContent: string, fileName: string): Promise<ParsedUpd> {
|
||||
const parsed = await parseStringPromise(xmlContent, {
|
||||
explicitArray: false,
|
||||
ignoreAttrs: false,
|
||||
mergeAttrs: true,
|
||||
})
|
||||
|
||||
const codes = extractCodes(parsed)
|
||||
|
||||
return {
|
||||
codes,
|
||||
fileName,
|
||||
documentNumber: extractField(parsed, 'Документ', 'НомерДок'),
|
||||
documentDate: extractField(parsed, 'Документ', 'ДатаДок'),
|
||||
sellerName: extractField(parsed, 'Документ', 'ТаблСчФакт', 'СведПрод', 'НаимОрг'),
|
||||
buyerName: extractField(parsed, 'Документ', 'ТаблСчФакт', 'СведПокуп', 'НаимОрг'),
|
||||
}
|
||||
}
|
||||
|
||||
function extractCodes(obj: Record<string, unknown>): string[] {
|
||||
const codes: string[] = []
|
||||
|
||||
try {
|
||||
const document = obj['Документ'] as Record<string, unknown>
|
||||
const table = document['ТаблСчФакт'] as Record<string, unknown>
|
||||
const items = table['СведТов'] as Record<string, unknown>[]
|
||||
|
||||
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)) {
|
||||
codes.push(...kmCodes.filter(Boolean))
|
||||
} else if (typeof kmCodes === 'string') {
|
||||
codes.push(kmCodes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// XML structure may vary; return what we found
|
||||
}
|
||||
|
||||
return codes
|
||||
}
|
||||
|
||||
function extractField(obj: Record<string, unknown>, ...keys: string[]): string | undefined {
|
||||
let current: unknown = obj
|
||||
for (const key of keys) {
|
||||
if (current && typeof current === 'object') {
|
||||
current = (current as Record<string, unknown>)[key]
|
||||
} else {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
return typeof current === 'string' ? current : undefined
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
export interface AuthKeyResponse {
|
||||
uuid: string
|
||||
data: string
|
||||
}
|
||||
|
||||
export interface AuthSignInRequest {
|
||||
uuid: string
|
||||
data: string
|
||||
}
|
||||
|
||||
export interface AuthSignInResponse {
|
||||
token: string
|
||||
uuidToken?: string
|
||||
expireDate?: string
|
||||
}
|
||||
|
||||
export interface CisInfoRequest {
|
||||
cisList: string[]
|
||||
}
|
||||
|
||||
export interface CisInfoItem {
|
||||
requestedCis: string
|
||||
cis?: string
|
||||
gtin?: string
|
||||
status?: string
|
||||
productName?: string
|
||||
productGroup?: string
|
||||
producerName?: string
|
||||
ownerName?: string
|
||||
ownerBin?: string
|
||||
producedDate?: string
|
||||
packageType?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface CisInfoResponse {
|
||||
cisInfo: CisInfoItem[]
|
||||
}
|
||||
|
||||
export interface PublicCheckResponse {
|
||||
code: string
|
||||
found: boolean
|
||||
valid: boolean
|
||||
status: string
|
||||
}
|
||||
|
||||
export interface CheckCodesRequest {
|
||||
codes: string[]
|
||||
}
|
||||
|
||||
export interface SingleCodeResult {
|
||||
code: string
|
||||
found: boolean
|
||||
valid: boolean
|
||||
status: string
|
||||
gtin?: string
|
||||
productName?: string
|
||||
producerName?: string
|
||||
ownerName?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface CheckCodesResponse {
|
||||
results: SingleCodeResult[]
|
||||
total: number
|
||||
validCount: number
|
||||
invalidCount: number
|
||||
errorCount: number
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Reference in New Issue
Block a user