Compare commits
7
Commits
18cfc8e1b2
...
b8f53d3660
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8f53d3660 | ||
|
|
10fa48a52f | ||
|
|
68faf840cf | ||
|
|
f21b3711df | ||
|
|
f4760a4c5b | ||
|
|
1774239553 | ||
|
|
5e10096fea |
@@ -6,7 +6,7 @@ import { FilesystemBackend } from "deepagents";
|
||||
*
|
||||
* 相比原生非 virtualMode 模式的两个安全缺口:
|
||||
* 1. 原生 resolvePath 对绝对路径原样放行(可读磁盘任意文件),此处强制锁定在 rootDir 内;
|
||||
* 2. 沙箱根下的敏感文件(conf.json、.env*、logs、dataDir)默认禁止访问,
|
||||
* 2. 沙箱根下的敏感文件(版本库元数据、.env*、conf.json、logs、dataDir)默认禁止访问,
|
||||
* 防止 LLM 通过 read_file/grep 读取密钥、数据库连接串及其他用户记忆。
|
||||
*
|
||||
* 注意:memory(AGENTS.md)与 skills(SKILL.md)也经由 backend 加载,
|
||||
@@ -17,6 +17,11 @@ import { FilesystemBackend } from "deepagents";
|
||||
* 永远匹配不上(grep 会泄露 conf.json 内容)。敏感路径拦截必须保持在后端层实现。
|
||||
*/
|
||||
export class RestrictedFilesystemBackend extends FilesystemBackend {
|
||||
// 任意层级都拦截的名称:.git 含历史提交(可能残留已轮换的密钥),conf.json 含密钥与库口令
|
||||
static DENY_SEGMENTS = [".git", ".env", "conf.json", "id_rsa", "id_ed25519"];
|
||||
// 按后缀拦截的密钥/证书文件
|
||||
static DENY_SUFFIXES = [".pem", ".key", ".p12", ".pfx", ".keystore"];
|
||||
|
||||
constructor(options = {}) {
|
||||
super(options);
|
||||
this.denyPaths = (options.deny ?? ["conf.json", "logs"]).map(d => String(d).toLowerCase().replace(/\/+$/, ""));
|
||||
@@ -27,8 +32,18 @@ export class RestrictedFilesystemBackend extends FilesystemBackend {
|
||||
const rel = path.relative(this.cwd, fullPath);
|
||||
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false;
|
||||
const norm = rel.split(path.sep).join("/").toLowerCase();
|
||||
// 根目录下的 .env / .env.local 等
|
||||
if (norm === ".env" || norm.startsWith(".env.")) return true;
|
||||
|
||||
// 固定拦截项与调用方传入的 deny 列表并列判断,避免使用方忘记配置
|
||||
for (const seg of norm.split("/")) {
|
||||
if (
|
||||
RestrictedFilesystemBackend.DENY_SEGMENTS.includes(seg) ||
|
||||
seg.startsWith(".env.")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (RestrictedFilesystemBackend.DENY_SUFFIXES.some(s => norm.endsWith(s))) return true;
|
||||
|
||||
return this.denyPaths.some(d => norm === d || norm.startsWith(d + "/"));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import z from "zod";
|
||||
import { DBModel } from "../../../../models/index.js";
|
||||
import { escapeRegex } from "./utils.js";
|
||||
|
||||
function createEscortRecordQueryTool(userInfo) {
|
||||
const userMobile = userInfo?.profile?.mobile;
|
||||
const userId = userInfo?._id;
|
||||
|
||||
return tool(
|
||||
async ({ patientName, status, page = 1, pageSize = 20 }) => {
|
||||
@@ -11,17 +12,20 @@ function createEscortRecordQueryTool(userInfo) {
|
||||
const filter = {};
|
||||
|
||||
if (patientName) {
|
||||
filter["patient.name"] = { $regex: patientName, $options: "i" };
|
||||
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
|
||||
}
|
||||
|
||||
// 强制使用当前登录用户的手机号进行查询
|
||||
if (!userMobile) {
|
||||
// 按订单归属用户过滤:不能用手机号作为隔离键,
|
||||
// 因为手机号可由用户自行修改(改到他人号码即可读到他人订单)
|
||||
if (!userId) {
|
||||
return {
|
||||
success: false,
|
||||
error: "用户未登录或手机号缺失,无法查询陪诊记录",
|
||||
error: "用户未登录,无法查询陪诊记录",
|
||||
};
|
||||
}
|
||||
filter["patient.mobile"] = userMobile;
|
||||
filter.userId = userId;
|
||||
// 软删除的订单对用户端不可见
|
||||
filter.deletedAt = null;
|
||||
|
||||
if (status) {
|
||||
filter.status = status;
|
||||
@@ -54,7 +58,7 @@ function createEscortRecordQueryTool(userInfo) {
|
||||
{
|
||||
name: "escort_record_query",
|
||||
description:
|
||||
"Query escort records from database for the current user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current logged-in user's mobile phone number.",
|
||||
"Query escort records from database for the current user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current logged-in user.",
|
||||
schema: z.object({
|
||||
patientName: z
|
||||
.string()
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import z from "zod";
|
||||
import { DBModel } from "../../../../models/index.js";
|
||||
import { escapeRegex } from "./utils.js";
|
||||
|
||||
const escortRecordQueryTool = tool(
|
||||
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
|
||||
try {
|
||||
const filter = {};
|
||||
const filter = { deletedAt: null };
|
||||
|
||||
if (patientName) {
|
||||
filter["patient.name"] = { $regex: patientName, $options: "i" };
|
||||
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
|
||||
}
|
||||
|
||||
if (mobile) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { tool } from "@langchain/core/tools";
|
||||
import z from "zod";
|
||||
import mongoose from "mongoose";
|
||||
import { DBModel } from "../../../../models/index.js";
|
||||
import { canTransition, STATUS_TRANSITIONS } from "../../../../utils/record_state.js";
|
||||
|
||||
const escortRecordSetTool = tool(
|
||||
async ({ orderId, status, notes, payment }) => {
|
||||
@@ -28,9 +29,20 @@ const escortRecordSetTool = tool(
|
||||
};
|
||||
}
|
||||
|
||||
// 状态迁移必须与接口层同一套规则:否则 Agent 能把已完成订单改回进行中,
|
||||
// 绕过状态机并造成费用/服务记录不一致
|
||||
const update = {};
|
||||
|
||||
if (status !== undefined) {
|
||||
if (status !== undefined && status !== record.status) {
|
||||
if (!canTransition(record.status, status)) {
|
||||
const allowed = STATUS_TRANSITIONS[record.status] || [];
|
||||
return {
|
||||
success: false,
|
||||
error: `Illegal status transition: ${record.status} -> ${status}. Allowed: ${
|
||||
allowed.length ? allowed.join(", ") : "none (terminal state)"
|
||||
}`,
|
||||
};
|
||||
}
|
||||
update.status = status;
|
||||
}
|
||||
|
||||
@@ -60,12 +72,23 @@ const escortRecordSetTool = tool(
|
||||
|
||||
update["meta.updatetime"] = Date.now();
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.findByIdAndUpdate(
|
||||
record._id,
|
||||
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单
|
||||
const filter = { _id: record._id, deletedAt: null };
|
||||
if (status !== undefined && status !== record.status) filter.status = record.status;
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.findOneAndUpdate(
|
||||
filter,
|
||||
{ $set: update },
|
||||
{ new: true }
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedRecord) {
|
||||
return {
|
||||
success: false,
|
||||
error: "Record state changed while updating. Re-query the record and retry.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: updatedRecord,
|
||||
@@ -104,9 +127,9 @@ const escortRecordSetTool = tool(
|
||||
totalFee: z.number().optional().describe("Total service fee (RMB)"),
|
||||
paidFee: z.number().optional().describe("Amount already paid (RMB)"),
|
||||
status: z
|
||||
.enum(["unpaid", "partial", "paid", "refunded"])
|
||||
.enum(["unpaid", "partial", "paid", "refunding", "refunded"])
|
||||
.optional()
|
||||
.describe("Payment status: unpaid, partial, paid, refunded"),
|
||||
.describe("Payment status: unpaid, partial, paid, refunding, refunded"),
|
||||
})
|
||||
.optional()
|
||||
.describe("Payment information to update"),
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* 数据库工具的公共小工具
|
||||
*/
|
||||
|
||||
/**
|
||||
* 转义正则元字符,用于把用户/模型输入当作字面量做模糊匹配
|
||||
*
|
||||
* 直接把输入拼进 $regex 有两个问题:用户输入 "(" 会导致查询报错,
|
||||
* 输入嵌套量词(如 (a+)+$)可能触发 ReDoS。这里统一转义并截断长度。
|
||||
*
|
||||
* @param {string} input 原始关键词
|
||||
* @param {number} maxLength 最大参与匹配的长度
|
||||
* @returns {string}
|
||||
*/
|
||||
function escapeRegex(input, maxLength = 64) {
|
||||
if (typeof input !== "string") return "";
|
||||
return input
|
||||
.slice(0, maxLength)
|
||||
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
export { escapeRegex };
|
||||
@@ -3,6 +3,32 @@
|
||||
import { tool } from '@langchain/core/tools';
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* 敏感变量判定:按命名模式兜底,而不是只认几个固定关键词。
|
||||
*
|
||||
* 原实现只匹配 API_KEY/SECRET/PASSWORD/TOKEN/CREDENTIAL,
|
||||
* 会漏掉 MONGODB_URI、DB_PASS、SIGN_KEY 这类常见命名。
|
||||
*/
|
||||
const SENSITIVE_PATTERNS = [
|
||||
/API_?KEY/i,
|
||||
/SECRET/i,
|
||||
/PASS(WORD|WD)?/i,
|
||||
/TOKEN/i,
|
||||
/CREDENTIAL/i,
|
||||
/PRIVATE/i,
|
||||
/AUTH/i,
|
||||
/(^|_)KEY($|_)/i,
|
||||
/(^|_)URI($|_)/i,
|
||||
/DSN/i,
|
||||
/CONN(ECTION)?/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {string} key 环境变量名
|
||||
* @returns {boolean}
|
||||
*/
|
||||
const isSensitive = (key) => SENSITIVE_PATTERNS.some((p) => p.test(key));
|
||||
|
||||
/**
|
||||
* 获取环境变量工具
|
||||
* @param {Object} input - 输入参数
|
||||
@@ -13,9 +39,6 @@ export const getEnvTool = tool(
|
||||
async (input) => {
|
||||
const { name } = input || {};
|
||||
|
||||
const sensitiveKeys = ['API_KEY', 'SECRET', 'PASSWORD', 'TOKEN', 'CREDENTIAL'];
|
||||
const isSensitive = (key) => sensitiveKeys.some(s => key.toUpperCase().includes(s));
|
||||
|
||||
if (name) {
|
||||
const value = process.env[name];
|
||||
if (value === undefined) {
|
||||
@@ -44,40 +67,4 @@ export const getEnvTool = tool(
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 设置环境变量工具
|
||||
* @param {Object} input - 输入参数
|
||||
* @param {string} input.name - 环境变量名
|
||||
* @param {string} input.value - 环境变量值
|
||||
* @returns {string} - 返回设置结果的JSON字符串
|
||||
*/
|
||||
export const setEnvTool = tool(
|
||||
async (input) => {
|
||||
const { name, value } = input || {};
|
||||
|
||||
if (!name) {
|
||||
return JSON.stringify({ error: 'Environment variable name is required' });
|
||||
}
|
||||
|
||||
if (value === undefined) {
|
||||
return JSON.stringify({ error: 'Environment variable value is required' });
|
||||
}
|
||||
|
||||
try {
|
||||
process.env[name] = value;
|
||||
return JSON.stringify({ success: true, name, value });
|
||||
} catch (error) {
|
||||
return JSON.stringify({ error: `Failed to set environment variable: ${error.message}` });
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'env_set',
|
||||
description: '设置环境变量的值。',
|
||||
schema: z.object({
|
||||
name: z.string().describe('环境变量名'),
|
||||
value: z.string().describe('环境变量值')
|
||||
})
|
||||
}
|
||||
);
|
||||
|
||||
export default getEnvTool;
|
||||
@@ -1,257 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import os from 'os'
|
||||
import { promisify } from 'util'
|
||||
import { exec } from 'child_process'
|
||||
|
||||
const execPromise = promisify(exec)
|
||||
|
||||
/**
|
||||
* 获取系统文件信息工具
|
||||
* @returns {string} - 返回系统文件信息的 JSON 字符串,包括分区信息和各分区剩余空间
|
||||
*/
|
||||
export const getSystemFileInfoTool = tool(
|
||||
async (input) => {
|
||||
try {
|
||||
const fileSystemInfo = {
|
||||
platform: os.platform(),
|
||||
partitions: [],
|
||||
volumeInfo: [],
|
||||
diskHealth: [],
|
||||
inodeInfo: []
|
||||
}
|
||||
|
||||
// 获取文件系统信息(Windows)
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const { stdout } = await execPromise('powershell -Command "Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID,Description,FileSystem,Size,FreeSpace,VolumeName | ConvertTo-Json"')
|
||||
const partitionData = JSON.parse(stdout)
|
||||
const partitionsArray = Array.isArray(partitionData) ? partitionData : [partitionData]
|
||||
|
||||
fileSystemInfo.partitions = partitionsArray.map(disk => {
|
||||
const size = disk.Size ? parseInt(disk.Size) : 0
|
||||
const freeSpace = disk.FreeSpace ? parseInt(disk.FreeSpace) : 0
|
||||
const usedSpace = size - freeSpace
|
||||
|
||||
return {
|
||||
device: disk.DeviceID || 'N/A',
|
||||
description: disk.Description || 'N/A',
|
||||
filesystem: disk.FileSystem || 'N/A',
|
||||
volumeName: disk.VolumeName || 'N/A',
|
||||
size: size > 0 ? `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'N/A',
|
||||
freeSpace: freeSpace > 0 ? `${(freeSpace / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'N/A',
|
||||
usedSpace: usedSpace > 0 ? `${(usedSpace / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'N/A',
|
||||
usePercent: size > 0 ? `${((usedSpace / size) * 100).toFixed(2)}%` : 'N/A'
|
||||
}
|
||||
}).filter(item => item)
|
||||
|
||||
// 获取卷详细信息(Windows)
|
||||
try {
|
||||
const { stdout } = await execPromise('powershell -Command "Get-WmiObject Win32_LogicalDisk | Select-Object VolumeName,VolumeSerialNumber,FileSystem,MaximumComponentLength,DeviceID,DriveType | ConvertTo-Json"')
|
||||
const allVolumeData = JSON.parse(stdout)
|
||||
const volumeArray = Array.isArray(allVolumeData) ? allVolumeData : [allVolumeData]
|
||||
|
||||
fileSystemInfo.volumeInfo = volumeArray.map(vol => ({
|
||||
device: vol.DeviceID || 'N/A',
|
||||
volumeName: vol.VolumeName || 'N/A',
|
||||
serialNumber: vol.VolumeSerialNumber || 'N/A',
|
||||
fileSystem: vol.FileSystem || 'N/A',
|
||||
maxComponentLength: vol.MaximumComponentLength || 'N/A',
|
||||
deviceID: vol.DeviceID || 'N/A',
|
||||
driveType: vol.DriveType === 2 ? 'Removable' : vol.DriveType === 3 ? 'Local' : vol.DriveType === 4 ? 'Network' : vol.DriveType === 5 ? 'CD-ROM' : 'Unknown'
|
||||
})).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting volume info:', error)
|
||||
}
|
||||
|
||||
// 获取磁盘健康状态(Windows SMART)
|
||||
try {
|
||||
const { stdout } = await execPromise('powershell -Command "Get-WmiObject Win32_DiskDrive | Select-Object Model,Status,SerialNumber,Size,MediaType | ConvertTo-Json"')
|
||||
const diskData = JSON.parse(stdout)
|
||||
const diskArray = Array.isArray(diskData) ? diskData : [diskData]
|
||||
fileSystemInfo.diskHealth = diskArray.map(disk => {
|
||||
return {
|
||||
model: disk.Model || 'N/A',
|
||||
status: disk.Status || 'N/A',
|
||||
serialNumber: disk.SerialNumber || 'N/A',
|
||||
size: disk.Size ? `${(parseInt(disk.Size) / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'N/A'
|
||||
}
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting disk health:', error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting file system info:', error)
|
||||
fileSystemInfo.error = 'Error getting file system info'
|
||||
}
|
||||
}
|
||||
// 获取文件系统信息(Linux)
|
||||
else if (os.platform() === 'linux') {
|
||||
try {
|
||||
const { stdout } = await execPromise('df -h')
|
||||
fileSystemInfo.partitions = stdout.trim().split('\n').slice(1).map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
device: parts[0],
|
||||
size: parts[1],
|
||||
usedSpace: parts[2],
|
||||
freeSpace: parts[3],
|
||||
usePercent: parts[4],
|
||||
mountedOn: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
|
||||
// 获取挂载选项和文件系统类型(Linux)
|
||||
try {
|
||||
const { stdout } = await execPromise('mount | column -t')
|
||||
const mountLines = stdout.trim().split('\n')
|
||||
const mountInfo = {}
|
||||
mountLines.forEach(line => {
|
||||
const match = line.match(/^(.+?)\s+on\s+(.+?)\s+type\s+(.+?)\s+\((.*)\)$/)
|
||||
if (match) {
|
||||
mountInfo[match[2]] = {
|
||||
device: match[1],
|
||||
filesystem: match[3],
|
||||
options: match[4]
|
||||
}
|
||||
}
|
||||
})
|
||||
fileSystemInfo.mountInfo = mountInfo
|
||||
} catch (error) {
|
||||
console.error('Error getting mount info:', error)
|
||||
}
|
||||
|
||||
// 获取inode信息(Linux)
|
||||
try {
|
||||
const { stdout } = await execPromise('df -i')
|
||||
fileSystemInfo.inodeInfo = stdout.trim().split('\n').slice(1).map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
device: parts[0],
|
||||
totalInodes: parts[1],
|
||||
usedInodes: parts[2],
|
||||
freeInodes: parts[3],
|
||||
usePercent: parts[4],
|
||||
mountedOn: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting inode info:', error)
|
||||
}
|
||||
|
||||
// 获取磁盘健康状态(Linux SMART)
|
||||
try {
|
||||
const { stdout } = await execPromise('smartctl --health --json /dev/sda 2>/dev/null || echo "{}"')
|
||||
if (stdout && stdout.includes('smart_status')) {
|
||||
const healthData = JSON.parse(stdout)
|
||||
fileSystemInfo.diskHealth.push({
|
||||
device: '/dev/sda',
|
||||
status: healthData.smart_status?.passed ? 'OK' : 'Failed',
|
||||
powerOnHours: healthData.power_on_time?.hours || 'N/A',
|
||||
temperature: healthData.temperature?.current || 'N/A'
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('SMART info not available or requires root')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting file system info:', error)
|
||||
fileSystemInfo.error = 'Error getting file system info'
|
||||
}
|
||||
}
|
||||
// 获取文件系统信息(macOS)
|
||||
else if (os.platform() === 'darwin') {
|
||||
try {
|
||||
const { stdout } = await execPromise('df -h')
|
||||
fileSystemInfo.partitions = stdout.trim().split('\n').slice(1).map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
device: parts[0],
|
||||
size: parts[1],
|
||||
usedSpace: parts[2],
|
||||
freeSpace: parts[3],
|
||||
usePercent: parts[4],
|
||||
mountedOn: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
|
||||
// 获取卷详细信息(macOS)
|
||||
try {
|
||||
const diskInfo = await execPromise('diskutil info -all')
|
||||
const diskLines = diskInfo.stdout.trim().split('\n\n')
|
||||
diskLines.forEach(disk => {
|
||||
const volMatch = disk.match(/Volume Name:\s+(.+)/)
|
||||
const devMatch = disk.match(/Device Node:\s+(.+)/)
|
||||
const fsMatch = disk.match(/File System Personality:\s+(.+)/)
|
||||
const serialMatch = disk.match(/Disk UUID:\s+(.+)/)
|
||||
|
||||
if (devMatch) {
|
||||
fileSystemInfo.volumeInfo.push({
|
||||
device: devMatch[1],
|
||||
volumeName: volMatch ? volMatch[1] : 'N/A',
|
||||
filesystem: fsMatch ? fsMatch[1] : 'N/A',
|
||||
serialNumber: serialMatch ? serialMatch[1] : 'N/A'
|
||||
})
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Error getting volume info:', error)
|
||||
}
|
||||
|
||||
// 获取inode信息(macOS)
|
||||
try {
|
||||
const { stdout } = await execPromise('df -i')
|
||||
fileSystemInfo.inodeInfo = stdout.trim().split('\n').slice(1).map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
device: parts[0],
|
||||
totalInodes: parts[1],
|
||||
usedInodes: parts[2],
|
||||
freeInodes: parts[3],
|
||||
usePercent: parts[4],
|
||||
mountedOn: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting inode info:', error)
|
||||
}
|
||||
|
||||
// 获取磁盘健康状态(macOS)
|
||||
try {
|
||||
const { stdout } = await execPromise('diskutil smartStatus -all 2>/dev/null || echo "N/A"')
|
||||
if (stdout && stdout !== 'N/A') {
|
||||
fileSystemInfo.diskHealth = stdout.trim()
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('SMART status not available')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting file system info:', error)
|
||||
fileSystemInfo.error = 'Error getting file system info'
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(fileSystemInfo, null, 2)
|
||||
} catch (error) {
|
||||
console.error('Error getting file system info:', error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_system_file_info",
|
||||
description: `获取系统硬盘分区和文件系统信息,包括分区信息、卷标、序列号、磁盘健康状态、inode信息等`,
|
||||
schema: z.object({})
|
||||
}
|
||||
)
|
||||
@@ -1,112 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import os from 'os'
|
||||
import { promisify } from 'util'
|
||||
import { exec } from 'child_process'
|
||||
|
||||
const execPromise = promisify(exec)
|
||||
|
||||
/**
|
||||
* 获取系统硬件配置信息工具
|
||||
* @returns {string} - 返回系统硬件配置信息的 JSON 字符串
|
||||
*/
|
||||
export const getHardwareInfoTool = tool(
|
||||
async (input) => {
|
||||
try {
|
||||
const hardwareInfo = {
|
||||
cpu: {
|
||||
cores: os.cpus().length,
|
||||
model: os.cpus()[0].model,
|
||||
speed: os.cpus()[0].speed
|
||||
},
|
||||
memory: {
|
||||
total: `${(os.totalmem() / (1024 ** 3)).toFixed(2)} GB`,
|
||||
free: `${(os.freemem() / (1024 ** 3)).toFixed(2)} GB`
|
||||
},
|
||||
disks: [],
|
||||
gpu: []
|
||||
}
|
||||
|
||||
// 获取硬盘信息(Windows)
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const { stdout } = await execPromise('powershell -Command "Get-WmiObject Win32_DiskDrive | Select-Object Model,InterfaceType,Size | ConvertTo-Json"')
|
||||
const diskData = JSON.parse(stdout)
|
||||
const diskArray = Array.isArray(diskData) ? diskData : [diskData]
|
||||
hardwareInfo.disks = diskArray.map(disk => ({
|
||||
model: disk.Model || 'N/A',
|
||||
interfaceType: disk.InterfaceType || 'N/A',
|
||||
size: disk.Size ? `${(parseInt(disk.Size) / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'N/A'
|
||||
})).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting disk info:', error)
|
||||
}
|
||||
|
||||
// 获取显卡信息(Windows)
|
||||
try {
|
||||
const { stdout } = await execPromise('wmic path win32_videocontroller get name')
|
||||
hardwareInfo.gpu = stdout.trim().split('\n').slice(1).filter(line => line.trim())
|
||||
} catch (error) {
|
||||
console.error('Error getting GPU info:', error)
|
||||
}
|
||||
}
|
||||
// 获取硬盘和显卡信息(Linux)
|
||||
else if (os.platform() === 'linux') {
|
||||
try {
|
||||
const { stdout } = await execPromise('lsblk -o NAME,MODEL,SIZE,TYPE | grep disk')
|
||||
const diskLines = stdout.trim().split('\n')
|
||||
hardwareInfo.disks = diskLines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 3) {
|
||||
return {
|
||||
name: parts[0],
|
||||
model: parts.slice(1, -1).join(' '),
|
||||
size: parts[parts.length - 1]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting disk info:', error)
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execPromise('lspci | grep VGA')
|
||||
hardwareInfo.gpu = stdout.trim().split('\n').map(line => line.trim())
|
||||
} catch (error) {
|
||||
console.error('Error getting GPU info:', error)
|
||||
}
|
||||
}
|
||||
// 获取硬盘和显卡信息(macOS)
|
||||
else if (os.platform() === 'darwin') {
|
||||
try {
|
||||
const { stdout } = await execPromise('diskutil list')
|
||||
hardwareInfo.disks = [{
|
||||
info: stdout.trim()
|
||||
}]
|
||||
} catch (error) {
|
||||
console.error('Error getting disk info:', error)
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await execPromise('system_profiler SPDisplaysDataType')
|
||||
hardwareInfo.gpu = [{
|
||||
info: stdout.trim()
|
||||
}]
|
||||
} catch (error) {
|
||||
console.error('Error getting GPU info:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(hardwareInfo, null, 2)
|
||||
} catch (error) {
|
||||
console.error('Error getting hardware info:', error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_hardware_info",
|
||||
description: `获取系统硬件配置信息,包括CPU、内存、硬盘、显卡等`,
|
||||
schema: z.object({})
|
||||
}
|
||||
)
|
||||
@@ -1,101 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import os from 'os'
|
||||
import { promisify } from 'util'
|
||||
import { exec } from 'child_process'
|
||||
|
||||
const execPromise = promisify(exec)
|
||||
|
||||
/**
|
||||
* 获取已安装软件信息工具
|
||||
* @returns {string} - 返回已安装软件信息的 JSON 字符串
|
||||
*/
|
||||
export const getInstalledSoftwareTool = tool(
|
||||
async (input) => {
|
||||
try {
|
||||
const softwareInfo = {
|
||||
platform: os.platform(),
|
||||
software: []
|
||||
}
|
||||
|
||||
// 获取Windows已安装软件
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const { stdout } = await execPromise('powershell -Command "Get-WmiObject Win32_Product | Select-Object Name,Version,Vendor,InstallDate | ConvertTo-Json"')
|
||||
const softwareData = JSON.parse(stdout)
|
||||
const softwareArray = Array.isArray(softwareData) ? softwareData : [softwareData]
|
||||
softwareInfo.software = softwareArray.map(soft => ({
|
||||
name: soft.Name || 'N/A',
|
||||
version: soft.Version || 'N/A',
|
||||
vendor: soft.Vendor || 'N/A',
|
||||
installDate: soft.InstallDate || 'N/A'
|
||||
})).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting installed software:', error)
|
||||
}
|
||||
}
|
||||
// 获取Linux已安装软件
|
||||
else if (os.platform() === 'linux') {
|
||||
try {
|
||||
// 尝试使用dpkg(Debian/Ubuntu)
|
||||
const { stdout: dpkgOutput } = await execPromise('dpkg -l 2>/dev/null || echo "N/A"')
|
||||
if (dpkgOutput && dpkgOutput !== 'N/A') {
|
||||
const lines = dpkgOutput.trim().split('\n').slice(5)
|
||||
softwareInfo.software = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 3) {
|
||||
return {
|
||||
name: parts[1],
|
||||
version: parts[2],
|
||||
description: parts.slice(3).join(' ')
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} else {
|
||||
// 尝试使用rpm(RHEL/CentOS)
|
||||
const { stdout: rpmOutput } = await execPromise('rpm -qa 2>/dev/null || echo "N/A"')
|
||||
if (rpmOutput && rpmOutput !== 'N/A') {
|
||||
const lines = rpmOutput.trim().split('\n')
|
||||
softwareInfo.software = lines.map(line => {
|
||||
const match = line.match(/(.+)-(.+)-(.+)/)
|
||||
if (match) {
|
||||
return {
|
||||
name: match[1],
|
||||
version: `${match[2]}-${match[3]}`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting installed software:', error)
|
||||
}
|
||||
}
|
||||
// 获取macOS已安装软件
|
||||
else if (os.platform() === 'darwin') {
|
||||
try {
|
||||
const { stdout } = await execPromise('find /Applications -name "*.app" -type d | sort')
|
||||
const apps = stdout.trim().split('\n')
|
||||
softwareInfo.software = apps.map(app => ({
|
||||
name: app.split('/').pop().replace('.app', ''),
|
||||
path: app
|
||||
})).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting installed software:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(softwareInfo, null, 2)
|
||||
} catch (error) {
|
||||
console.error('Error getting installed software:', error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_installed_software",
|
||||
description: `获取系统已安装的软件信息,包括软件名称、版本、供应商等`,
|
||||
schema: z.object({})
|
||||
}
|
||||
)
|
||||
@@ -1,89 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import os from 'os'
|
||||
import { promisify } from 'util'
|
||||
import { exec } from 'child_process'
|
||||
|
||||
const execPromise = promisify(exec)
|
||||
|
||||
/**
|
||||
* 获取操作系统信息工具
|
||||
* @returns {string} - 返回操作系统信息的 JSON 字符串
|
||||
*/
|
||||
export const getOsInfoTool = tool(
|
||||
async (input) => {
|
||||
try {
|
||||
const osInfo = {
|
||||
platform: os.platform(),
|
||||
arch: os.arch(),
|
||||
release: os.release(),
|
||||
hostname: os.hostname(),
|
||||
uptime: `${Math.round(os.uptime() / 3600)} hours`,
|
||||
nodeVersion: process.version,
|
||||
homeDir: os.homedir(),
|
||||
tempDir: os.tmpdir(),
|
||||
userInfo: os.userInfo()
|
||||
}
|
||||
|
||||
// 获取Windows详细信息
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const { stdout } = await execPromise('powershell -Command "Get-WmiObject Win32_OperatingSystem | Select-Object Caption,Version,BuildNumber,OSArchitecture | ConvertTo-Json"')
|
||||
const winInfo = JSON.parse(stdout)
|
||||
osInfo.windows = {
|
||||
caption: winInfo.Caption || 'N/A',
|
||||
version: winInfo.Version || 'N/A',
|
||||
buildNumber: winInfo.BuildNumber || 'N/A',
|
||||
architecture: winInfo.OSArchitecture || 'N/A'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting Windows info:', error)
|
||||
}
|
||||
}
|
||||
// 获取Linux详细信息
|
||||
else if (os.platform() === 'linux') {
|
||||
try {
|
||||
const { stdout } = await execPromise('cat /etc/os-release')
|
||||
const lines = stdout.trim().split('\n')
|
||||
const linuxInfo = {}
|
||||
lines.forEach(line => {
|
||||
const match = line.match(/(.+?)=(.+)/)
|
||||
if (match) {
|
||||
linuxInfo[match[1]] = match[2].replace(/"/g, '')
|
||||
}
|
||||
})
|
||||
osInfo.linux = linuxInfo
|
||||
} catch (error) {
|
||||
console.error('Error getting Linux info:', error)
|
||||
}
|
||||
}
|
||||
// 获取macOS详细信息
|
||||
else if (os.platform() === 'darwin') {
|
||||
try {
|
||||
const { stdout } = await execPromise('sw_vers')
|
||||
const lines = stdout.trim().split('\n')
|
||||
const macInfo = {}
|
||||
lines.forEach(line => {
|
||||
const match = line.match(/(.+?):\s+(.+)/)
|
||||
if (match) {
|
||||
macInfo[match[1]] = match[2]
|
||||
}
|
||||
})
|
||||
osInfo.macOS = macInfo
|
||||
} catch (error) {
|
||||
console.error('Error getting macOS info:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(osInfo, null, 2)
|
||||
} catch (error) {
|
||||
console.error('Error getting OS info:', error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_os_info",
|
||||
description: `获取操作系统信息,包括平台、架构、版本、主机名、运行时间等`,
|
||||
schema: z.object({})
|
||||
}
|
||||
)
|
||||
@@ -1,242 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import os from 'os'
|
||||
import { promisify } from 'util'
|
||||
import { exec } from 'child_process'
|
||||
|
||||
const execPromise = promisify(exec)
|
||||
|
||||
/**
|
||||
* 获取系统网卡和网络连接信息工具
|
||||
* @returns {string} - 返回网络信息的 JSON 字符串,包括网卡信息和网络连接信息
|
||||
*/
|
||||
export const getNetworkInfoTool = tool(
|
||||
async (input) => {
|
||||
try {
|
||||
const networkInfo = {
|
||||
platform: os.platform(),
|
||||
networkInterfaces: [],
|
||||
dnsServers: [],
|
||||
gateway: []
|
||||
}
|
||||
|
||||
// 获取网络接口信息(跨平台)
|
||||
const interfaces = os.networkInterfaces()
|
||||
for (const [name, addresses] of Object.entries(interfaces)) {
|
||||
networkInfo.networkInterfaces.push({
|
||||
name,
|
||||
addresses: addresses.map(addr => ({
|
||||
family: addr.family,
|
||||
address: addr.address,
|
||||
netmask: addr.netmask,
|
||||
mac: addr.mac,
|
||||
internal: addr.internal,
|
||||
cidr: addr.cidr
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
// 获取详细网络信息(Windows)
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const { stdout } = await execPromise('ipconfig /all')
|
||||
const lines = stdout.trim().split('\n')
|
||||
let currentAdapter = null
|
||||
|
||||
lines.forEach(line => {
|
||||
const adapterMatch = line.match(/适配器\s+(.+?):/)
|
||||
if (adapterMatch) {
|
||||
if (currentAdapter) {
|
||||
networkInfo.networkInterfaces.push(currentAdapter)
|
||||
}
|
||||
currentAdapter = {
|
||||
name: adapterMatch[1],
|
||||
description: '',
|
||||
macAddress: '',
|
||||
dhcpEnabled: false,
|
||||
ipAddress: [],
|
||||
subnetMask: [],
|
||||
defaultGateway: [],
|
||||
dnsServers: []
|
||||
}
|
||||
} else if (currentAdapter) {
|
||||
const descMatch = line.match(/描述\s+(.+)/)
|
||||
if (descMatch) currentAdapter.description = descMatch[1].trim()
|
||||
|
||||
const macMatch = line.match(/物理地址\s+:\s+(.+)/)
|
||||
if (macMatch) currentAdapter.macAddress = macMatch[1].trim()
|
||||
|
||||
const dhcpMatch = line.match(/DHCP 已启用\s+:\s+(.+)/)
|
||||
if (dhcpMatch) currentAdapter.dhcpEnabled = dhcpMatch[1].trim() === '是'
|
||||
|
||||
const ipMatch = line.match(/IPv4 地址\s+:\s+(.+)/)
|
||||
if (ipMatch) currentAdapter.ipAddress.push(ipMatch[1].trim())
|
||||
|
||||
const subnetMatch = line.match(/子网掩码\s+:\s+(.+)/)
|
||||
if (subnetMatch) currentAdapter.subnetMask.push(subnetMatch[1].trim())
|
||||
|
||||
const gatewayMatch = line.match(/默认网关\s+:\s+(.+)/)
|
||||
if (gatewayMatch && gatewayMatch[1].trim()) currentAdapter.defaultGateway.push(gatewayMatch[1].trim())
|
||||
|
||||
const dnsMatch = line.match(/DNS 服务器\s+:\s+(.+)/)
|
||||
if (dnsMatch && dnsMatch[1].trim()) currentAdapter.dnsServers.push(dnsMatch[1].trim())
|
||||
}
|
||||
})
|
||||
|
||||
if (currentAdapter) {
|
||||
networkInfo.networkInterfaces.push(currentAdapter)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting network config:', error)
|
||||
}
|
||||
|
||||
// 获取DNS服务器(Windows)
|
||||
try {
|
||||
const { stdout } = await execPromise('nslookup localhost 2>&1')
|
||||
const dnsMatch = stdout.match(/Server:\s+(.+)/)
|
||||
if (dnsMatch) {
|
||||
networkInfo.dnsServers.push(dnsMatch[1].trim())
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting DNS servers:', error)
|
||||
}
|
||||
}
|
||||
// 获取详细网络信息(Linux)
|
||||
else if (os.platform() === 'linux') {
|
||||
try {
|
||||
const { stdout } = await execPromise('ip addr show')
|
||||
const lines = stdout.trim().split('\n')
|
||||
let currentInterface = null
|
||||
|
||||
lines.forEach(line => {
|
||||
const interfaceMatch = line.match(/^\d+:\s+(\w+):/)
|
||||
if (interfaceMatch) {
|
||||
if (currentInterface) {
|
||||
networkInfo.networkInterfaces.push(currentInterface)
|
||||
}
|
||||
currentInterface = {
|
||||
name: interfaceMatch[1],
|
||||
state: '',
|
||||
macAddress: '',
|
||||
ipAddress: [],
|
||||
subnetMask: []
|
||||
}
|
||||
} else if (currentInterface) {
|
||||
const stateMatch = line.match(/state\s+(\w+)/)
|
||||
if (stateMatch) currentInterface.state = stateMatch[1]
|
||||
|
||||
const macMatch = line.match(/link\/ether\s+([a-fA-F0-9:]+)/)
|
||||
if (macMatch) currentInterface.macAddress = macMatch[1]
|
||||
|
||||
const ipMatch = line.match(/inet\s+(\d+\.\d+\.\d+\.\d+)\/(\d+)/)
|
||||
if (ipMatch) {
|
||||
currentInterface.ipAddress.push(ipMatch[1])
|
||||
const maskLength = parseInt(ipMatch[2])
|
||||
currentInterface.subnetMask.push(maskLength)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (currentInterface) {
|
||||
networkInfo.networkInterfaces.push(currentInterface)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting network config:', error)
|
||||
}
|
||||
|
||||
// 获取DNS服务器(Linux)
|
||||
try {
|
||||
const { stdout } = await execPromise('cat /etc/resolv.conf')
|
||||
const dnsMatches = stdout.match(/nameserver\s+(.+)/g)
|
||||
if (dnsMatches) {
|
||||
networkInfo.dnsServers = dnsMatches.map(match => match.replace('nameserver', '').trim())
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting DNS servers:', error)
|
||||
}
|
||||
|
||||
// 获取网关(Linux)
|
||||
try {
|
||||
const { stdout } = await execPromise('ip route show default')
|
||||
const gatewayMatch = stdout.match(/default via (\d+\.\d+\.\d+\.\d+)/)
|
||||
if (gatewayMatch) {
|
||||
networkInfo.gateway.push(gatewayMatch[1])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting gateway:', error)
|
||||
}
|
||||
}
|
||||
// 获取详细网络信息(macOS)
|
||||
else if (os.platform() === 'darwin') {
|
||||
try {
|
||||
const { stdout } = await execPromise('ifconfig')
|
||||
const lines = stdout.trim().split('\n')
|
||||
let currentInterface = null
|
||||
|
||||
lines.forEach(line => {
|
||||
const interfaceMatch = line.match(/^(\w+):/)
|
||||
if (interfaceMatch) {
|
||||
if (currentInterface) {
|
||||
networkInfo.networkInterfaces.push(currentInterface)
|
||||
}
|
||||
currentInterface = {
|
||||
name: interfaceMatch[1],
|
||||
status: '',
|
||||
macAddress: '',
|
||||
ipAddress: [],
|
||||
subnetMask: []
|
||||
}
|
||||
} else if (currentInterface) {
|
||||
const statusMatch = line.match(/status:\s+(\w+)/)
|
||||
if (statusMatch) currentInterface.status = statusMatch[1]
|
||||
|
||||
const macMatch = line.match(/ether\s+([a-fA-F0-9:]+)/)
|
||||
if (macMatch) currentInterface.macAddress = macMatch[1]
|
||||
|
||||
const ipMatch = line.match(/inet\s+(\d+\.\d+\.\d+\.\d+)\s+netmask\s+(0x[0-9a-fA-F]+)/)
|
||||
if (ipMatch) {
|
||||
currentInterface.ipAddress.push(ipMatch[1])
|
||||
currentInterface.subnetMask.push(ipMatch[2])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (currentInterface) {
|
||||
networkInfo.networkInterfaces.push(currentInterface)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting network config:', error)
|
||||
}
|
||||
|
||||
// 获取DNS服务器(macOS)
|
||||
try {
|
||||
const { stdout } = await execPromise('scutil --dns | grep nameserver | awk \'{print $3}\'')
|
||||
networkInfo.dnsServers = stdout.trim().split('\n').filter(dns => dns)
|
||||
} catch (error) {
|
||||
console.error('Error getting DNS servers:', error)
|
||||
}
|
||||
|
||||
// 获取网关(macOS)
|
||||
try {
|
||||
const { stdout } = await execPromise('netstat -nr | grep default')
|
||||
const gatewayMatch = stdout.match(/default\s+(\d+\.\d+\.\d+\.\d+)/)
|
||||
if (gatewayMatch) {
|
||||
networkInfo.gateway.push(gatewayMatch[1])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting gateway:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(networkInfo, null, 2)
|
||||
} catch (error) {
|
||||
console.error('Error getting network info:', error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_network_info",
|
||||
description: `获取系统网卡和网络信息,包括网卡配置、IP地址、MAC地址、DNS服务器、网关等`,
|
||||
schema: z.object({})
|
||||
}
|
||||
)
|
||||
@@ -1,157 +0,0 @@
|
||||
import * as z from "zod"
|
||||
import { tool } from "langchain"
|
||||
import os from 'os'
|
||||
import { promisify } from 'util'
|
||||
import { exec } from 'child_process'
|
||||
|
||||
const execPromise = promisify(exec)
|
||||
|
||||
/**
|
||||
* 获取系统活动连接和Socket信息工具
|
||||
* @returns {string} - 返回Socket信息的 JSON 字符串,包括活动连接和监听端口等
|
||||
*/
|
||||
export const getSocketInfoTool = tool(
|
||||
async (input) => {
|
||||
try {
|
||||
const socketInfo = {
|
||||
platform: os.platform(),
|
||||
activeConnections: [],
|
||||
listeningPorts: []
|
||||
}
|
||||
|
||||
// 获取活动连接(Windows)
|
||||
if (os.platform() === 'win32') {
|
||||
try {
|
||||
const { stdout } = await execPromise('netstat -ano')
|
||||
const lines = stdout.trim().split('\n').slice(4)
|
||||
socketInfo.activeConnections = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 5) {
|
||||
return {
|
||||
protocol: parts[0],
|
||||
localAddress: parts[1],
|
||||
foreignAddress: parts[2],
|
||||
state: parts[3],
|
||||
processId: parts[4]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting active connections:', error)
|
||||
}
|
||||
|
||||
// 获取监听端口(Windows)
|
||||
try {
|
||||
const { stdout } = await execPromise('netstat -an | findstr LISTENING')
|
||||
const lines = stdout.trim().split('\n')
|
||||
socketInfo.listeningPorts = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 4) {
|
||||
return {
|
||||
protocol: parts[0],
|
||||
localAddress: parts[1],
|
||||
state: parts[3]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting listening ports:', error)
|
||||
}
|
||||
}
|
||||
// 获取活动连接(Linux)
|
||||
else if (os.platform() === 'linux') {
|
||||
try {
|
||||
const { stdout } = await execPromise('ss -tuln')
|
||||
const lines = stdout.trim().split('\n').slice(1)
|
||||
socketInfo.activeConnections = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 5) {
|
||||
return {
|
||||
protocol: parts[0],
|
||||
state: parts[1],
|
||||
localAddress: parts[4],
|
||||
peerAddress: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting active connections:', error)
|
||||
}
|
||||
|
||||
// 获取监听端口(Linux)
|
||||
try {
|
||||
const { stdout } = await execPromise('ss -tulpn')
|
||||
const lines = stdout.trim().split('\n').slice(1)
|
||||
socketInfo.listeningPorts = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
protocol: parts[0],
|
||||
state: parts[1],
|
||||
localAddress: parts[4],
|
||||
processInfo: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting listening ports:', error)
|
||||
}
|
||||
}
|
||||
// 获取活动连接(macOS)
|
||||
else if (os.platform() === 'darwin') {
|
||||
try {
|
||||
const { stdout } = await execPromise('netstat -an')
|
||||
const lines = stdout.trim().split('\n').slice(2)
|
||||
socketInfo.activeConnections = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
protocol: parts[0],
|
||||
localAddress: parts[3],
|
||||
foreignAddress: parts[4],
|
||||
state: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting active connections:', error)
|
||||
}
|
||||
|
||||
// 获取监听端口(macOS)
|
||||
try {
|
||||
const { stdout } = await execPromise('netstat -an | grep LISTEN')
|
||||
const lines = stdout.trim().split('\n')
|
||||
socketInfo.listeningPorts = lines.map(line => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length >= 6) {
|
||||
return {
|
||||
protocol: parts[0],
|
||||
localAddress: parts[3],
|
||||
foreignAddress: parts[4],
|
||||
state: parts[5]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}).filter(item => item)
|
||||
} catch (error) {
|
||||
console.error('Error getting listening ports:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(socketInfo, null, 2)
|
||||
} catch (error) {
|
||||
console.error('Error getting socket info:', error)
|
||||
return JSON.stringify({ error: error.message }, null, 2)
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "get_socket_info",
|
||||
description: `获取系统活动连接和Socket信息,包括TCP/UDP连接、监听端口、进程ID等`,
|
||||
schema: z.object({})
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Agent 出网 HTTP 客户端:统一承载 SSRF 校验、重定向控制、超时上限与响应体截断。
|
||||
*
|
||||
* http_get / http_post 只负责参数整理,真正的安全约束集中在这里,
|
||||
* 避免两个工具各写一套、修了一个漏掉另一个。
|
||||
*
|
||||
* 约束:
|
||||
* - 每一跳都重新做同步 + DNS 校验,最多 3 跳(重定向可被用来绕过首次校验);
|
||||
* - POST 不跟随重定向(303/302 会改写成 GET,语义与安全性都不可控);
|
||||
* - 超时由服务端夹紧到 1s~15s,不接受模型传入的任意大值;
|
||||
* - 响应体最多读取 2MB,超出即截断并标记 truncated。
|
||||
*/
|
||||
|
||||
import { checkUrlAllowedAsync } from "./url_guard.js";
|
||||
|
||||
const DEFAULT_TIMEOUT = 15000;
|
||||
const MAX_TIMEOUT = 15000;
|
||||
const MAX_REDIRECTS = 3;
|
||||
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
|
||||
|
||||
/**
|
||||
* 夹紧超时:非法值用默认值,过大值截到上限
|
||||
* @param {number} timeout 调用方传入的毫秒数
|
||||
* @returns {number}
|
||||
*/
|
||||
function clampTimeout(timeout) {
|
||||
const value = Number(timeout);
|
||||
if (!Number.isFinite(value) || value <= 0) return DEFAULT_TIMEOUT;
|
||||
return Math.min(Math.max(value, 1000), MAX_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取响应体,超过上限时截断
|
||||
* @param {Response} response fetch 响应
|
||||
* @returns {Promise<{buffer: Buffer, truncated: boolean}>}
|
||||
*/
|
||||
async function readBodyLimited(response) {
|
||||
if (!response.body) return { buffer: Buffer.alloc(0), truncated: false };
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
let truncated = false;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
const chunk = Buffer.from(value);
|
||||
if (size + chunk.length > MAX_BODY_BYTES) {
|
||||
chunks.push(chunk.subarray(0, MAX_BODY_BYTES - size));
|
||||
size = MAX_BODY_BYTES;
|
||||
truncated = true;
|
||||
await reader.cancel().catch(() => {});
|
||||
break;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
size += chunk.length;
|
||||
}
|
||||
|
||||
return { buffer: Buffer.concat(chunks), truncated };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起受控的 HTTP 请求
|
||||
* @param {string} url 目标地址
|
||||
* @param {Object} options
|
||||
* @param {string} [options.method] 请求方法
|
||||
* @param {Object} [options.headers] 请求头
|
||||
* @param {string} [options.body] 请求体
|
||||
* @param {number} [options.timeout] 超时毫秒数(会被夹紧)
|
||||
* @returns {Promise<{status:number,statusText:string,headers:Object,buffer:Buffer,text:string,truncated:boolean,url:string}>}
|
||||
*/
|
||||
async function safeFetch(url, options = {}) {
|
||||
const method = (options.method || "GET").toUpperCase();
|
||||
const timeout = clampTimeout(options.timeout);
|
||||
let currentUrl = url;
|
||||
|
||||
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
||||
// 每一跳都重新校验,防止「公网地址 302 到内网」绕过首次检查
|
||||
const blocked = await checkUrlAllowedAsync(currentUrl);
|
||||
if (blocked) throw new Error(blocked);
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
try {
|
||||
const response = await fetch(currentUrl, {
|
||||
method,
|
||||
headers: options.headers,
|
||||
body: options.body,
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (REDIRECT_STATUS.has(response.status)) {
|
||||
const location = response.headers.get("location");
|
||||
await response.body?.cancel().catch(() => {});
|
||||
if (!location) throw new Error(`Redirect without location: ${response.status}`);
|
||||
if (method !== "GET") throw new Error("Redirects are not followed for non-GET requests");
|
||||
currentUrl = new URL(location, currentUrl).toString();
|
||||
continue;
|
||||
}
|
||||
|
||||
const { buffer, truncated } = await readBodyLimited(response);
|
||||
return {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: Object.fromEntries(response.headers.entries()),
|
||||
buffer,
|
||||
text: buffer.toString("utf8"),
|
||||
truncated,
|
||||
url: currentUrl,
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Too many redirects (max ${MAX_REDIRECTS})`);
|
||||
}
|
||||
|
||||
export { safeFetch, clampTimeout };
|
||||
@@ -1,63 +1,58 @@
|
||||
import { tool } from 'langchain';
|
||||
import * as z from 'zod';
|
||||
import { checkUrlAllowed } from './url_guard.js';
|
||||
import { safeFetch } from './http_client.js';
|
||||
|
||||
export const httpGetTool = tool(
|
||||
async ({ url, headers = {}, timeout = 30000 }) => {
|
||||
// SSRF 防护:仅允许 http/https 且目标不得为环回/内网地址
|
||||
const blocked = checkUrlAllowed(url);
|
||||
if (blocked) {
|
||||
return JSON.stringify({ success: false, error: blocked });
|
||||
}
|
||||
|
||||
async ({ url, headers = {}, timeout = 15000 }) => {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
const response = await fetch(url, {
|
||||
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
|
||||
const response = await safeFetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'XAgent-Bot/1.0',
|
||||
...headers
|
||||
},
|
||||
signal: controller.signal
|
||||
timeout
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
const contentType = response.headers.get('content-type') || '';
|
||||
const contentType = response.headers['content-type'] || '';
|
||||
let body;
|
||||
|
||||
if (contentType.includes('application/json')) {
|
||||
body = await response.json();
|
||||
try {
|
||||
body = JSON.parse(response.text);
|
||||
} catch (e) {
|
||||
// 服务端声明 json 但返回非法内容时退回原文,避免工具直接抛错中断对话
|
||||
body = response.text;
|
||||
}
|
||||
} else if (contentType.includes('text/') || contentType.includes('application/javascript')) {
|
||||
body = await response.text();
|
||||
body = response.text;
|
||||
} else {
|
||||
const buffer = await response.arrayBuffer();
|
||||
body = Buffer.from(buffer).toString('base64');
|
||||
body = response.buffer.toString('base64');
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
success: true,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: Object.fromEntries(response.headers.entries()),
|
||||
headers: response.headers,
|
||||
truncated: response.truncated,
|
||||
body
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
return JSON.stringify({ success: false, error: `Request timed out after ${timeout}ms` });
|
||||
return JSON.stringify({ success: false, error: 'Request timed out' });
|
||||
}
|
||||
return JSON.stringify({ success: false, error: error.message });
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'http_get',
|
||||
description: 'Send HTTP GET request and return response content. Supports custom headers and timeout settings.',
|
||||
description: 'Send HTTP GET request and return response content. Response body is capped at 2MB.',
|
||||
schema: z.object({
|
||||
url: z.string().describe('Request URL'),
|
||||
headers: z.record(z.string(), z.string()).optional().describe('Request headers'),
|
||||
timeout: z.number().optional().describe('Timeout in milliseconds, default 30000')
|
||||
timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s')
|
||||
})
|
||||
}
|
||||
);
|
||||
@@ -1,15 +1,9 @@
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import z from "zod";
|
||||
import { checkUrlAllowed } from "./url_guard.js";
|
||||
import { safeFetch } from "./http_client.js";
|
||||
|
||||
const httpPostTool = tool(
|
||||
async ({ url, body, headers = {}, contentType = 'json', timeout = 30000 }) => {
|
||||
// SSRF 防护:仅允许 http/https 且目标不得为环回/内网地址
|
||||
const blocked = checkUrlAllowed(url);
|
||||
if (blocked) {
|
||||
return { success: false, error: blocked };
|
||||
}
|
||||
|
||||
async ({ url, body, headers = {}, contentType = 'json', timeout = 15000 }) => {
|
||||
let requestBody;
|
||||
const requestHeaders = {
|
||||
'User-Agent': 'XAgent-Bot/1.0',
|
||||
@@ -38,50 +32,51 @@ const httpPostTool = tool(
|
||||
}
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
const response = await fetch(url, {
|
||||
// 校验(含 DNS)、超时夹紧、响应体截断统一在 safeFetch 内完成;POST 不跟随重定向
|
||||
const response = await safeFetch(url, {
|
||||
method: 'POST',
|
||||
headers: requestHeaders,
|
||||
body: requestBody,
|
||||
signal: controller.signal
|
||||
timeout
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
const responseContentType = response.headers.get('content-type') || '';
|
||||
const responseContentType = response.headers['content-type'] || '';
|
||||
let responseBody;
|
||||
|
||||
if (responseContentType.includes('application/json')) {
|
||||
responseBody = await response.json();
|
||||
try {
|
||||
responseBody = JSON.parse(response.text);
|
||||
} catch (e) {
|
||||
responseBody = response.text;
|
||||
}
|
||||
} else {
|
||||
responseBody = await response.text();
|
||||
responseBody = response.text;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: Object.fromEntries(response.headers.entries()),
|
||||
headers: response.headers,
|
||||
truncated: response.truncated,
|
||||
body: responseBody
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
return { success: false, error: `Request timed out after ${timeout}ms` };
|
||||
return { success: false, error: 'Request timed out' };
|
||||
}
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "http_post",
|
||||
description: "Send HTTP POST request. Supports JSON and form data.",
|
||||
description: "Send HTTP POST request. Supports JSON and form data. Response body is capped at 2MB.",
|
||||
schema: z.object({
|
||||
url: z.string().describe("Request URL"),
|
||||
body: z.union([z.string(), z.object({})]).describe("Request body, can be string or JSON object"),
|
||||
headers: z.record(z.string()).optional().describe("Request headers"),
|
||||
contentType: z.enum(['json', 'form', 'text', 'raw']).optional().describe("Content type, default json"),
|
||||
timeout: z.number().optional().describe("Timeout in milliseconds, default 30000")
|
||||
timeout: z.number().optional().describe("Timeout in milliseconds, clamped to 1s-15s")
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3,9 +3,16 @@
|
||||
*
|
||||
* Agent 的 HTTP 工具处理的 URL 来自模型输出,而模型输入含不可信的用户内容,
|
||||
* 因此可能被诱导去访问环回/内网地址(如本机 127.0.0.1 上的其他服务、云元数据地址)。
|
||||
* 这里集中做白名单式校验:仅允许 http/https,且目标不能是环回/内网/链路本地地址。
|
||||
*
|
||||
* 两层校验:
|
||||
* 1. checkUrlAllowed —— 同步校验协议与字面量主机(覆盖直接写内网 IP 的情况);
|
||||
* 2. checkUrlAllowedAsync —— 再对域名做 DNS 解析,逐个校验解析结果
|
||||
* (覆盖「公网域名解析到内网地址」的绕过)。仅做同步校验是不够的。
|
||||
*/
|
||||
|
||||
import dns from "dns/promises";
|
||||
import net from "net";
|
||||
|
||||
// 仅允许的协议
|
||||
const ALLOWED_PROTOCOLS = ["http:", "https:"];
|
||||
|
||||
@@ -28,15 +35,56 @@ function isPrivateIPv4(host) {
|
||||
if (a === 169 && b === 254) return true; // 169.254.0.0/16 链路本地(含云 metadata)
|
||||
if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
|
||||
if (a === 192 && b === 168) return true; // 192.168.0.0/16
|
||||
if (a === 192 && b === 0) return true; // 192.0.0.0/24 IETF 保留
|
||||
if (a === 198 && (b === 18 || b === 19)) return true; // 198.18.0.0/15 基准测试
|
||||
if (a >= 224) return true; // 组播与保留段
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 URL 是否允许出网访问
|
||||
* 是否为内网/保留 IPv6 地址
|
||||
* @param {string} host 不带方括号的 IPv6 地址
|
||||
*/
|
||||
function isPrivateIPv6(host) {
|
||||
const h = host.toLowerCase();
|
||||
if (h === "::1" || h === "::") return true;
|
||||
if (/^f[cd]/.test(h)) return true; // 唯一本地 fc00::/7
|
||||
if (/^fe[89ab]/.test(h)) return true; // 链路本地 fe80::/10
|
||||
|
||||
// IPv4 映射地址:URL 会把 ::ffff:127.0.0.1 规范化成 ::ffff:7f00:1
|
||||
const mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
|
||||
if (mapped) return isPrivateIPv4(mapped[1]);
|
||||
const mappedHex = h.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
||||
if (mappedHex) {
|
||||
const hi = parseInt(mappedHex[1], 16);
|
||||
const lo = parseInt(mappedHex[2], 16);
|
||||
return isPrivateIPv4(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
|
||||
}
|
||||
|
||||
// NAT64 64:ff9b::/96 同样内嵌 IPv4
|
||||
const nat64 = h.match(/^64:ff9b::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
||||
if (nat64) {
|
||||
const hi = parseInt(nat64[1], 16);
|
||||
const lo = parseInt(nat64[2], 16);
|
||||
return isPrivateIPv4(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为内网/保留地址(IPv4 或 IPv6 字面量)
|
||||
* @param {string} address IP 地址
|
||||
*/
|
||||
function isPrivateAddress(address) {
|
||||
return net.isIP(address) === 6 ? isPrivateIPv6(address) : isPrivateIPv4(address);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步校验 URL:协议、字面量主机、内网 IP
|
||||
* @param {string} url 待校验的 URL
|
||||
* @returns {string|null} 不允许时返回原因文案,允许时返回 null
|
||||
*/
|
||||
export function checkUrlAllowed(url) {
|
||||
function checkUrlAllowed(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
@@ -54,21 +102,45 @@ export function checkUrlAllowed(url) {
|
||||
if (BLOCKED_HOSTNAMES.has(hostname)) {
|
||||
return `Blocked host: ${hostname}`;
|
||||
}
|
||||
if (isPrivateIPv4(hostname)) {
|
||||
if (isPrivateAddress(hostname)) {
|
||||
return `Blocked private network address: ${hostname}`;
|
||||
}
|
||||
if (hostname.includes(":")) {
|
||||
// IPv6:环回 ::1 / 未指定 :: / 唯一本地 fc00::、fd00:: / 链路本地 fe80::
|
||||
if (hostname === "::1" || hostname === "::") {
|
||||
return `Blocked private network address: ${hostname}`;
|
||||
}
|
||||
if (/^f[cd]/.test(hostname)) {
|
||||
return `Blocked private network address: ${hostname}`;
|
||||
}
|
||||
if (/^fe[89ab]/.test(hostname)) {
|
||||
return `Blocked private network address: ${hostname}`;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 先同步校验,再解析域名并逐个校验解析结果
|
||||
* @param {string} url 待校验的 URL
|
||||
* @returns {Promise<string|null>} 不允许时返回原因文案,允许时返回 null
|
||||
*/
|
||||
async function checkUrlAllowedAsync(url) {
|
||||
const blocked = checkUrlAllowed(url);
|
||||
if (blocked) return blocked;
|
||||
|
||||
const hostname = new URL(url).hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
||||
if (net.isIP(hostname)) return null; // 字面量地址已在同步阶段校验
|
||||
|
||||
let addresses;
|
||||
try {
|
||||
addresses = await dns.lookup(hostname, { all: true });
|
||||
} catch (e) {
|
||||
return `DNS lookup failed: ${hostname}`;
|
||||
}
|
||||
if (!addresses.length) return `DNS lookup returned no address: ${hostname}`;
|
||||
|
||||
for (const { address } of addresses) {
|
||||
if (isPrivateAddress(address)) {
|
||||
return `Blocked private network address: ${hostname} -> ${address}`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export {
|
||||
checkUrlAllowed,
|
||||
checkUrlAllowedAsync,
|
||||
isPrivateAddress,
|
||||
isPrivateIPv4,
|
||||
isPrivateIPv6,
|
||||
};
|
||||
|
||||
@@ -32,7 +32,9 @@ class APP {
|
||||
const start = Date.now();
|
||||
await next();
|
||||
const ms = Date.now() - start;
|
||||
console.log(`${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`);
|
||||
// 只记录路径,不记录查询串:URL 里可能带 token、手机号等敏感参数,
|
||||
// 一旦进入 access log 就等于把凭证/隐私落盘
|
||||
console.log(`${ctx.method} ${ctx.path} - ${ctx.status} - ${ms}ms`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+9
-5
@@ -28,6 +28,8 @@ import ResponseUtil from "../utils/responseUtil.js";
|
||||
const MIN_PUBLIC_REVIEW_COUNT = 5;
|
||||
|
||||
class HandlerEmployee {
|
||||
// 公示列表单页上限:避免一次请求把整张表拖出来
|
||||
static MAX_PAGE_SIZE = 50;
|
||||
// 姓名脱敏:只留姓 + 「陪诊师」,不给全名,降低私下联系(跳单)的可能
|
||||
static maskName(name) {
|
||||
const trimmed = String(name || "").trim();
|
||||
@@ -105,8 +107,10 @@ class HandlerEmployee {
|
||||
// 公示信息本身不敏感,且避免登录态异常导致页面空白
|
||||
async getAttendants(ctx) {
|
||||
try {
|
||||
const page = parseInt(ctx.request.query.page) || 1;
|
||||
const pageSize = parseInt(ctx.request.query.pageSize) || 50;
|
||||
// 分页参数夹紧:pageSize 未上限时可用一个请求把整表拖出来
|
||||
const page = Math.max(1, parseInt(ctx.request.query.page) || 1);
|
||||
const rawSize = parseInt(ctx.request.query.pageSize) || 50;
|
||||
const pageSize = Math.min(Math.max(1, rawSize), HandlerEmployee.MAX_PAGE_SIZE);
|
||||
|
||||
// 只取在职陪诊员。
|
||||
// 排序不按 attendantInfo.rating(无可信来源),改按服务年限 / 累计接单数
|
||||
@@ -125,7 +129,7 @@ class HandlerEmployee {
|
||||
"查询成功"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,9 +172,9 @@ class HandlerEmployee {
|
||||
|
||||
return ResponseUtil.success(ctx, { attendant }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { HandlerEmployee };
|
||||
export { HandlerEmployee };
|
||||
|
||||
+110
-42
@@ -1,6 +1,8 @@
|
||||
import { DBModel } from "../models/index.js";
|
||||
import services from "../resource/services.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import { isAdmin as isAdminUser } from "../utils/permissions.js";
|
||||
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js";
|
||||
|
||||
class HandlerEscortRecord {
|
||||
constructor() {
|
||||
@@ -13,20 +15,24 @@ class HandlerEscortRecord {
|
||||
"shippingAddress",
|
||||
];
|
||||
|
||||
// 用户端可自助修改的字段:费用、状态、陪诊员分配等一律由平台控制
|
||||
static OWNER_UPDATE_FIELDS = [
|
||||
"patient", "healthProfileId", "hospital", "schedule", "notes",
|
||||
// 用户自助可改字段按订单状态区分(费用、状态、陪诊员分配、档案归属一律由平台控制):
|
||||
// - 待支付/已支付:可改医院与排期(改期会写审计时间)
|
||||
// - 进行中:服务已开始,仅可补充就诊人备注,排期与医院不允许用户单方变更
|
||||
// - 终态:全部不可改
|
||||
static OWNER_NOTE_FIELDS = ["notes.patientNote"];
|
||||
static OWNER_BOOKING_FIELDS = [
|
||||
"hospital.province", "hospital.name", "hospital.address", "hospital.department",
|
||||
"hospital.doctor", "hospital.medicalRecordNo", "schedule.date", "schedule.startTime",
|
||||
];
|
||||
static OWNER_EDITABLE_BY_STATUS = {
|
||||
pending: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
confirmed: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
in_progress: ["notes.patientNote"],
|
||||
};
|
||||
|
||||
// 用户端只能取消;服务完成由平台确认,避免用户端重复写入终态。
|
||||
// 迁移规则集中在 utils/record_state.js,与管理端 Agent 工具共用
|
||||
static OWNER_ALLOWED_STATUS = ["cancelled"];
|
||||
static STATUS_TRANSITIONS = {
|
||||
pending: ["confirmed", "cancelled"],
|
||||
confirmed: ["in_progress", "cancelled"],
|
||||
in_progress: ["completed"],
|
||||
completed: [],
|
||||
cancelled: [],
|
||||
};
|
||||
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
@@ -36,7 +42,31 @@ class HandlerEscortRecord {
|
||||
* @param {Object} user token 解析出的用户
|
||||
*/
|
||||
static isAdmin(user) {
|
||||
return !!(user && user.app && ("wxapp-escort-admin" in user.app));
|
||||
return isAdminUser(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户端在当前状态下可自助修改的字段清单(白名单精确匹配,点号路径)
|
||||
* @param {string} status 订单状态
|
||||
* @returns {string[]}
|
||||
*/
|
||||
static ownerEditableFields(status) {
|
||||
return HandlerEscortRecord.OWNER_EDITABLE_BY_STATUS[status] || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 就诊人快照:下单与更换档案共用,保证订单里的展示字段一致
|
||||
* @param {Object} profile 健康档案文档
|
||||
* @returns {Object}
|
||||
*/
|
||||
static buildPatientSnapshot(profile) {
|
||||
const patient = {
|
||||
name: profile.profile?.name || "",
|
||||
mobile: profile.profile?.mobile || "",
|
||||
birth: profile.profile?.birth || "",
|
||||
};
|
||||
if (["male", "female"].includes(profile.profile?.sex)) patient.sex = profile.profile.sex;
|
||||
return patient;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,11 +80,17 @@ class HandlerEscortRecord {
|
||||
return String(record.userId) === String(user?._id);
|
||||
}
|
||||
|
||||
static pickFields(body, allowFields = HandlerEscortRecord.RECORD_FIELDS) {
|
||||
/**
|
||||
* 从入参中挑出白名单字段
|
||||
* @param {Object} body 请求体
|
||||
* @param {string[]} allowFields 允许的字段(支持点号路径)
|
||||
* @param {boolean} exact 是否精确匹配;用户端用 true,防止 notes.patientNote.x 这类嵌套越界
|
||||
*/
|
||||
static pickFields(body, allowFields = HandlerEscortRecord.RECORD_FIELDS, exact = false) {
|
||||
const picked = {};
|
||||
for (const key of Object.keys(body || {})) {
|
||||
const allowed = allowFields.some(
|
||||
(f) => key === f || key.startsWith(f + ".")
|
||||
(f) => key === f || (!exact && key.startsWith(f + "."))
|
||||
);
|
||||
if (allowed) {
|
||||
picked[key] = body[key];
|
||||
@@ -164,7 +200,7 @@ class HandlerEscortRecord {
|
||||
statusArray = status.split(',')
|
||||
}
|
||||
|
||||
if (statusArray && statusArray.some((item) => !Object.hasOwn(HandlerEscortRecord.STATUS_TRANSITIONS, item))) {
|
||||
if (statusArray && statusArray.some((item) => !Object.hasOwn(STATUS_TRANSITIONS, item))) {
|
||||
return ResponseUtil.badRequest(ctx, "订单状态筛选值不正确");
|
||||
}
|
||||
|
||||
@@ -179,7 +215,7 @@ class HandlerEscortRecord {
|
||||
|
||||
return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +237,7 @@ class HandlerEscortRecord {
|
||||
|
||||
return ResponseUtil.success(ctx, { records }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,7 +259,7 @@ class HandlerEscortRecord {
|
||||
|
||||
return ResponseUtil.success(ctx, { record }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,14 +309,13 @@ class HandlerEscortRecord {
|
||||
if (addressResult.error) return ResponseUtil.badRequest(ctx, addressResult.error);
|
||||
|
||||
const payload = HandlerEscortRecord.pickFields(body);
|
||||
// 陪诊员分配由平台决定:用户下单时提交的 attendant 一律丢弃,防止自选/伪造陪诊员
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) delete payload.attendant;
|
||||
payload.userId = userId;
|
||||
// healthProfileId 以校验通过的档案为准,覆盖客户端原值
|
||||
payload.healthProfileId = profile._id;
|
||||
payload.status = "pending";
|
||||
payload.patient = {
|
||||
name: profile.profile?.name || "",
|
||||
mobile: profile.profile?.mobile || "",
|
||||
birth: profile.profile?.birth || "",
|
||||
};
|
||||
if (["male", "female"].includes(profile.profile?.sex)) payload.patient.sex = profile.profile.sex;
|
||||
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
|
||||
payload.escort = {
|
||||
serviceId: service.id,
|
||||
serviceName: service.title,
|
||||
@@ -309,7 +344,7 @@ class HandlerEscortRecord {
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,15 +366,30 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
||||
if (!isAdmin && ["completed", "cancelled"].includes(existing.status)) {
|
||||
// 非管理员的可改字段随订单状态收敛:终态无可改字段,进行中只剩就诊人备注
|
||||
const allowFields = isAdmin
|
||||
? HandlerEscortRecord.RECORD_FIELDS
|
||||
: HandlerEscortRecord.ownerEditableFields(existing.status);
|
||||
if (allowFields.length === 0) {
|
||||
return ResponseUtil.forbidden(ctx, "已结束的订单不可修改");
|
||||
}
|
||||
|
||||
// 非管理员只能改就诊信息类字段,费用/状态/归属/陪诊员分配不可自助修改
|
||||
const allowFields = isAdmin
|
||||
? HandlerEscortRecord.RECORD_FIELDS
|
||||
: HandlerEscortRecord.OWNER_UPDATE_FIELDS;
|
||||
const payload = HandlerEscortRecord.pickFields(update, allowFields);
|
||||
const payload = HandlerEscortRecord.pickFields(update, allowFields, !isAdmin);
|
||||
if (Object.keys(payload).length === 0) {
|
||||
// 例如进行中订单提交医院/排期:字段被状态规则过滤,明确告知而不是静默成功
|
||||
return ResponseUtil.badRequest(ctx, "该订单当前状态不支持修改这些信息");
|
||||
}
|
||||
|
||||
// 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上;
|
||||
// 通过后同步刷新订单里的就诊人快照
|
||||
if (payload.healthProfileId) {
|
||||
const profile = await DBModel.HealthProfile.findProfileById(payload.healthProfileId);
|
||||
if (!profile || String(profile.userId) !== String(existing.userId)) {
|
||||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||||
}
|
||||
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
|
||||
}
|
||||
const service = services.find((item) => item.id === existing.escort?.serviceId);
|
||||
if (!service) return ResponseUtil.badRequest(ctx, "订单关联的服务已下架");
|
||||
|
||||
@@ -352,6 +402,10 @@ class HandlerEscortRecord {
|
||||
for (const key of Object.keys(payload)) {
|
||||
if (key.startsWith("schedule.")) delete payload[key];
|
||||
}
|
||||
// 已支付后的改期留审计时间,便于客服追溯谁在何时改过排期
|
||||
if (existing.status !== "pending") {
|
||||
scheduleResult.schedule.scheduleUpdatedAt = new Date();
|
||||
}
|
||||
payload.schedule = scheduleResult.schedule;
|
||||
}
|
||||
|
||||
@@ -368,7 +422,7 @@ class HandlerEscortRecord {
|
||||
|
||||
return ResponseUtil.success(ctx, { record: updatedRecord }, "更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,7 +450,7 @@ class HandlerEscortRecord {
|
||||
if (!isAdmin && !HandlerEscortRecord.OWNER_ALLOWED_STATUS.includes(status)) {
|
||||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||||
}
|
||||
if (!HandlerEscortRecord.STATUS_TRANSITIONS[existing.status]?.includes(status)) {
|
||||
if (!canTransition(existing.status, status)) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||||
}
|
||||
|
||||
@@ -419,7 +473,7 @@ class HandlerEscortRecord {
|
||||
|
||||
return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,24 +493,38 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权删除该订单");
|
||||
}
|
||||
|
||||
// 与前端口径一致:仅「未支付且未进入服务阶段」的订单可删。
|
||||
// 已支付/进行中/已完成的订单承载服务与费用记录,不能只靠前端隐藏按钮来保护
|
||||
// 删除口径(与产品确认一致):
|
||||
// - 未支付且未进入服务阶段:物理删除,允许用户/管理员清理误建订单;
|
||||
// - 其他(已支付/进行中/已完成):仅管理员可「软删除」,
|
||||
// 状态置为已取消并打 deletedAt 标记,保留费用与服务审计链,列表默认不再展示
|
||||
const paymentStatus = existing.payment?.status || "unpaid";
|
||||
const deletable = paymentStatus === "unpaid"
|
||||
const hardDeletable = paymentStatus === "unpaid"
|
||||
&& ["pending", "confirmed", "cancelled"].includes(existing.status);
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user) && !deletable) {
|
||||
|
||||
if (hardDeletable) {
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
if (!deletedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
return ResponseUtil.success(ctx, { record: deletedRecord }, "删除成功");
|
||||
}
|
||||
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) {
|
||||
return ResponseUtil.forbidden(ctx, "该订单不可删除");
|
||||
}
|
||||
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
|
||||
if (!deletedRecord) {
|
||||
const softDeleted = await DBModel.EscortRecord.updateRecord(id, {
|
||||
status: "cancelled",
|
||||
cancelReason: "平台删除",
|
||||
cancelledAt: new Date(),
|
||||
deletedAt: new Date(),
|
||||
});
|
||||
if (!softDeleted) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { record: deletedRecord }, "删除成功");
|
||||
return ResponseUtil.success(ctx, { record: softDeleted }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+82
-11
@@ -11,6 +11,12 @@ class HandlerHealthProfile {
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
|
||||
// 单个账号可添加的就诊人数量上限
|
||||
static MAX_PROFILES_PER_USER = 20;
|
||||
|
||||
// 手机号:11 位大陆手机号
|
||||
static MOBILE_PATTERN = /^1[3-9]\d{9}$/;
|
||||
|
||||
// 解析分页参数并夹紧上限
|
||||
static parsePaging(query = {}) {
|
||||
const page = Math.max(1, parseInt(query.page) || 1);
|
||||
@@ -19,6 +25,40 @@ class HandlerHealthProfile {
|
||||
return { page, pageSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验就诊人基本信息(只校验请求中出现的字段,未出现的沿用原值)
|
||||
* @param {Object} body 已按白名单挑出的请求体
|
||||
* @param {boolean} requireBase 新增时要求姓名与手机号必填
|
||||
* @returns {string|null} 不合规时返回提示文案
|
||||
*/
|
||||
static validateProfileInput(body, requireBase = false) {
|
||||
const name = body["profile.name"] ?? body.profile?.name;
|
||||
const mobile = body["profile.mobile"] ?? body.profile?.mobile;
|
||||
|
||||
if (requireBase || name !== undefined) {
|
||||
if (!String(name || "").trim()) return "请填写就诊人姓名";
|
||||
}
|
||||
if (requireBase || mobile !== undefined) {
|
||||
const value = String(mobile || "").trim();
|
||||
if (!HandlerHealthProfile.MOBILE_PATTERN.test(value)) return "请填写正确的就诊人手机号";
|
||||
}
|
||||
|
||||
const height = body["health.height"] ?? body.health?.height;
|
||||
if (height !== undefined && (Number(height) < 0 || Number(height) > 300)) {
|
||||
return "身高需在 0-300cm 之间";
|
||||
}
|
||||
const weight = body["health.weight"] ?? body.health?.weight;
|
||||
if (weight !== undefined && (Number(weight) < 0 || Number(weight) > 500)) {
|
||||
return "体重需在 0-500kg 之间";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按白名单挑选字段(支持 "profile.name" 这类点号路径)
|
||||
* @param {Object} body 请求体
|
||||
* @returns {Object}
|
||||
*/
|
||||
static pickFields(body) {
|
||||
const picked = {};
|
||||
for (const key of Object.keys(body || {})) {
|
||||
@@ -32,6 +72,18 @@ class HandlerHealthProfile {
|
||||
return picked;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验失败统一转成 400:schema 校验错误直接抛给前端会暴露字段名与内部实现
|
||||
* @param {Object} ctx Koa 上下文
|
||||
* @param {Error} err 捕获到的异常
|
||||
*/
|
||||
static handleWriteError(ctx, err) {
|
||||
if (err?.name === "ValidationError") {
|
||||
return ResponseUtil.badRequest(ctx, "填写内容不合法,请检查身高、体重、性别等字段");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
|
||||
async getProfiles(ctx) {
|
||||
try {
|
||||
const { userId, name, mobile, sortBy } = ctx.request.query;
|
||||
@@ -48,7 +100,7 @@ class HandlerHealthProfile {
|
||||
|
||||
return ResponseUtil.success(ctx, result, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +122,7 @@ class HandlerHealthProfile {
|
||||
|
||||
return ResponseUtil.success(ctx, result, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +141,7 @@ class HandlerHealthProfile {
|
||||
|
||||
return ResponseUtil.success(ctx, { profile }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,10 +151,24 @@ class HandlerHealthProfile {
|
||||
const body = HandlerHealthProfile.pickFields(ctx.request.body);
|
||||
body.userId = ctx.state.user?._id;
|
||||
|
||||
const invalid = HandlerHealthProfile.validateProfileInput(body, true);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
// 每账号档案数量上限:防止被当作无限存储使用
|
||||
const count = await DBModel.HealthProfile.countDocuments({ userId: body.userId });
|
||||
if (count >= HandlerHealthProfile.MAX_PROFILES_PER_USER) {
|
||||
return ResponseUtil.badRequest(
|
||||
ctx,
|
||||
`最多可添加 ${HandlerHealthProfile.MAX_PROFILES_PER_USER} 位就诊人`
|
||||
);
|
||||
}
|
||||
|
||||
const newProfile = await DBModel.HealthProfile.createProfile(body);
|
||||
return ResponseUtil.success(ctx, { profile: newProfile }, "创建成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return HandlerHealthProfile.handleWriteError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +190,15 @@ class HandlerHealthProfile {
|
||||
const update = HandlerHealthProfile.pickFields(ctx.request.body);
|
||||
delete update.userId; // 不允许通过请求转移档案归属
|
||||
|
||||
const invalid = HandlerHealthProfile.validateProfileInput(update);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const updatedProfile = await DBModel.HealthProfile.updateProfileById(id, update);
|
||||
return ResponseUtil.success(ctx, { profile: updatedProfile }, "更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return HandlerHealthProfile.handleWriteError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,7 +218,7 @@ class HandlerHealthProfile {
|
||||
await DBModel.HealthProfile.deleteProfileById(id);
|
||||
return ResponseUtil.success(ctx, { profile }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +246,7 @@ class HandlerHealthProfile {
|
||||
|
||||
return ResponseUtil.success(ctx, { profile }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +257,7 @@ class HandlerHealthProfile {
|
||||
const newProfile = await DBModel.HealthProfile.createProfile(HandlerHealthProfile.pickFields(body));
|
||||
return ResponseUtil.success(ctx, { profile: newProfile }, "创建成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +277,7 @@ class HandlerHealthProfile {
|
||||
|
||||
return ResponseUtil.success(ctx, { profile: updatedProfile }, "更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,9 +296,9 @@ class HandlerHealthProfile {
|
||||
|
||||
return ResponseUtil.success(ctx, { profile: deletedProfile }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { HandlerHealthProfile };
|
||||
export { HandlerHealthProfile };
|
||||
|
||||
+6
-6
@@ -14,7 +14,7 @@ class HandlerResource {
|
||||
try {
|
||||
return ResponseUtil.success(ctx, { services }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ class HandlerResource {
|
||||
try {
|
||||
return ResponseUtil.success(ctx, { agreement }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ class HandlerResource {
|
||||
try {
|
||||
return ResponseUtil.success(ctx, { hospitalInfo }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ class HandlerResource {
|
||||
try {
|
||||
return ResponseUtil.success(ctx, { hospitalRanking }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ class HandlerResource {
|
||||
try {
|
||||
return ResponseUtil.success(ctx, { departmentRankings }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ class HandlerResource {
|
||||
try {
|
||||
return ResponseUtil.success(ctx, { aiquick_questions }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
|
||||
/**
|
||||
* 进程内速率限制(health 服务的写接口)
|
||||
*
|
||||
* 与 user 服务的限流同构,但有两点差异:
|
||||
* - 键优先用登录 token(已通过 requireAuth),避免多个用户共用同一 NAT 出口 IP 时互相挤占;
|
||||
* - 无 token 时回退到 IP,保证匿名请求也受限。
|
||||
*
|
||||
* 说明:单进程内存计数,多实例部署时每个实例各自计数(当前为单机部署,
|
||||
* 若后续横向扩容需换成 Redis 之类的共享计数)。
|
||||
*/
|
||||
const store = new Map();
|
||||
|
||||
const cleanupTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, record] of store.entries()) {
|
||||
if (now - record.resetAt > record.windowMs) store.delete(key);
|
||||
}
|
||||
}, 60_000);
|
||||
cleanupTimer.unref();
|
||||
|
||||
/**
|
||||
* 创建限流中间件
|
||||
* @param {number} max 窗口内最大请求数
|
||||
* @param {number} windowMs 窗口时长(毫秒)
|
||||
*/
|
||||
function rateLimit(max, windowMs = 60_000) {
|
||||
return async (ctx, next) => {
|
||||
const identity = ctx.state.user?._id ? `u:${ctx.state.user._id}` : `ip:${ctx.ip}`;
|
||||
const key = `${identity}:${ctx.method}:${ctx.path}`;
|
||||
const now = Date.now();
|
||||
|
||||
let record = store.get(key);
|
||||
if (!record || now - record.resetAt > windowMs) {
|
||||
record = { count: 0, resetAt: now, windowMs };
|
||||
store.set(key, record);
|
||||
}
|
||||
|
||||
record.count++;
|
||||
if (record.count > max) {
|
||||
const retryAfter = Math.ceil((record.resetAt + windowMs - now) / 1000);
|
||||
ctx.set("Retry-After", String(retryAfter));
|
||||
return ResponseUtil.error(ctx, "操作过于频繁,请稍后再试", null, 429);
|
||||
}
|
||||
|
||||
ctx.set("X-RateLimit-Limit", String(max));
|
||||
ctx.set("X-RateLimit-Remaining", String(Math.max(0, max - record.count)));
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按用户维度的限流(供 WebSocket 等无 ctx 的场景复用)
|
||||
* @param {string} identity 身份键(通常是 userId)
|
||||
* @param {number} max 窗口内最大次数
|
||||
* @param {number} windowMs 窗口时长(毫秒)
|
||||
* @returns {(identity: string) => {allowed: boolean, retryAfter: number}}
|
||||
*/
|
||||
function createUserLimiter(max, windowMs = 60_000) {
|
||||
const buckets = new Map();
|
||||
|
||||
return (identity) => {
|
||||
const now = Date.now();
|
||||
let record = buckets.get(identity);
|
||||
if (!record || now - record.resetAt > windowMs) {
|
||||
record = { count: 0, resetAt: now };
|
||||
buckets.set(identity, record);
|
||||
}
|
||||
record.count++;
|
||||
if (record.count > max) {
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfter: Math.ceil((record.resetAt + windowMs - now) / 1000),
|
||||
};
|
||||
}
|
||||
return { allowed: true, retryAfter: 0 };
|
||||
};
|
||||
}
|
||||
|
||||
export { rateLimit, createUserLimiter };
|
||||
@@ -153,6 +153,12 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
cancelReason: { type: String, default: "", comment: "订单取消原因" },
|
||||
cancelledAt: { type: Date, default: null, comment: "订单取消时间" },
|
||||
|
||||
/**
|
||||
* 软删除标记:已支付/进行中/已完成的订单不允许物理删除(费用与服务记录需留存审计),
|
||||
* 管理员删除时打此标记,列表与详情默认过滤,历史数据不受影响
|
||||
*/
|
||||
deletedAt: { type: Date, default: null, comment: "软删除时间" },
|
||||
|
||||
/**
|
||||
* 元数据 - 系统管理信息
|
||||
*/
|
||||
@@ -182,9 +188,12 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
|
||||
*/
|
||||
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
const { status, userId, appointmentDate, healthProfileId } = options;
|
||||
const { status, userId, appointmentDate, healthProfileId, includeDeleted = false } = options;
|
||||
const filter = {};
|
||||
|
||||
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
|
||||
if (!includeDeleted) filter.deletedAt = null;
|
||||
|
||||
if (status && Array.isArray(status) && status.length > 0) {
|
||||
filter.status = { $in: status };
|
||||
}
|
||||
@@ -281,20 +290,26 @@ EscortRecordSchema.statics.createRecord = async function (record, cb) {
|
||||
*/
|
||||
EscortRecordSchema.statics.updateRecord = async function (id, update, cb) {
|
||||
const $set = { ...update, "meta.updatetime": Date.now() };
|
||||
return await this.findByIdAndUpdate(id, { $set }, { new: true, runValidators: true }, cb);
|
||||
// 已软删除的订单不可再被修改
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id: id, deletedAt: null },
|
||||
{ $set },
|
||||
{ new: true, runValidators: true },
|
||||
cb
|
||||
);
|
||||
};
|
||||
|
||||
// 状态迁移必须仍以读取时的状态为条件,避免并发请求重复取消或跨过服务阶段。
|
||||
EscortRecordSchema.statics.updateRecordStatus = async function (id, fromStatus, update) {
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id: id, status: fromStatus },
|
||||
{ _id: id, status: fromStatus, deletedAt: null },
|
||||
{ $set: { ...update, "meta.updatetime": Date.now() } },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
};
|
||||
|
||||
EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) {
|
||||
return await this.findOne({ userId, idempotencyKey }).exec();
|
||||
return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -305,7 +320,8 @@ EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempo
|
||||
* @returns {Promise<Object|null>} 陪诊记录,不存在返回null
|
||||
*/
|
||||
EscortRecordSchema.statics.findRecordById = async function (id, cb) {
|
||||
return await this.findById(id).exec(cb);
|
||||
// 软删除的订单按不存在处理
|
||||
return await this.findOne({ _id: id, deletedAt: null }).exec(cb);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -39,8 +39,9 @@ const HealthProfileSchema = mongoose.Schema(
|
||||
|
||||
// 健康信息
|
||||
health: {
|
||||
height: { type: Number, default: 0, comment: "身高(cm)" },
|
||||
weight: { type: Number, default: 0, comment: "体重(kg)" },
|
||||
// 范围校验:0 表示未填写;非法值(负数、超大值)以前会被静默写入并影响下单展示
|
||||
height: { type: Number, min: 0, max: 300, default: 0, comment: "身高(cm)" },
|
||||
weight: { type: Number, min: 0, max: 500, default: 0, comment: "体重(kg)" },
|
||||
bloodType: { type: String, default: "", comment: "血型" },
|
||||
remark: { type: String, default: "", comment: "备注" },
|
||||
},
|
||||
@@ -165,11 +166,13 @@ HealthProfileSchema.statics.createProfile = async function (data) {
|
||||
|
||||
/**
|
||||
* 根据ID更新健康档案(更新姓名时同步拼音字段)
|
||||
* runValidators: 更新时同样校验 schema 约束(性别枚举、身高体重范围),
|
||||
* 否则非法值会绕过校验被静默写入
|
||||
*/
|
||||
HealthProfileSchema.statics.updateProfileById = async function (id, update) {
|
||||
syncPinyinOnUpdate(update);
|
||||
update["meta.updatetime"] = Date.now();
|
||||
return await this.findByIdAndUpdate(id, { $set: update }, { new: true }).exec();
|
||||
return await this.findByIdAndUpdate(id, { $set: update }, { new: true, runValidators: true }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -178,7 +181,7 @@ HealthProfileSchema.statics.updateProfileById = async function (id, update) {
|
||||
HealthProfileSchema.statics.updateProfile = async function (userId, update) {
|
||||
syncPinyinOnUpdate(update);
|
||||
update["meta.updatetime"] = Date.now();
|
||||
return await this.findOneAndUpdate({ userId }, { $set: update }, { new: true }).exec();
|
||||
return await this.findOneAndUpdate({ userId }, { $set: update }, { new: true, runValidators: true }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+2
-1
@@ -6,7 +6,8 @@
|
||||
"main": "app.js",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"dev": "nodemon index.js"
|
||||
"dev": "nodemon index.js",
|
||||
"test": "node --test test/*.test.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@langchain/anthropic": "^1.5.9",
|
||||
|
||||
+16
-5438
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+29
-11
@@ -5,19 +5,37 @@ import { HandlerResource } from "../handler/resource.js";
|
||||
import { HandlerEmployee } from "../handler/employee.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import { getUserByToken } from "../utils/user_service.js";
|
||||
import { isAdmin } from "../utils/permissions.js";
|
||||
import { rateLimit } from "../middleware/ratelimit.js";
|
||||
|
||||
// 写接口限流:下单最容易造成脏数据与费用纠纷,给最紧的额度;
|
||||
// 修改/取消次之;查询不限制(列表页会轮询刷新)
|
||||
const createLimit = rateLimit(5);
|
||||
const updateLimit = rateLimit(20);
|
||||
const deleteLimit = rateLimit(10);
|
||||
|
||||
/**
|
||||
* 鉴权中间件:校验 token 并将用户信息挂到 ctx.state.user
|
||||
* token→user 结果带 5 分钟进程内缓存(见 utils/user_service.js)
|
||||
*
|
||||
* token 只从请求头读取:曾支持 ?token= 传参,但 access log 会原样记录 URL,
|
||||
* 等于把登录凭证写进日志。另兼容 "Bearer xxx" 头格式,与 user 服务口径一致。
|
||||
*/
|
||||
async function requireAuth(ctx, next) {
|
||||
const token = ctx.header["token"] || ctx.header["authorization"] || ctx.request.query?.token;
|
||||
const raw = ctx.header["token"] || ctx.header["authorization"];
|
||||
const token = raw ? String(raw).replace(/^Bearer\s+/i, "").trim() : "";
|
||||
if (!token) {
|
||||
ResponseUtil.unauthorized(ctx, "缺少token");
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await getUserByToken(token);
|
||||
let user;
|
||||
try {
|
||||
user = await getUserByToken(token, { strict: true });
|
||||
} catch (err) {
|
||||
// 用户服务故障不等于登录失效:区分开才能让前端提示「稍后重试」而不是踢回登录
|
||||
return ResponseUtil.error(ctx, "服务暂不可用,请稍后重试", null, 503);
|
||||
}
|
||||
if (!user) {
|
||||
ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
return;
|
||||
@@ -28,11 +46,11 @@ async function requireAuth(ctx, next) {
|
||||
|
||||
/**
|
||||
* 管理员校验中间件:仅管理端小程序绑定的账号可访问管理端接口
|
||||
* 与 WS 管理端 agent 的校验口径保持一致(app 中是否存在 wxapp-escort-admin)
|
||||
* 与 WS 管理端 agent、订单 handler 共用 utils/permissions.js 的同一口径
|
||||
*/
|
||||
async function requireAdmin(ctx, next) {
|
||||
const user = ctx.state.user;
|
||||
if (!user || !user.app || !("wxapp-escort-admin" in user.app)) {
|
||||
if (!isAdmin(user)) {
|
||||
ResponseUtil.forbidden(ctx, "无管理员权限");
|
||||
return;
|
||||
}
|
||||
@@ -62,17 +80,17 @@ function registerRoutes(app) {
|
||||
// 全量查询属管理端能力,必须管理员
|
||||
router.get("/escort-record", requireAuth, requireAdmin, handlerEscortRecord.getRecords.bind(handlerEscortRecord));
|
||||
router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord));
|
||||
router.post("/escort-record", requireAuth, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
|
||||
router.put("/escort-record/:id", requireAuth, handlerEscortRecord.updateRecord.bind(handlerEscortRecord));
|
||||
router.patch("/escort-record/:id/status", requireAuth, handlerEscortRecord.updateStatus.bind(handlerEscortRecord));
|
||||
router.delete("/escort-record/:id", requireAuth, handlerEscortRecord.deleteRecord.bind(handlerEscortRecord));
|
||||
router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
|
||||
router.put("/escort-record/:id", requireAuth, updateLimit, handlerEscortRecord.updateRecord.bind(handlerEscortRecord));
|
||||
router.patch("/escort-record/:id/status", requireAuth, updateLimit, handlerEscortRecord.updateStatus.bind(handlerEscortRecord));
|
||||
router.delete("/escort-record/:id", requireAuth, deleteLimit, handlerEscortRecord.deleteRecord.bind(handlerEscortRecord));
|
||||
|
||||
// C 端"我的健康档案":userId 一律取自 token,必须注册在 /health-profile/:id 之前
|
||||
router.get("/health-profile/mine", requireAuth, handlerHealthProfile.getMyProfiles.bind(handlerHealthProfile));
|
||||
router.post("/health-profile/mine", requireAuth, handlerHealthProfile.createMyProfile.bind(handlerHealthProfile));
|
||||
router.post("/health-profile/mine", requireAuth, createLimit, handlerHealthProfile.createMyProfile.bind(handlerHealthProfile));
|
||||
router.get("/health-profile/mine/:id", requireAuth, handlerHealthProfile.getMyProfileById.bind(handlerHealthProfile));
|
||||
router.put("/health-profile/mine/:id", requireAuth, handlerHealthProfile.updateMyProfile.bind(handlerHealthProfile));
|
||||
router.delete("/health-profile/mine/:id", requireAuth, handlerHealthProfile.deleteMyProfile.bind(handlerHealthProfile));
|
||||
router.put("/health-profile/mine/:id", requireAuth, updateLimit, handlerHealthProfile.updateMyProfile.bind(handlerHealthProfile));
|
||||
router.delete("/health-profile/mine/:id", requireAuth, deleteLimit, handlerHealthProfile.deleteMyProfile.bind(handlerHealthProfile));
|
||||
|
||||
// 以下为管理端档案接口(C 端一律走 /mine),必须管理员
|
||||
router.get("/health-profile", requireAuth, requireAdmin, handlerHealthProfile.getProfiles.bind(handlerHealthProfile));
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js";
|
||||
import { isAdmin } from "../utils/permissions.js";
|
||||
import { escapeRegex } from "../agent/infra/tools/db/utils.js";
|
||||
import {
|
||||
checkUrlAllowed,
|
||||
isPrivateAddress,
|
||||
} from "../agent/infra/tools/web/url_guard.js";
|
||||
import { clampTimeout } from "../agent/infra/tools/web/http_client.js";
|
||||
|
||||
test("订单状态机只允许正向流转", () => {
|
||||
assert.equal(canTransition("pending", "confirmed"), true);
|
||||
assert.equal(canTransition("confirmed", "in_progress"), true);
|
||||
assert.equal(canTransition("in_progress", "completed"), true);
|
||||
assert.equal(canTransition("pending", "cancelled"), true);
|
||||
|
||||
// 终态不可回退,也不能跳步
|
||||
assert.equal(canTransition("completed", "in_progress"), false);
|
||||
assert.equal(canTransition("cancelled", "pending"), false);
|
||||
assert.equal(canTransition("pending", "completed"), false);
|
||||
// 未知状态一律拒绝
|
||||
assert.equal(canTransition("unknown", "pending"), false);
|
||||
});
|
||||
|
||||
test("管理端身份要求显式 role=admin", () => {
|
||||
assert.equal(isAdmin(null), false);
|
||||
assert.equal(isAdmin({}), false);
|
||||
assert.equal(isAdmin({ app: { "wxapp-escort-admin": { role: ["admin"] } } }), true);
|
||||
assert.equal(isAdmin({ app: { "wxapp-escort-admin": { role: "admin" } } }), true);
|
||||
assert.equal(isAdmin({ app: { "wxapp-escort-admin": { role: ["user"] } } }), false);
|
||||
});
|
||||
|
||||
test("关键词按字面量转义并截断", () => {
|
||||
assert.equal(escapeRegex("张三"), "张三");
|
||||
assert.equal(escapeRegex("(a+)+$"), "\\(a\\+\\)\\+\\$");
|
||||
assert.equal(escapeRegex("a".repeat(100)).length, 64);
|
||||
assert.equal(escapeRegex(null), "");
|
||||
});
|
||||
|
||||
test("SSRF 校验拦截内网、环回与云元数据地址", () => {
|
||||
const blocked = [
|
||||
"http://127.0.0.1/",
|
||||
"http://10.1.2.3/",
|
||||
"http://169.254.169.254/latest/meta-data/",
|
||||
"http://192.168.1.1/",
|
||||
"http://localhost:8080/",
|
||||
"http://[::1]/",
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.com/",
|
||||
];
|
||||
for (const url of blocked) {
|
||||
assert.notEqual(checkUrlAllowed(url), null, url);
|
||||
}
|
||||
assert.equal(checkUrlAllowed("https://www.baidu.com"), null);
|
||||
assert.equal(checkUrlAllowed("not a url"), "Invalid URL: not a url");
|
||||
});
|
||||
|
||||
test("内网地址判定覆盖 IPv4 映射与链路本地", () => {
|
||||
assert.equal(isPrivateAddress("127.0.0.1"), true);
|
||||
assert.equal(isPrivateAddress("8.8.8.8"), false);
|
||||
assert.equal(isPrivateAddress("fe80::1"), true);
|
||||
assert.equal(isPrivateAddress("::ffff:10.0.0.1"), true);
|
||||
});
|
||||
|
||||
test("出网超时被夹紧在 1s-15s", () => {
|
||||
assert.equal(clampTimeout(undefined), 15000);
|
||||
assert.equal(clampTimeout(0), 15000);
|
||||
assert.equal(clampTimeout("abc"), 15000);
|
||||
assert.equal(clampTimeout(600000), 15000);
|
||||
assert.equal(clampTimeout(300), 1000);
|
||||
assert.equal(clampTimeout(5000), 5000);
|
||||
});
|
||||
|
||||
test("状态机表覆盖全部订单状态", () => {
|
||||
assert.deepEqual(
|
||||
Object.keys(STATUS_TRANSITIONS).sort(),
|
||||
["cancelled", "completed", "confirmed", "in_progress", "pending"]
|
||||
);
|
||||
});
|
||||
@@ -1,135 +0,0 @@
|
||||
"use strict";
|
||||
|
||||
import crypto from "crypto"
|
||||
import logger from './logger.js'
|
||||
|
||||
function AuthToken() {
|
||||
}
|
||||
|
||||
AuthToken.prototype.init = function (redisdb, defaultExpiresSeconds) {
|
||||
this.tokenDB = redisdb;
|
||||
this.defaultExpiresSeconds = defaultExpiresSeconds;
|
||||
}
|
||||
|
||||
AuthToken.prototype.gen = async function (uid, tokenOld) {
|
||||
let userToken = tokenOld;
|
||||
|
||||
try {
|
||||
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
|
||||
return JSON.parse(data);
|
||||
});
|
||||
if (!tokenData) {
|
||||
if (!userToken || userToken.length <= 16) {
|
||||
let hash = crypto.createHash("md5");
|
||||
hash.update(uid + Date() + Math.random());
|
||||
userToken = hash.digest("hex");
|
||||
}
|
||||
|
||||
tokenData = {
|
||||
uid,
|
||||
token: userToken,
|
||||
ts: Math.floor(Date.now() / 1000),
|
||||
ttl: this.defaultExpiresSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
this.tokenDB.set(userToken, JSON.stringify(tokenData), "EX", this.defaultExpiresSeconds);
|
||||
} catch (err) {
|
||||
logger.error('生成Token失败:', { error: err.message, uid, stack: err.stack });
|
||||
}
|
||||
|
||||
return userToken;
|
||||
};
|
||||
|
||||
AuthToken.prototype.update = async function (userToken) {
|
||||
try {
|
||||
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
|
||||
return JSON.parse(data);
|
||||
});
|
||||
|
||||
if (tokenData) {
|
||||
this.tokenDB.set(userToken, JSON.stringify(tokenData), "EX", this.defaultExpiresSeconds);
|
||||
return tokenData;
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('更新Token失败:', { error: err.message, stack: err.stack });
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
AuthToken.prototype.del = async function (userToken) {
|
||||
let tokenData = await this.tokenDB.get(userToken).then(function (data) {
|
||||
return JSON.parse(data);
|
||||
});
|
||||
|
||||
if (tokenData) {
|
||||
this.tokenDB.del(userToken);
|
||||
}
|
||||
|
||||
return tokenData;
|
||||
};
|
||||
|
||||
AuthToken.prototype.check = async function (userToken, updateExpire = true) {
|
||||
try {
|
||||
if (updateExpire) {
|
||||
if (await this.tokenDB.expire(userToken, this.defaultExpiresSeconds) >= 1) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (await this.tokenDB.exists([userToken]) >= 1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('检查Token失败:', { error: err.message, userToken, stack: err.stack });
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
AuthToken.prototype.get = async function (token) {
|
||||
let tokenData = await this.tokenDB.get(token).then(function (data) {
|
||||
return JSON.parse(data);
|
||||
});
|
||||
|
||||
if (!tokenData) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return tokenData;
|
||||
};
|
||||
|
||||
AuthToken.prototype.koaRequest = async function (ctx, next) {
|
||||
try {
|
||||
let token = ctx.request.body.token;
|
||||
|
||||
if (!token) token = ctx.request.query.token;
|
||||
if (!token) token = ctx.header["authorization"];
|
||||
if (!token) token = ctx.header["token"];
|
||||
|
||||
if (!token) {
|
||||
throw new Error("Need token param.");
|
||||
}
|
||||
|
||||
let ret = await this.check(token);
|
||||
if (!ret) {
|
||||
throw new Error("User not login in.");
|
||||
}
|
||||
|
||||
let tokenData = await this.get(token);
|
||||
if (tokenData && tokenData.uid) {
|
||||
// 用户体系在外部服务(user 服务),tokenData 中已包含 uid
|
||||
ctx.userInfo = tokenData;
|
||||
}
|
||||
|
||||
ctx.authToken = this;
|
||||
|
||||
return next();
|
||||
} catch (err) {
|
||||
logger.error('身份验证失败:', { error: err.message, token: ctx.request.body.token || ctx.request.query.token || ctx.header["authorization"] || ctx.header["token"], stack: err.stack });
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
const Token = new AuthToken()
|
||||
export { Token }
|
||||
@@ -1,13 +0,0 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
const SALT_ROUNDS = 10;
|
||||
|
||||
function hash(text) {
|
||||
return bcrypt.hash(text, SALT_ROUNDS);
|
||||
}
|
||||
|
||||
function compare(text, hash) {
|
||||
return bcrypt.compare(text, hash);
|
||||
}
|
||||
|
||||
export default { hash, compare }
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 管理端身份判定:路由中间件、订单 handler、WebSocket 入口共用同一口径。
|
||||
*
|
||||
* 为什么不再用「app 里存在 wxapp-escort-admin 键」:
|
||||
* 该键历史上可由 /user/register 的客户端入参写入,任何人都能据此自封管理员。
|
||||
* 现在注册侧已拒绝客户端写 app,但库里可能残留历史账号,
|
||||
* 因此要求显式 role === 'admin';role 缺失的历史账号暂按管理员放行并打告警,
|
||||
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
|
||||
*/
|
||||
function isAdmin(user) {
|
||||
const entry = user?.app?.["wxapp-escort-admin"];
|
||||
if (!entry) return false;
|
||||
|
||||
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
|
||||
if (roles.includes("admin")) return true;
|
||||
|
||||
if (entry.role === undefined) {
|
||||
console.warn(
|
||||
"[permissions] 管理员账号缺少 role 字段,请补齐 app.wxapp-escort-admin.role = ['admin']"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export { isAdmin };
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 陪诊订单状态机(HTTP 接口与管理端 Agent 工具共用同一份规则)
|
||||
*
|
||||
* 之前 Agent 的 escort_record_set 直接改 status,绕过了接口层的迁移校验,
|
||||
* 可以把已完成订单改回进行中。规则集中在这里,任何入口都必须走 canTransition。
|
||||
*/
|
||||
|
||||
// 允许的状态迁移;终态不可再变
|
||||
const STATUS_TRANSITIONS = {
|
||||
pending: ["confirmed", "cancelled"],
|
||||
confirmed: ["in_progress", "cancelled"],
|
||||
in_progress: ["completed"],
|
||||
completed: [],
|
||||
cancelled: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断状态迁移是否允许
|
||||
* @param {string} from 当前状态
|
||||
* @param {string} to 目标状态
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function canTransition(from, to) {
|
||||
return (STATUS_TRANSITIONS[from] || []).includes(to);
|
||||
}
|
||||
|
||||
export { STATUS_TRANSITIONS, canTransition };
|
||||
+19
-3
@@ -1,6 +1,11 @@
|
||||
import logger from "./logger.js";
|
||||
|
||||
/**
|
||||
* 响应工具类
|
||||
* 提供统一的响应格式
|
||||
*
|
||||
* 约定(与小程序端保持一致):业务状态一律走 body.code,HTTP 状态码固定 200;
|
||||
* 同时把 code 写进 X-Biz-Code 响应头,便于 nginx/监控按业务码告警而不必解析响应体。
|
||||
*/
|
||||
class ResponseUtil {
|
||||
/**
|
||||
@@ -11,6 +16,7 @@ class ResponseUtil {
|
||||
*/
|
||||
static success(ctx, data, message = '操作成功') {
|
||||
ctx.status = 200;
|
||||
ctx.set('X-Biz-Code', '0');
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
msg: message,
|
||||
@@ -28,6 +34,7 @@ class ResponseUtil {
|
||||
static error(ctx, message, data = null, errorCode = 500) {
|
||||
// 根据规则,只要进入controller,http状态码都是200
|
||||
ctx.status = 200;
|
||||
ctx.set('X-Biz-Code', String(errorCode));
|
||||
ctx.body = {
|
||||
code: errorCode,
|
||||
msg: message,
|
||||
@@ -74,11 +81,20 @@ class ResponseUtil {
|
||||
|
||||
/**
|
||||
* 服务器内部错误响应
|
||||
*
|
||||
* 详细原因只进日志:err.message 可能包含 Mongo 连接串、字段名、堆栈等内部信息,
|
||||
* 直接回传等于把服务端实现细节暴露给前端/攻击者。
|
||||
*
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
* @param {string|Error} detail - 内部错误详情(仅用于日志)
|
||||
* @param {Object} data - 附加数据
|
||||
*/
|
||||
static internalError(ctx, message = '服务器内部错误', data = null) {
|
||||
return ResponseUtil.error(ctx, message, data, 500);
|
||||
static internalError(ctx, detail = null, data = null) {
|
||||
if (detail) {
|
||||
const text = detail instanceof Error ? detail.stack : String(detail);
|
||||
logger.error(`[internal] ${ctx.method} ${ctx.path}: ${text}`);
|
||||
}
|
||||
return ResponseUtil.error(ctx, '服务器繁忙,请稍后重试', data, 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-1
@@ -4,6 +4,7 @@ const USER_SERVICE_URL = process.env.USER_SERVICE_URL || "http://127.0.0.1:9010"
|
||||
const CACHE_TTL = 5 * 60 * 1000; // 成功结果缓存 5 分钟
|
||||
const NEGATIVE_TTL = 60 * 1000; // 无效 token 短缓存,防止打爆 user 服务
|
||||
const MAX_CACHE_SIZE = 2000;
|
||||
const LOOKUP_TIMEOUT = 5000; // user 服务偶发无响应时不能拖住 health 的全部请求
|
||||
|
||||
// key -> { user, expiresAt },Map 按插入序实现简易 LRU
|
||||
const cache = new Map();
|
||||
@@ -33,6 +34,7 @@ async function lookup(body) {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
|
||||
});
|
||||
const data = await res.json();
|
||||
return data?.data?.user || null;
|
||||
@@ -48,9 +50,12 @@ async function lookup(body) {
|
||||
* 故不存在 userId 兜底,避免凭 userId 冒充他人身份。
|
||||
*
|
||||
* @param {string} token 登录 token
|
||||
* @param {Object} [options]
|
||||
* @param {boolean} [options.strict] 严格模式:user 服务不可用时不返回 null,
|
||||
* 而是抛出 code = USER_SERVICE_UNAVAILABLE 的错误,供接口区分「登录失效」与「服务故障」
|
||||
* @returns {Promise<Object|null>} 用户信息或 null
|
||||
*/
|
||||
export async function getUserByToken(token) {
|
||||
export async function getUserByToken(token, options = {}) {
|
||||
if (!token) return null;
|
||||
|
||||
const key = `tk:${token}`;
|
||||
@@ -68,6 +73,11 @@ export async function getUserByToken(token) {
|
||||
} catch (err) {
|
||||
// 网络异常不缓存,避免把故障期内的问题固化 5 分钟
|
||||
console.error("getUserByToken error:", err.message);
|
||||
if (options.strict) {
|
||||
const unavailable = new Error("用户服务暂不可用");
|
||||
unavailable.code = "USER_SERVICE_UNAVAILABLE";
|
||||
throw unavailable;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
+29
-2
@@ -4,9 +4,16 @@ import { DBModel } from "./models/index.js";
|
||||
import { chatTask } from "./agent/bots/bot-escort/task.js";
|
||||
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
|
||||
import { getUserByToken } from "./utils/user_service.js";
|
||||
import { isAdmin } from "./utils/permissions.js";
|
||||
import { createUserLimiter } from "./middleware/ratelimit.js";
|
||||
|
||||
let systemMessageSequence = 0;
|
||||
|
||||
// 单连接上行帧上限:超限会被 ws 直接断开,避免超大 JSON 占用内存与 CPU
|
||||
const MAX_PAYLOAD_BYTES = 256 * 1024;
|
||||
// 单用户聊天频次限制:AI 调用有成本,且同一用户的会话本就串行处理
|
||||
const chatLimiter = createUserLimiter(20);
|
||||
|
||||
// 所有下行帧保持同一结构,调用方无需按消息类型猜测字段。
|
||||
const sendFrame = (ws, source, type, content = '', id = '') => {
|
||||
if (ws.readyState !== WebSocket.OPEN) return;
|
||||
@@ -33,6 +40,7 @@ export default class WebSocketServerManager {
|
||||
|
||||
this.wss = new WebSocketServer({
|
||||
server: this.server,
|
||||
maxPayload: MAX_PAYLOAD_BYTES,
|
||||
perMessageDeflate: {
|
||||
zlibDeflateOptions: {
|
||||
chunkSize: 1024,
|
||||
@@ -70,9 +78,18 @@ export default class WebSocketServerManager {
|
||||
_handleChatConnection(ws) {
|
||||
sendFrame(ws, 'system', 'connected', 'Connected to chat server');
|
||||
|
||||
ws.on('message', (data) => this._handleMessage(ws, data));
|
||||
// 同一连接的消息串行处理:agent 的 messages 数组是共享状态,
|
||||
// 并发跑同一个 agent 会让上下文交错、回复错乱
|
||||
ws.messageQueue = Promise.resolve();
|
||||
ws.on('message', (data) => {
|
||||
ws.messageQueue = ws.messageQueue
|
||||
.then(() => this._handleMessage(ws, data))
|
||||
.catch((err) => console.error('WebSocket message handling error:', err));
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
// 断开后释放队列引用,避免连接对象被闭包长期持有
|
||||
ws.messageQueue = null;
|
||||
console.log('Chat client disconnected');
|
||||
});
|
||||
|
||||
@@ -113,9 +130,19 @@ export default class WebSocketServerManager {
|
||||
send('system', 'error', '请先登录', msg.id);
|
||||
return;
|
||||
}
|
||||
|
||||
// 频次限制按用户维度:防止单账号刷 AI 调用(同一账号多连接共享额度)
|
||||
if (msg.type === 'chat') {
|
||||
const limit = chatLimiter(String(userInfo._id));
|
||||
if (!limit.allowed) {
|
||||
send('system', 'error', `操作过于频繁,请 ${limit.retryAfter} 秒后重试`, msg.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.agent === 'escort-admin') {
|
||||
// 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权
|
||||
if (!userInfo.app || !("wxapp-escort-admin" in userInfo.app)) {
|
||||
if (!isAdmin(userInfo)) {
|
||||
send('system', 'error', '无管理员权限', msg.id);
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user