ok
This commit is contained in:
@@ -18,9 +18,9 @@ export const config = {
|
||||
corsOrigin: process.env.CORS_ORIGIN || '*',
|
||||
|
||||
trueApi: {
|
||||
authPath: '/auth',
|
||||
cisesInfoPath: '/cises/info',
|
||||
codesCheckPath: '/codes/check',
|
||||
authPath: 'auth',
|
||||
cisesInfoPath: 'cises/info',
|
||||
codesCheckPath: 'codes/check',
|
||||
batchSize: 1000,
|
||||
tokenTTL: 10 * 60 * 60 * 1000,
|
||||
maxRetries: 3,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { TrueApiEnv } from '../config.js'
|
||||
import { getAuthKey, signIn, clearToken, getAuthStatus } from '../services/auth-service.js'
|
||||
import { getAuthKey, signIn, clearToken, getAuthStatus, setTokenDirect } from '../services/auth-service.js'
|
||||
import { AppError, extractDebugInfo } from '../services/cises-service.js'
|
||||
|
||||
const VALID_ENVS = ['sandbox', 'prod']
|
||||
@@ -18,6 +18,7 @@ const signInSchema = {
|
||||
properties: {
|
||||
uuid: { type: 'string' },
|
||||
data: { type: 'string' },
|
||||
inn: { type: 'string' },
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -43,11 +44,12 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
}
|
||||
})
|
||||
|
||||
app.post<{ Body: { uuid: string; data: string } }>('/auth/simpleSignIn', { schema: signInSchema }, async (request, reply) => {
|
||||
app.post<{ Body: { uuid: string; data: string; inn?: string } }>('/auth/simpleSignIn', { schema: signInSchema }, async (request, reply) => {
|
||||
const env = parseEnv(request.query as Record<string, string>)
|
||||
try {
|
||||
const { uuid, data } = request.body
|
||||
const result = await signIn(env, { uuid, data })
|
||||
const { uuid, data, inn } = request.body
|
||||
const result = await signIn(env, { uuid, data, inn })
|
||||
request.log.info({ env, token: result.token }, 'auth: token received')
|
||||
return result
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) {
|
||||
@@ -74,4 +76,11 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
clearToken(env)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
app.post<{ Body: { token: string } }>('/auth/setToken', async (request) => {
|
||||
const env = parseEnv(request.query as Record<string, string>)
|
||||
setTokenDirect(env, request.body.token)
|
||||
request.log.info({ env, tokenPrefix: request.body.token.slice(0, 20) + '...' }, 'auth: token set manually')
|
||||
return { success: true }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function cisesRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.post<{ Body: CheckCodesRequest }>('/api/check-codes/auth', { schema: checkCodesSchema }, async (request, reply) => {
|
||||
const env = parseEnv(request.query as Record<string, string>)
|
||||
try {
|
||||
return await checkCodesAuth(env, request.body)
|
||||
return await checkCodesAuth(env, request.body, (msg, data) => request.log.error(data, msg))
|
||||
} catch (err) {
|
||||
if (err instanceof AppError) {
|
||||
return reply.status(err.statusCode).send({
|
||||
|
||||
@@ -1,17 +1,50 @@
|
||||
import got from 'got'
|
||||
import type { Response } from 'got'
|
||||
import { config, envUrls } from '../config.js'
|
||||
import type { TrueApiEnv } from '../config.js'
|
||||
import { getToken, setToken, invalidateToken, hasToken, getTokenTTL } from './token-cache.js'
|
||||
import { AppError, extractDebugInfo } from './cises-service.js'
|
||||
import type { AuthKeyResponse, AuthSignInRequest, AuthSignInResponse } from '../types/index.js'
|
||||
|
||||
function authClient(env: TrueApiEnv) {
|
||||
function loggedClient(prefixUrl: string) {
|
||||
return got.extend({
|
||||
prefixUrl: envUrls[env].baseUrl + config.trueApi.authPath,
|
||||
prefixUrl,
|
||||
responseType: 'json',
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(options) => {
|
||||
const headers = { ...options.headers } as Record<string, string>
|
||||
if (headers.authorization) {
|
||||
headers.authorization = 'Bearer ***'
|
||||
}
|
||||
console.log(JSON.stringify({
|
||||
type: 'trueapi_request',
|
||||
method: options.method,
|
||||
url: String(options.url || ''),
|
||||
headers,
|
||||
body: options.json || options.body || null,
|
||||
}))
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
(response: Response) => {
|
||||
console.log(JSON.stringify({
|
||||
type: 'trueapi_response',
|
||||
statusCode: response.statusCode,
|
||||
url: response.requestUrl,
|
||||
body: response.body,
|
||||
}))
|
||||
return response
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function authClient(env: TrueApiEnv) {
|
||||
return loggedClient(envUrls[env].baseUrl + config.trueApi.authPath)
|
||||
}
|
||||
|
||||
export async function getAuthKey(env: TrueApiEnv): Promise<AuthKeyResponse> {
|
||||
try {
|
||||
const { body } = await authClient(env).get<AuthKeyResponse>('key')
|
||||
@@ -25,8 +58,12 @@ export async function getAuthKey(env: TrueApiEnv): Promise<AuthKeyResponse> {
|
||||
|
||||
export async function signIn(env: TrueApiEnv, body: AuthSignInRequest): Promise<AuthSignInResponse> {
|
||||
try {
|
||||
const requestBody: Record<string, unknown> = { uuid: body.uuid, data: body.data }
|
||||
if (body.inn) {
|
||||
requestBody.inn = body.inn
|
||||
}
|
||||
const { body: response } = await authClient(env).post<AuthSignInResponse>('simpleSignIn', {
|
||||
json: body,
|
||||
json: requestBody,
|
||||
})
|
||||
setToken(env, response.token)
|
||||
return response
|
||||
@@ -41,6 +78,10 @@ export function getCachedToken(env: TrueApiEnv): string | undefined {
|
||||
return getToken(env)
|
||||
}
|
||||
|
||||
export function setTokenDirect(env: TrueApiEnv, token: string): void {
|
||||
setToken(env, token)
|
||||
}
|
||||
|
||||
export function clearToken(env: TrueApiEnv): void {
|
||||
invalidateToken(env)
|
||||
}
|
||||
|
||||
@@ -1,22 +1,56 @@
|
||||
import got from 'got'
|
||||
import type { Response } from 'got'
|
||||
import { config, envUrls } from '../config.js'
|
||||
import type { TrueApiEnv } from '../config.js'
|
||||
import { getCachedToken, clearToken } from './auth-service.js'
|
||||
import type {
|
||||
CisInfoResponse,
|
||||
CisInfoResponseItem,
|
||||
PublicCheckResponse,
|
||||
CheckCodesRequest,
|
||||
CheckCodesResponse,
|
||||
SingleCodeResult,
|
||||
ApiDebugInfo,
|
||||
} from '../types/index.js'
|
||||
|
||||
function apiClient(env: TrueApiEnv) {
|
||||
function loggedClient(prefixUrl: string) {
|
||||
return got.extend({
|
||||
prefixUrl: envUrls[env].baseUrl,
|
||||
prefixUrl,
|
||||
responseType: 'json',
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
(options) => {
|
||||
const headers = { ...options.headers } as Record<string, string>
|
||||
if (headers.authorization) {
|
||||
headers.authorization = 'Bearer ***'
|
||||
}
|
||||
console.log(JSON.stringify({
|
||||
type: 'trueapi_request',
|
||||
method: options.method,
|
||||
url: String(options.url || ''),
|
||||
headers,
|
||||
body: options.json || options.body || null,
|
||||
}))
|
||||
},
|
||||
],
|
||||
afterResponse: [
|
||||
(response: Response) => {
|
||||
console.log(JSON.stringify({
|
||||
type: 'trueapi_response',
|
||||
statusCode: response.statusCode,
|
||||
url: response.requestUrl,
|
||||
body: response.body,
|
||||
}))
|
||||
return response
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function apiClient(env: TrueApiEnv) {
|
||||
return loggedClient(envUrls[env].baseUrl)
|
||||
}
|
||||
|
||||
export async function checkCodesPublic(env: TrueApiEnv, body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||
const results: SingleCodeResult[] = []
|
||||
const queue = [...body.codes]
|
||||
@@ -25,9 +59,9 @@ export async function checkCodesPublic(env: TrueApiEnv, body: CheckCodesRequest)
|
||||
while (queue.length > 0) {
|
||||
const code = queue.shift()!
|
||||
try {
|
||||
const { body: response } = await got.get<PublicCheckResponse>(
|
||||
`${envUrls[env].publicCheckUrl}?code=${encodeURIComponent(code)}`,
|
||||
{ responseType: 'json', timeout: { request: 10000 } }
|
||||
const { body: response } = await loggedClient(envUrls[env].publicCheckUrl).get<PublicCheckResponse>(
|
||||
`?code=${encodeURIComponent(code)}`,
|
||||
{ timeout: { request: 10000 } }
|
||||
)
|
||||
results.push({
|
||||
code: response.code,
|
||||
@@ -59,9 +93,14 @@ function getToken(env: TrueApiEnv): string {
|
||||
return token
|
||||
}
|
||||
|
||||
export async function checkCodesAuth(env: TrueApiEnv, body: CheckCodesRequest): Promise<CheckCodesResponse> {
|
||||
export async function checkCodesAuth(
|
||||
env: TrueApiEnv,
|
||||
body: CheckCodesRequest,
|
||||
log?: (msg: string, data?: Record<string, unknown>) => void,
|
||||
): Promise<CheckCodesResponse> {
|
||||
const token = getToken(env)
|
||||
const results: SingleCodeResult[] = []
|
||||
let debugInfo: ApiDebugInfo | undefined
|
||||
|
||||
try {
|
||||
await processBatch(env, body.codes, token, results, 0)
|
||||
@@ -70,6 +109,14 @@ export async function checkCodesAuth(env: TrueApiEnv, body: CheckCodesRequest):
|
||||
clearToken(env)
|
||||
throw err
|
||||
}
|
||||
if (err instanceof AppError) {
|
||||
debugInfo = err.debugInfo
|
||||
if (log) log('Auth API error (non-401)', { error: err.message, debugInfo })
|
||||
} else {
|
||||
debugInfo = extractDebugInfo(err)
|
||||
if (log) log('Auth API error (non-401)', { error: String(err), debugInfo })
|
||||
}
|
||||
|
||||
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' })
|
||||
@@ -77,20 +124,46 @@ export async function checkCodesAuth(env: TrueApiEnv, body: CheckCodesRequest):
|
||||
}
|
||||
}
|
||||
|
||||
return buildResponse(results)
|
||||
return buildResponse(results, debugInfo)
|
||||
}
|
||||
|
||||
export interface ApiDebugInfo {
|
||||
request: {
|
||||
method: string
|
||||
url: string
|
||||
headers: Record<string, string>
|
||||
body: unknown
|
||||
function buildResponse(results: SingleCodeResult[], debugInfo?: ApiDebugInfo): 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,
|
||||
debugInfo,
|
||||
}
|
||||
response: {
|
||||
statusCode: number
|
||||
headers: Record<string, string>
|
||||
body: unknown
|
||||
}
|
||||
|
||||
function extractRequestHeaders(options: Record<string, unknown> | undefined): Record<string, string> {
|
||||
const reqHeaders = options?.headers as Record<string, string> | undefined
|
||||
const clean: Record<string, string> = {}
|
||||
if (reqHeaders) {
|
||||
for (const [k, v] of Object.entries(reqHeaders)) {
|
||||
clean[k] = k.toLowerCase() === 'authorization' ? 'Bearer ***' : String(v)
|
||||
}
|
||||
}
|
||||
return clean
|
||||
}
|
||||
|
||||
export function extractDebugInfoFromResponse<T>(response: Response<T>): ApiDebugInfo {
|
||||
const req = response.request as unknown as Record<string, unknown> | undefined
|
||||
const opts = req?.options as Record<string, unknown> | undefined
|
||||
return {
|
||||
request: {
|
||||
method: String(opts?.method || 'POST'),
|
||||
url: String(response.requestUrl || response.url || 'unknown'),
|
||||
headers: extractRequestHeaders(opts),
|
||||
body: (opts?.json || opts?.body) ?? null,
|
||||
},
|
||||
response: {
|
||||
statusCode: response.statusCode,
|
||||
headers: (response.headers || {}) as Record<string, string>,
|
||||
body: response.body ?? null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,33 +172,37 @@ export function extractDebugInfo(err: unknown): ApiDebugInfo | undefined {
|
||||
const gotErr = err as Record<string, unknown>
|
||||
const response = gotErr.response as Record<string, unknown> | undefined
|
||||
const options = gotErr.options as Record<string, unknown> | undefined
|
||||
if (!response) return undefined
|
||||
|
||||
const reqHeaders = options?.headers as Record<string, string> | undefined
|
||||
const cleanHeaders: Record<string, string> = {}
|
||||
if (reqHeaders) {
|
||||
for (const [k, v] of Object.entries(reqHeaders)) {
|
||||
if (k.toLowerCase() === 'authorization') {
|
||||
cleanHeaders[k] = 'Bearer ***'
|
||||
} else {
|
||||
cleanHeaders[k] = String(v)
|
||||
}
|
||||
}
|
||||
const code = gotErr.code ? String(gotErr.code) : undefined
|
||||
const message = gotErr.message ? String(gotErr.message) : undefined
|
||||
|
||||
const cleanHeaders = extractRequestHeaders(options)
|
||||
|
||||
let reqUrl = 'unknown'
|
||||
if (response?.requestUrl) {
|
||||
reqUrl = String(response.requestUrl)
|
||||
} else if (options) {
|
||||
const u = (options as Record<string, unknown>).url
|
||||
if (u) reqUrl = String(u)
|
||||
else if ((options as Record<string, unknown>).href) reqUrl = String((options as Record<string, unknown>).href)
|
||||
else if ((options as Record<string, unknown>).pathname) reqUrl = String((options as Record<string, unknown>).pathname)
|
||||
}
|
||||
|
||||
const resHeaders = response.headers as Record<string, string> | undefined
|
||||
const resHeaders = response?.headers as Record<string, string> | undefined
|
||||
|
||||
return {
|
||||
request: {
|
||||
method: String(options?.method || 'POST'),
|
||||
url: String(response.requestUrl || (options?.url?.toString()) || 'unknown'),
|
||||
url: reqUrl,
|
||||
headers: cleanHeaders,
|
||||
body: options?.json || options?.body || null,
|
||||
},
|
||||
response: {
|
||||
statusCode: Number(response.statusCode),
|
||||
statusCode: Number(response?.statusCode || 0),
|
||||
headers: resHeaders || {},
|
||||
body: response.body || null,
|
||||
body: response?.body || null,
|
||||
errorCode: code,
|
||||
errorMessage: message,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -147,56 +224,49 @@ async function processBatch(
|
||||
async function retryOnError(
|
||||
env: TrueApiEnv, batch: string[], token: string, results: SingleCodeResult[], attempt = 0
|
||||
): Promise<void> {
|
||||
try {
|
||||
const { body: response } = await apiClient(env).post<CisInfoResponse>(
|
||||
config.trueApi.cisesInfoPath,
|
||||
{
|
||||
json: { cisList: batch },
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: { request: 30000 },
|
||||
}
|
||||
)
|
||||
|
||||
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 (err) {
|
||||
if (is401(err)) {
|
||||
const debugInfo = extractDebugInfo(err)
|
||||
throw new AppError('Token expired', 401, debugInfo)
|
||||
const response = await apiClient(env).post<CisInfoResponseItem[]>(
|
||||
config.trueApi.cisesInfoPath,
|
||||
{
|
||||
json: batch,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
timeout: { request: 30000 },
|
||||
throwHttpErrors: false,
|
||||
}
|
||||
)
|
||||
|
||||
const isRetryable = isRetryableError(err)
|
||||
if (isRetryable && attempt < config.trueApi.maxRetries) {
|
||||
const delay = Math.pow(2, attempt) * 500
|
||||
await sleep(delay)
|
||||
return retryOnError(env, batch, token, results, attempt + 1)
|
||||
}
|
||||
|
||||
throw err
|
||||
if (response.statusCode === 401) {
|
||||
const debugInfo = extractDebugInfoFromResponse(response)
|
||||
throw new AppError('Token expired', 401, debugInfo)
|
||||
}
|
||||
}
|
||||
|
||||
function is401(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') return false
|
||||
return 'response' in err &&
|
||||
(err as { response?: { statusCode?: number } }).response?.statusCode === 401
|
||||
}
|
||||
if (response.statusCode === 429 || (response.statusCode >= 500 && attempt < config.trueApi.maxRetries)) {
|
||||
const delay = Math.pow(2, attempt) * 500
|
||||
await sleep(delay)
|
||||
return retryOnError(env, batch, token, results, attempt + 1)
|
||||
}
|
||||
|
||||
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
|
||||
if (!response.body || !Array.isArray(response.body)) {
|
||||
const debugInfo = extractDebugInfoFromResponse(response)
|
||||
const apiErr = response.body && typeof response.body === 'object'
|
||||
? (response.body as Record<string, unknown>).error_message || ''
|
||||
: ''
|
||||
throw new AppError(`API error: ${apiErr || response.statusCode}`, response.statusCode, debugInfo)
|
||||
}
|
||||
|
||||
const items = response.body as CisInfoResponseItem[]
|
||||
for (const item of items) {
|
||||
const ci = item.cisInfo
|
||||
results.push({
|
||||
code: ci.requestedCis,
|
||||
found: !!ci.cis && !item.errorCode,
|
||||
valid: ci.status === 'INTRODUCED' || ci.status === 'APPLIED' || ci.status === 'EMITTED',
|
||||
status: item.errorCode || ci.status || 'UNKNOWN',
|
||||
gtin: ci.gtin,
|
||||
productName: ci.productName,
|
||||
producerName: ci.producerName,
|
||||
ownerName: ci.ownerName,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
@@ -213,12 +283,4 @@ export class AppError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface AuthKeyResponse {
|
||||
export interface AuthSignInRequest {
|
||||
uuid: string
|
||||
data: string
|
||||
inn?: string
|
||||
}
|
||||
|
||||
export interface AuthSignInResponse {
|
||||
@@ -14,10 +15,6 @@ export interface AuthSignInResponse {
|
||||
expireDate?: string
|
||||
}
|
||||
|
||||
export interface CisInfoRequest {
|
||||
cisList: string[]
|
||||
}
|
||||
|
||||
export interface CisInfoItem {
|
||||
requestedCis: string
|
||||
cis?: string
|
||||
@@ -33,8 +30,10 @@ export interface CisInfoItem {
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface CisInfoResponse {
|
||||
cisInfo: CisInfoItem[]
|
||||
export interface CisInfoResponseItem {
|
||||
cisInfo: CisInfoItem
|
||||
errorMessage?: string | null
|
||||
errorCode?: string | null
|
||||
}
|
||||
|
||||
export interface PublicCheckResponse {
|
||||
@@ -48,6 +47,22 @@ export interface CheckCodesRequest {
|
||||
codes: string[]
|
||||
}
|
||||
|
||||
export interface ApiDebugInfo {
|
||||
request: {
|
||||
method: string
|
||||
url: string
|
||||
headers: Record<string, string>
|
||||
body: unknown
|
||||
}
|
||||
response: {
|
||||
statusCode: number
|
||||
headers: Record<string, string>
|
||||
body: unknown
|
||||
errorCode?: string
|
||||
errorMessage?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface SingleCodeResult {
|
||||
code: string
|
||||
found: boolean
|
||||
@@ -66,4 +81,5 @@ export interface CheckCodesResponse {
|
||||
validCount: number
|
||||
invalidCount: number
|
||||
errorCount: number
|
||||
debugInfo?: ApiDebugInfo
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { getAuthStatus, getAuthKey, signIn } from '../services/api'
|
||||
import { getAuthStatus, getAuthKey, signIn, setTokenManually } from '../services/api'
|
||||
import type { RequestError } from '../services/api'
|
||||
import { isCadesPluginAvailable, listCertificates, signWithCadesPlugin } from '../services/cadesplugin'
|
||||
import type { CertInfo } from '../services/cadesplugin'
|
||||
@@ -13,10 +13,13 @@ export function AuthPage({ onAuth }: Props) {
|
||||
const [hasPlugin, setHasPlugin] = useState<boolean | null>(null)
|
||||
const [certs, setCerts] = useState<CertInfo[]>([])
|
||||
const [selectedThumbprint, setSelectedThumbprint] = useState('')
|
||||
const [inn, setInn] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [errorDebug, setErrorDebug] = useState<string | null>(null)
|
||||
const [debugExpanded, setDebugExpanded] = useState(false)
|
||||
const [manualToken, setManualToken] = useState('')
|
||||
const [manualLoading, setManualLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
getAuthStatus().then(setStatus).catch(() => {})
|
||||
@@ -34,6 +37,27 @@ export function AuthPage({ onAuth }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSetToken() {
|
||||
setManualLoading(true)
|
||||
setError('')
|
||||
setErrorDebug(null)
|
||||
setDebugExpanded(false)
|
||||
try {
|
||||
await setTokenManually(manualToken)
|
||||
const s = await getAuthStatus()
|
||||
setStatus(s)
|
||||
if (s.authenticated) onAuth()
|
||||
} catch (err) {
|
||||
const re = err as RequestError
|
||||
setError(re.message)
|
||||
if (re.debugInfo) {
|
||||
setErrorDebug(JSON.stringify(re.debugInfo, null, 2))
|
||||
}
|
||||
} finally {
|
||||
setManualLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSignIn() {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
@@ -42,7 +66,7 @@ export function AuthPage({ onAuth }: Props) {
|
||||
try {
|
||||
const { uuid, data } = await getAuthKey()
|
||||
const signature = await signWithCadesPlugin(data, selectedThumbprint || undefined)
|
||||
await signIn(uuid, signature)
|
||||
await signIn(uuid, signature, inn || undefined)
|
||||
const s = await getAuthStatus()
|
||||
setStatus(s)
|
||||
if (s.authenticated) onAuth()
|
||||
@@ -92,6 +116,19 @@ export function AuthPage({ onAuth }: Props) {
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxWidth: 500 }}>
|
||||
<div>
|
||||
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||
ИНН организации:
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={inn}
|
||||
onChange={e => setInn(e.target.value)}
|
||||
placeholder="Введите ИНН для однозначной авторизации"
|
||||
style={inputStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasPlugin && certs.length > 0 && (
|
||||
<div>
|
||||
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||
@@ -126,6 +163,39 @@ export function AuthPage({ onAuth }: Props) {
|
||||
{loading ? 'Подписание...' : 'Подписать и войти'}
|
||||
</button>
|
||||
|
||||
<div style={{
|
||||
borderTop: '1px solid #e0e0e0',
|
||||
margin: '12px 0',
|
||||
paddingTop: 16,
|
||||
}}>
|
||||
<label style={{ fontSize: 13, color: '#666', display: 'block', marginBottom: 4 }}>
|
||||
Или введите готовый токен:
|
||||
</label>
|
||||
<textarea
|
||||
value={manualToken}
|
||||
onChange={e => setManualToken(e.target.value)}
|
||||
placeholder="Вставьте токен доступа к True API"
|
||||
rows={3}
|
||||
style={{
|
||||
...inputStyle,
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 12,
|
||||
resize: 'vertical',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
onClick={handleSetToken}
|
||||
disabled={manualLoading || !manualToken.trim()}
|
||||
style={{
|
||||
...btnStyle,
|
||||
background: '#1565c0',
|
||||
marginTop: 8,
|
||||
}}
|
||||
>
|
||||
{manualLoading ? 'Сохранение...' : 'Сохранить токен'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div style={{ color: '#c62828', fontSize: 14, marginTop: 8 }}>Ошибка: {error}</div>
|
||||
)}
|
||||
@@ -197,3 +267,12 @@ const selectStyle: React.CSSProperties = {
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
}
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
padding: 8,
|
||||
border: '1px solid #ccc',
|
||||
borderRadius: 4,
|
||||
fontSize: 13,
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from 'react'
|
||||
import { checkCodesPublic, checkCodesAuth } from '../services/api'
|
||||
import type { RequestError } from '../services/api'
|
||||
import { ResultsTable } from '../components/ResultsTable'
|
||||
import type { CodeResult } from '../types'
|
||||
import type { CodeResult, CheckCodesResponse } from '../types'
|
||||
|
||||
export function CheckCodesPage() {
|
||||
const [codesInput, setCodesInput] = useState('')
|
||||
@@ -14,7 +14,7 @@ export function CheckCodesPage() {
|
||||
|
||||
async function handleCheck(mode: 'public' | 'auth') {
|
||||
const codes = codesInput
|
||||
.split(/[\n,;]+/)
|
||||
.split('\n')
|
||||
.map(c => c.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
@@ -29,8 +29,11 @@ export function CheckCodesPage() {
|
||||
setDebugExpanded(false)
|
||||
try {
|
||||
const fn = mode === 'public' ? checkCodesPublic : checkCodesAuth
|
||||
const response = await fn(codes)
|
||||
const response: CheckCodesResponse = await fn(codes)
|
||||
setResults(response.results)
|
||||
if (response.debugInfo) {
|
||||
setErrorDebug(JSON.stringify(response.debugInfo, null, 2))
|
||||
}
|
||||
} catch (err) {
|
||||
const re = err as RequestError
|
||||
setError(re.message)
|
||||
@@ -47,7 +50,7 @@ export function CheckCodesPage() {
|
||||
<h2>Проверка кодов маркировки (КМ)</h2>
|
||||
|
||||
<textarea
|
||||
placeholder="Введите коды маркировки (каждый с новой строки, через запятую или точку с запятой)"
|
||||
placeholder="Введите коды маркировки (каждый с новой строки)"
|
||||
value={codesInput}
|
||||
onChange={e => setCodesInput(e.target.value)}
|
||||
rows={6}
|
||||
|
||||
@@ -38,7 +38,7 @@ async function handleError(res: Response, env: ApiEnv): Promise<never> {
|
||||
async function request<T>(url: string, options?: RequestInit & { env?: ApiEnv }): Promise<T> {
|
||||
const reqEnv = options?.env || currentEnv
|
||||
const headers: Record<string, string> = {}
|
||||
if (!(options?.body instanceof FormData)) {
|
||||
if (!(options?.body instanceof FormData) && options?.body) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
if (options?.headers) {
|
||||
@@ -59,10 +59,10 @@ export async function getAuthKey(env?: ApiEnv): Promise<{ uuid: string; data: st
|
||||
return request('/auth/key', { env })
|
||||
}
|
||||
|
||||
export async function signIn(uuid: string, data: string, env?: ApiEnv): Promise<{ token: string }> {
|
||||
export async function signIn(uuid: string, data: string, inn?: string, env?: ApiEnv): Promise<{ token: string }> {
|
||||
return request('/auth/simpleSignIn', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ uuid, data }),
|
||||
body: JSON.stringify({ uuid, data, inn }),
|
||||
env,
|
||||
})
|
||||
}
|
||||
@@ -97,6 +97,14 @@ export async function uploadUpd(file: File, env?: ApiEnv): Promise<UpdUploadResp
|
||||
return request('/api/upload-upd', { method: 'POST', body: formData, env })
|
||||
}
|
||||
|
||||
export async function setTokenManually(token: string, env?: ApiEnv): Promise<void> {
|
||||
await request('/auth/setToken', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ token }),
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
export async function getPlansList(): Promise<{ name: string; path: string; size: number }[]> {
|
||||
return request('/api/plans')
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface CheckCodesResponse {
|
||||
validCount: number
|
||||
invalidCount: number
|
||||
errorCount: number
|
||||
debugInfo?: ApiDebugInfo
|
||||
}
|
||||
|
||||
export interface UpdDocument {
|
||||
@@ -33,7 +34,7 @@ export interface UpdDocument {
|
||||
fileName: string
|
||||
}
|
||||
|
||||
export interface ApiErrorLog {
|
||||
export interface ApiDebugInfo {
|
||||
request: {
|
||||
method: string
|
||||
url: string
|
||||
@@ -44,12 +45,14 @@ export interface ApiErrorLog {
|
||||
statusCode: number
|
||||
headers: Record<string, string>
|
||||
body: unknown
|
||||
errorCode?: string
|
||||
errorMessage?: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
error: string
|
||||
debugInfo?: ApiErrorLog
|
||||
debugInfo?: ApiDebugInfo
|
||||
}
|
||||
|
||||
export interface UpdUploadResponse {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Соответствие ID складов Wildberries
|
||||
|
||||
## Официальные API (требуется API-ключ продавца)
|
||||
|
||||
### Suppliers API
|
||||
```
|
||||
GET https://suppliers-api.wildberries.ru/api/v3/warehouses
|
||||
Header: Authorization: <API-ключ>
|
||||
```
|
||||
Возвращает полный список складов с ID и названиями.
|
||||
|
||||
### Statistics API
|
||||
```
|
||||
GET https://statistics-api.wildberries.ru/api/v1/warehouses
|
||||
Header: Authorization: <API-ключ>
|
||||
```
|
||||
|
||||
## Публичные веб-ресурсы
|
||||
|
||||
### Карта складов wbarcode.ru
|
||||
- **Список всех складов (названия):** https://wbarcode.ru/warehouses
|
||||
- **Страницы отдельных складов:** `/warehouses/<slug>` (например, `/warehouses/koledino`, `/warehouses/novosibirsk`, `/warehouses/domodedovo`)
|
||||
- Содержит адреса, координаты, информацию о режиме работы (но ID складов на страницах не отображаются, только названия)
|
||||
|
||||
### Статья с перечнем складов (litestat.io)
|
||||
- https://litestat.io/blog/sklady-wildberries-adresa-zony-pokrytiya-koordinaty/
|
||||
- Адреса и описания основных складов, но без ID
|
||||
|
||||
### Карта складов WB prod
|
||||
- https://wbprod.ru/zony-pokritiya-skladov-wb/Novosibirsk/
|
||||
|
||||
### Wildberries Edu
|
||||
- https://wildberries-edu.ru/sklady-wildberries/
|
||||
|
||||
## Community-ресурсы (GitHub)
|
||||
|
||||
Репозитории, в которых могут быть JSON-файлы с маппингом:
|
||||
- https://github.com/eslazarev/wildberries-sdk — OpenAPI-спецификации WB API
|
||||
- https://github.com/ilyautov/marketplaces-mcp-ru — MCP-сервер для WB, маппинги внутри
|
||||
- https://github.com/salacoste/daytona-wildberries-typescript-sdk — TypeScript SDK
|
||||
|
||||
Поискать по GitHub: `wb warehouses`, `wb-warehouses`, `wildberries warehouses list`, `warehouses.json`
|
||||
|
||||
## Кабинет продавца
|
||||
https://seller.wildberries.ru — при создании поставки или в разделе «Склады» видны ID.
|
||||
|
||||
## Известные ID складов (справочно)
|
||||
|
||||
| ID | Название | Регион |
|
||||
|---------|------------------------------|-----------------------|
|
||||
| 120602 | Коледино | Московская область |
|
||||
| 686 | Новосибирск | Новосибирская область |
|
||||
| 116433 | Домодедово (Белые Столбы) | Московская область |
|
||||
| 117986 | Казань | Татарстан |
|
||||
| 118535 | Екатеринбург (Кольцово) | Свердловская область |
|
||||
| 121709 | Санкт-Петербург (Шушары) | Ленинградская область |
|
||||
| 121710 | Подольск | Московская область |
|
||||
| 98591 | Краснодар | Краснодарский край |
|
||||
| 207743 | Хабаровск | Хабаровский край |
|
||||
| 98774 | Горячий Ключ | Краснодарский край |
|
||||
| 119698 | Ростов-на-Дону | Ростовская область |
|
||||
|
||||
## Пути к статическим файлам WB (могут не работать)
|
||||
```
|
||||
https://catalog.wb.ru/catalog/warehouse/v1/warehouses
|
||||
https://static-basket-01.wb.ru/vol0/data/warehouses.json
|
||||
https://static-basket-01.wbbasket.ru/vol0/data/warehouses.json
|
||||
```
|
||||
Большинство эндпоинтов WB защищены антибот-системой (498 ошибка).
|
||||
Reference in New Issue
Block a user