import crypto from 'crypto'; import { pool } from '../db'; import { hashPassword, verifyPasswordHash } from '../utils/password'; export const SUPPLIER_INTEGRATION_SCOPE = 'supplier_integration' as const; export const INTEGRATION_TOKEN_TTL_SEC = 60 * 60 * 24; // 24h export interface IntegrationClientRow { id: string; client_id: string; client_secret_hash: string; secret_version: number; name: string; status: number; } export interface IntegrationSupplierBinding { client_id: string; branch_code: string; supplier_code: string; } function newClientId() { return `erp_${crypto.randomBytes(8).toString('hex')}`; } function newClientSecret() { return crypto.randomBytes(32).toString('base64url'); } export async function createIntegrationClient(input: { name: string }) { const name = String(input.name || '').trim(); if (!name) { throw Object.assign(new Error('请填写客户端名称'), { status: 400, code: 'invalid_request' }); } const clientId = newClientId(); const clientSecret = newClientSecret(); const secretHash = await hashPassword(clientSecret); const result = await pool.query( `INSERT INTO public.supplier_integration_clients (client_id, client_secret_hash, secret_version, name, status) VALUES ($1, $2, 1, $3, 1) RETURNING id, client_id, secret_version, name, status, created_at`, [clientId, secretHash, name] ); const row = result.rows[0]; return { id: String(row.id), client_id: String(row.client_id), client_secret: clientSecret, secret_version: Number(row.secret_version) || 1, name: String(row.name), status: Number(row.status) || 1, created_at: row.created_at, }; } export async function listIntegrationClients() { const result = await pool.query( `SELECT c.id, c.client_id, c.secret_version, c.name, c.status, c.created_at, c.updated_at, c.webhook_url, (NULLIF(TRIM(c.webhook_secret), '') IS NOT NULL) AS has_webhook_secret, COALESCE( (SELECT json_agg(json_build_object( 'branch_code', s.branch_code, 'supplier_code', s.supplier_code ) ORDER BY s.branch_code, s.supplier_code) FROM public.supplier_integration_client_suppliers s WHERE s.client_id = c.client_id), '[]'::json ) AS suppliers FROM public.supplier_integration_clients c ORDER BY c.created_at DESC` ); return result.rows.map((row) => ({ id: String(row.id), client_id: String(row.client_id), secret_version: Number(row.secret_version) || 1, name: String(row.name), status: Number(row.status) || 0, webhook_url: row.webhook_url ? String(row.webhook_url) : null, has_webhook_secret: Boolean(row.has_webhook_secret), created_at: row.created_at, updated_at: row.updated_at, suppliers: Array.isArray(row.suppliers) ? row.suppliers : [], })); } function newWebhookSecret() { return crypto.randomBytes(32).toString('base64url'); } /** * 配置分配回调。webhook_url 传空字符串可清空。 * rotate_secret=true 或首次配置 URL 且尚无 secret 时生成新 secret(明文仅本次返回)。 */ export async function setIntegrationClientWebhook(input: { clientId: string; webhookUrl?: string | null; rotateSecret?: boolean; clearUrl?: boolean; }) { const clientId = String(input.clientId || '').trim(); if (!clientId) { throw Object.assign(new Error('缺少 client_id'), { status: 400, code: 'invalid_request' }); } const existing = await pool.query( `SELECT client_id, webhook_url, webhook_secret FROM public.supplier_integration_clients WHERE client_id = $1 LIMIT 1`, [clientId] ); if (!existing.rows[0]) { throw Object.assign(new Error('客户端不存在'), { status: 404, code: 'not_found' }); } let webhookUrl: string | null = input.webhookUrl === undefined ? existing.rows[0].webhook_url ? String(existing.rows[0].webhook_url) : null : String(input.webhookUrl || '').trim() || null; if (input.clearUrl) webhookUrl = null; if (webhookUrl) { try { const u = new URL(webhookUrl); if (u.protocol !== 'https:' && u.protocol !== 'http:') { throw new Error('invalid protocol'); } } catch { throw Object.assign(new Error('webhook_url 须为 http(s) URL'), { status: 400, code: 'invalid_request', }); } } const hadSecret = Boolean(String(existing.rows[0].webhook_secret || '').trim()); const needNewSecret = Boolean(input.rotateSecret) || (Boolean(webhookUrl) && !hadSecret); const webhookSecret = needNewSecret ? newWebhookSecret() : undefined; const result = await pool.query( `UPDATE public.supplier_integration_clients SET webhook_url = $2, webhook_secret = COALESCE($3, webhook_secret), updated_at = NOW() WHERE client_id = $1 RETURNING client_id, webhook_url, (NULLIF(TRIM(webhook_secret), '') IS NOT NULL) AS has_webhook_secret`, [clientId, webhookUrl, webhookSecret ?? null] ); const row = result.rows[0]; return { client_id: String(row.client_id), webhook_url: row.webhook_url ? String(row.webhook_url) : null, has_webhook_secret: Boolean(row.has_webhook_secret), ...(webhookSecret ? { webhook_secret: webhookSecret } : {}), }; } export async function setIntegrationClientStatus(clientId: string, status: 0 | 1) { const result = await pool.query( `UPDATE public.supplier_integration_clients SET status = $2, updated_at = NOW() WHERE client_id = $1 RETURNING client_id, status`, [clientId, status] ); if (!result.rows[0]) { throw Object.assign(new Error('客户端不存在'), { status: 404, code: 'not_found' }); } return { client_id: String(result.rows[0].client_id), status: Number(result.rows[0].status) }; } export async function rotateIntegrationClientSecret(clientId: string) { const clientSecret = newClientSecret(); const secretHash = await hashPassword(clientSecret); const result = await pool.query( `UPDATE public.supplier_integration_clients SET client_secret_hash = $2, secret_version = COALESCE(secret_version, 1) + 1, updated_at = NOW() WHERE client_id = $1 AND status = 1 RETURNING client_id, secret_version, name`, [clientId, secretHash] ); if (!result.rows[0]) { throw Object.assign(new Error('客户端不存在或已停用'), { status: 404, code: 'not_found' }); } return { client_id: String(result.rows[0].client_id), client_secret: clientSecret, secret_version: Number(result.rows[0].secret_version) || 1, name: String(result.rows[0].name), }; } export async function bindIntegrationSupplier(input: { clientId: string; branchCode: string; supplierCode: string; }) { const clientId = String(input.clientId || '').trim(); const branchCode = String(input.branchCode || '').trim(); const supplierCode = String(input.supplierCode || '').trim(); if (!clientId || !branchCode || !supplierCode) { throw Object.assign(new Error('缺少 client_id / branch_code / supplier_code'), { status: 400, code: 'invalid_request', }); } const client = await pool.query( `SELECT client_id FROM public.supplier_integration_clients WHERE client_id = $1 AND status = 1`, [clientId] ); if (!client.rows[0]) { throw Object.assign(new Error('客户端不存在或已停用'), { status: 404, code: 'not_found' }); } await pool.query( `INSERT INTO public.supplier_integration_client_suppliers (client_id, branch_code, supplier_code) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [clientId, branchCode, supplierCode] ); return { client_id: clientId, branch_code: branchCode, supplier_code: supplierCode }; } export async function unbindIntegrationSupplier(input: { clientId: string; branchCode: string; supplierCode: string; }) { const result = await pool.query( `DELETE FROM public.supplier_integration_client_suppliers WHERE client_id = $1 AND branch_code = $2 AND supplier_code = $3 RETURNING client_id`, [input.clientId, input.branchCode, input.supplierCode] ); if (!result.rows[0]) { throw Object.assign(new Error('绑定不存在'), { status: 404, code: 'not_found' }); } return { ok: true }; } export async function loadActiveIntegrationClient(clientId: string): Promise { const result = await pool.query( `SELECT id, client_id, client_secret_hash, secret_version, name, status FROM public.supplier_integration_clients WHERE client_id = $1 LIMIT 1`, [clientId] ); const row = result.rows[0]; if (!row) return null; return { id: String(row.id), client_id: String(row.client_id), client_secret_hash: String(row.client_secret_hash), secret_version: Number(row.secret_version) || 1, name: String(row.name), status: Number(row.status) || 0, }; } export async function findAuthorizedSupplierBinding( clientId: string, supplierCode: string ): Promise { const result = await pool.query( `SELECT client_id, branch_code, supplier_code FROM public.supplier_integration_client_suppliers WHERE client_id = $1 AND supplier_code = $2 ORDER BY branch_code ASC LIMIT 1`, [clientId, supplierCode] ); const row = result.rows[0]; if (!row) return null; return { client_id: String(row.client_id), branch_code: String(row.branch_code), supplier_code: String(row.supplier_code), }; } /** 校验 client 凭证并返回绑定(换 Token 用) */ export async function authenticateIntegrationClient(input: { clientId: string; clientSecret: string; supplierCode: string; }) { const clientId = String(input.clientId || '').trim(); const clientSecret = String(input.clientSecret || '').trim(); const supplierCode = String(input.supplierCode || '').trim(); if (!clientId || !clientSecret || !supplierCode) { throw Object.assign(new Error('请填写 client_id、client_secret、supplier_code'), { status: 400, code: 'invalid_request', }); } const client = await loadActiveIntegrationClient(clientId); if (!client || client.status !== 1) { throw Object.assign(new Error('客户端无效或已停用'), { status: 401, code: 'invalid_client' }); } const ok = await verifyPasswordHash(clientSecret, client.client_secret_hash); if (!ok) { throw Object.assign(new Error('client_secret 错误'), { status: 401, code: 'invalid_client' }); } const binding = await findAuthorizedSupplierBinding(clientId, supplierCode); if (!binding) { throw Object.assign(new Error('未授权访问该供应商'), { status: 403, code: 'forbidden' }); } return { client, binding }; } /** 校验集成 JWT 的 clientId + secretVer 是否仍有效 */ export async function validateIntegrationTokenClaims(input: { clientId?: string; secretVer?: number; supplierCode?: string; branchCode?: string; }): Promise<{ clientId: string; supplierCode: string; branchCode: string } | null> { const clientId = String(input.clientId || '').trim(); const supplierCode = String(input.supplierCode || '').trim(); const branchCode = String(input.branchCode || '').trim(); const secretVer = Number(input.secretVer); if (!clientId || !supplierCode || !branchCode || !Number.isFinite(secretVer)) return null; const client = await loadActiveIntegrationClient(clientId); if (!client || client.status !== 1) return null; if (Number(client.secret_version) !== secretVer) return null; const bind = await pool.query( `SELECT 1 FROM public.supplier_integration_client_suppliers WHERE client_id = $1 AND supplier_code = $2 AND branch_code = $3 LIMIT 1`, [clientId, supplierCode, branchCode] ); if (!bind.rows[0]) return null; return { clientId, supplierCode, branchCode }; }