const { Controller, } = require('egg'); const fs = require('fs').promises; const path = require('path'); function escapeHtml(value) { return String(value || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } /** * 清洗 window 标签使用的跳转地址,避免注入危险协议或控制字符。 * @param {string} value 待清洗的地址。 * @return {string} 允许使用的地址,非法时返回空字符串。 */ function sanitizeWindowHref(value) { const href = String(value || '').trim(); if (!href) { return ''; } const hasControlCharacter = Array.from(href).some(character => { const code = character.charCodeAt(0); return code <= 0x1f || code === 0x7f; }); if (hasControlCharacter || /^(javascript|data|vbscript):/i.test(href)) { return ''; } return href; } /** * 从 window 标签属性中提取跳转地址。 * @param {string} attributeText 标签属性文本。 * @return {string} 提取到的地址,未找到时返回空字符串。 */ function extractWindowHref(attributeText) { const attributes = String(attributeText || ''); const match = attributes.match(/(?:href|data-href|data-window-href)\s*=\s*("([^"]*)"|'([^']*)')/i); if (!match) { return ''; } return match[2] || match[3] || ''; } /** * 渲染可点击的 window 自定义元素。 * @param {string} label 元素展示文案。 * @param {string} href 点击后打开的地址。 * @param {string} [className] 额外样式类名。 * @return {string} 生成的 HTML 片段。 */ function renderWindowElement(label, href, className = '') { const safeHref = sanitizeWindowHref(href); const safeLabel = escapeHtml(label || safeHref); if (!safeHref) { return safeLabel; } const classes = [ 'window-link' ]; if (className) { classes.push(className); } return `${safeLabel}`; } /** * 将文本中的 标签安全渲染为可点击元素。 * @param {string} value 原始文本。 * @return {string} 处理后的 HTML。 */ function renderTextWithWindowTags(value) { const text = String(value || ''); if (!text.includes(']*)>([\s\S]*?)<\/window>/gi; let lastIndex = 0; let rendered = ''; let match; while ((match = pattern.exec(text)) !== null) { rendered += escapeHtml(text.slice(lastIndex, match.index)); const attributes = match[1] || ''; const content = match[2] || ''; const href = sanitizeWindowHref(extractWindowHref(attributes) || content.trim()); const label = content.trim() || href; rendered += renderWindowElement(label, href); lastIndex = pattern.lastIndex; } rendered += escapeHtml(text.slice(lastIndex)); return rendered; } function toArray(value) { return Array.isArray(value) ? value : []; } function slugify(value) { return String(value || '') .toLowerCase() .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-') .replace(/(^-|-$)/g, ''); } function isValidDocName(docName) { return /^[a-zA-Z0-9_-]+$/.test(docName || ''); } function getDocFilePath(app, docName) { return path.join(app.baseDir, 'methods', `${docName}.json`); } function getDocChangesFilePath(app, docName) { return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`); } /** * 获取 docs 目录的绝对路径。 * @param {Egg.Application} app Egg 应用实例。 * @return {string} docs 根目录绝对路径。 */ function getDocsRootPath(app) { return path.resolve(app.baseDir, 'docs'); } /** * 递归解码 URL 路径片段,尽量还原编码穿越路径。 * @param {string} input 待解码的路径片段。 * @return {string|null} 解码后的路径片段,解码失败时返回 null。 */ function decodeDocsPath(input) { let value = String(input || '').trim(); if (!value) { return ''; } for (let index = 0; index < 3; index += 1) { try { const decoded = decodeURIComponent(value); if (decoded === value) { break; } value = decoded; } catch (error) { return null; } } return value; } /** * 将 docs 相对路径转换为可访问 URL。 * @param {string} relativePath docs 相对路径。 * @return {string} 可直接用于 href 的路径。 */ function toDocsHref(relativePath) { return String(relativePath || '') .split(/[\\/]+/) .filter(Boolean) .map(segment => encodeURIComponent(segment)) .join('/'); } /** * 按扩展名返回 docs 文件的响应类型。 * @param {string} filePath 文件绝对路径。 * @return {string} Content-Type 值。 */ function getDocsContentType(filePath) { const ext = path.extname(filePath).toLowerCase(); if (ext === '.md' || ext === '.markdown') { return 'text/markdown; charset=utf-8'; } if (ext === '.json') { return 'application/json; charset=utf-8'; } return 'text/plain; charset=utf-8'; } /** * 解析并校验 docs 文件路径,阻止路径穿越。 * @param {Egg.Application} app Egg 应用实例。 * @param {string} relativePath docs 相对路径。 * @return {{ ok: boolean, filePath?: string, relativePath?: string, message?: string }} 解析结果。 */ function resolveDocsFilePath(app, relativePath) { const decodedPath = decodeDocsPath(relativePath); if (decodedPath === null || !decodedPath) { return { ok: false, message: '无效文档路径', }; } if (decodedPath.includes('\\') || path.isAbsolute(decodedPath)) { return { ok: false, message: '无效文档路径', }; } const docsRootPath = getDocsRootPath(app); const filePath = path.resolve(docsRootPath, decodedPath); const relativeToRoot = path.relative(docsRootPath, filePath); if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) { return { ok: false, message: '路径越界', }; } return { ok: true, filePath, relativePath: decodedPath, }; } /** * 递归收集 docs 目录下的所有文件。 * @param {string} dirPath 当前扫描目录。 * @param {string} baseDir docs 根目录。 * @return {Promise>} 文件列表。 */ async function collectDocsFiles(dirPath, baseDir) { const entries = await fs.readdir(dirPath, { withFileTypes: true }); const files = []; for (const entry of entries) { const entryPath = path.join(dirPath, entry.name); if (entry.isDirectory()) { const nestedFiles = await collectDocsFiles(entryPath, baseDir); files.push(...nestedFiles); continue; } if (entry.isFile()) { files.push({ relativePath: path.relative(baseDir, entryPath), filePath: entryPath, }); } } return files; } /** * 生成 docs 索引页 HTML。 * @param {Array<{ relativePath: string }>} files docs 文件列表。 * @return {string} HTML 文档。 */ function renderDocsIndexPage(files) { const listHtml = files.length ? files.map(file => { const href = `/docs/${toDocsHref(file.relativePath)}`; return `
  • ${renderWindowElement(file.relativePath, href, 'doc-file-link')}
  • `; }).join('') : '
  • docs 目录下暂无文件
  • '; return ` Docs 索引

    docs 目录索引

    以下文件来自 docs 根目录,点击即可直接查看对应内容。

      ${listHtml}
    `; } /** * 生成 docs 文件内容响应。 * @param {Egg.Context} ctx 当前请求上下文。 * @param {string} filePath 文件绝对路径。 * @return {Promise} 无返回值。 */ async function sendDocsFile(ctx, filePath) { const content = await fs.readFile(filePath, 'utf8'); ctx.set('Content-Type', getDocsContentType(filePath)); ctx.body = content; } function normalizeGroups(docData) { if (docData && docData.methods && Array.isArray(docData.methods.groups)) { return docData.methods.groups.map(group => ({ groupName: group.groupName || group.module || 'Default', module: group.module || '', list: toArray(group.list), })); } if (docData && Array.isArray(docData.endpoints)) { return [{ groupName: docData.groupName || 'Endpoints', module: docData.module || '', list: docData.endpoints, }]; } return []; } /** * 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。 * @param {object} docData 文档 JSON 数据。 * @return {string} 统一入口路径。 */ function resolveDocEntryPath(docData) { const httpPath = String(docData?.http?.path || '').trim(); if (httpPath.startsWith('/')) { return httpPath; } if (docData?.module === 'qimen') { return '/qimen'; } if (docData?.module === 'gateway') { return '/internal/v1/gateway'; } return '/system'; } /** * 渲染键值表格。 * @param {Array} items 数据项列表。 * @param {{ name: string, type: string, required: string, description: string }} keyMap 字段映射。 * @return {string} 表格行 HTML。 */ function renderKeyValueRows(items, keyMap) { if (!items.length) { return '暂无数据'; } return items.map(item => { return ` ${escapeHtml(item[keyMap.name] || '')} ${escapeHtml(item[keyMap.type] || '')} ${item[keyMap.required] ? '是' : '否'} ${renderTextWithWindowTags(item[keyMap.description] || '')} `; }).join(''); } /** * 渲染全局 Header 控件区域。 * @param {Array} globalHeaders 全局 Header 定义。 * @return {string} HTML 片段。 */ function renderGlobalHeadersControls(globalHeaders) { const headers = toArray(globalHeaders); if (!headers.length) { return '

    当前文档未定义额外全局 Header

    '; } return `
    ${headers.map(item => { const name = item.name || ''; const type = item.type || 'string'; const required = !!item.required; const description = item.description || ''; const options = toArray(item.list); const field = options.length ? `` : ``; return ``; }).join('')}
    `; } /** * 渲染单个接口卡片。 * @param {object} item 接口定义。 * @param {string} entryPath 统一入口路径。 * @param {string} moduleName 文档所属模块名。 * @return {string} HTML 片段。 */ function renderMethodCard(item, entryPath, moduleName) { const headers = toArray(item.headers); const params = toArray(item.params); const response = toArray(item.response); const errors = toArray(item.errors); const methodName = item.method || item.name || 'unknown'; const description = item.description || ''; const isQimen = moduleName === 'qimen'; const isOpenapi = moduleName === 'openapi'; const isWarehouse = moduleName === 'warehouse'; const isExternalApi = isOpenapi || isWarehouse; const queryHint = isQimen ? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000' : isExternalApi ? `app_key=&method=${methodName}&v=1.0×tamp=1700000000` : `method=${methodName}&v=1.0×tamp=1700000000`; const queryLabel = isExternalApi ? 'Query 参数(自动生成)' : 'Query 参数'; const queryReadonlyAttr = isExternalApi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : ''; return `

    ${escapeHtml(methodName)}

    ${renderTextWithWindowTags(description)}

    入口: ${escapeHtml(entryPath)} 鉴权: ${item.isNeedAuth ? '是' : '否'} 登录: ${item.isNeedLogin ? '是' : '否'}
    Headers (${headers.length}) ${renderKeyValueRows(headers, { name: 'name', type: 'type', required: 'required', description: 'description', })}
    名称类型必填说明
    Params (${params.length}) ${renderKeyValueRows(params, { name: 'name', type: 'type', required: 'required', description: 'description', })}
    名称类型必填说明
    Response (${response.length}) ${renderKeyValueRows(response, { name: 'name', type: 'type', required: 'required', description: 'description', })}
    名称类型必填说明
    Errors (${errors.length}) ${renderKeyValueRows(errors, { name: 'code', type: 'type', required: 'required', description: 'message', })}
    名称类型必填说明
    在线调试
    ${isExternalApi ? ` ` : ''}
    ${item.isNeedLogin ? '该接口需要登录,未设置 Token 将阻止请求' : '该接口无需登录,可不设置 Token 直接调试'}
    点击发送后显示响应
    `; } /** * 渲染 API 文档页面。 * @param {{ docName: string, docData: object, groups: Array, docs: Array, entryPath: string }} options 渲染参数。 * @return {string} HTML 文档。 */ function renderHtmlPage({ docName, docData, groups, docs, entryPath, }) { const isOpenapi = docData.module === 'openapi'; const isWarehouse = docData.module === 'warehouse'; const isExternalApi = isOpenapi || isWarehouse; const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse').map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; }).join(''); const sidebarHtml = groups.map((group, index) => { const list = toArray(group.list); const groupKey = slugify(group.module || group.groupName || `group-${index}`) || `group-${index}`; const methodsHtml = list.map(item => { const methodName = item.method || item.name || 'unknown'; const desc = item.description || ''; return ``; }).join(''); return ``; }).join(''); const groupHtml = groups.map(group => { const list = toArray(group.list); const groupKey = slugify(group.module || group.groupName) || 'group'; const cards = list.map(item => renderMethodCard(item, entryPath, docData.module)).join(''); return `

    ${escapeHtml(group.groupName)} ${escapeHtml(group.module || '')}

    ${cards || '

    该分组暂无方法定义

    '}
    `; }).join(''); return ` ${escapeHtml(docName)} API 文档

    ${escapeHtml(docData.module || docName)} API 文档

    说明: ${escapeHtml(docData.description || '无')} 版本: ${escapeHtml(docData.version || 'N/A')} 更新: ${escapeHtml(docData.updatedAt || 'N/A')} 方法数: ${methodsCount} 统一入口: ${escapeHtml(entryPath)}
    ${isExternalApi ? '' : `

    全局 Authorization

    设置后会自动注入所有“在线调试”请求头,保存在浏览器本地。

    全局业务 Header

    ${globalHeadersControls}

    来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。

    `} ${isExternalApi ? '' : `

    文档资源

    ${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')} ${renderWindowElement('打开原文 JSON', rawUrl, 'doc-resource-link')}
    点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
    `} ${isExternalApi ? `

    请求方式

    POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
    Content-Type: application/json
    
    {请求体 JSON}

    签名算法(MD5)

    参与签名字符串 = canonicalQuery + self_app_secret + bodySign
    最终签名 sign = md5(参与签名字符串).toLowerCase()
    
    其中:
      canonicalQuery = 将 query 参数(排除 sign/signature)按 key 字母序升序排列,
                       拼接为 key1=value1&key2=value2 格式。
                       参数值序列化规则:undefined/null → 空字符串,
                       对象类型 → stableStringify 序列化,其他 → String(value)。
      bodySign = md5(stableStringify(请求体))
      stableStringify = 递归排序对象 key 的稳定序列化:
                       - 对普通对象,按 key 字母序递归序列化每个字段
                       - 对数组,按顺序递归序列化每个元素
                       - 对非普通对象(Date 等),使用 JSON.stringify
                       - undefined 返回空字符串,null 返回 "null"
      self_app_secret = 平台分配的密钥
    
    示例(假设 self_app_secret=abc123,请求体={"id":1}):
      query: app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0
      canonicalQuery = app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0
      stableStringify({"id":1}) = {"id":1}
      bodySign = md5({"id":1}) = 0a5b3e...
      signText = app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0abc1230a5b3e...
      sign = md5(signText) = ...

    注意事项

    • method 格式为 模块.方法,如 index.ping
    • app_key / self_app_secret 由仓库申请配置,请联系仓库管理员获取
    • 请求体必须为合法 JSON,空 body 传 {}
    • 时间戳 timestamp 为 Unix 秒级时间戳(数字类型)
    • 时间戳 timestamp 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400
    • 签名结果为 32 位小写十六进制字符串
    ${isOpenapi ? `

    → 回调测试工具 (模拟接收回调通知,验证回调链路)

    ` : ''}
    ` : ''}
    ${groupHtml || '

    暂无可展示的方法定义

    '}
    `; } class DocsController extends Controller { /** * 返回 docs 目录索引页面。 * @return {Promise} 无返回值。 */ async docsIndex() { const { ctx } = this; try { const docsRootPath = getDocsRootPath(this.app); const files = await collectDocsFiles(docsRootPath, docsRootPath); files.sort((left, right) => left.relativePath.localeCompare(right.relativePath, 'zh-Hans-CN')); ctx.set('Content-Type', 'text/html; charset=utf-8'); ctx.body = renderDocsIndexPage(files); } catch (error) { ctx.status = 500; ctx.body = { code: 500, message: '读取 docs 目录失败', error: error.message, }; } } /** * 读取 docs 目录下的指定文件。 * @return {Promise} 无返回值。 */ async docsFile() { const { ctx } = this; const rawRelativePath = ctx.params[0] || ctx.params.relPath || ctx.params.path || ''; const resolved = resolveDocsFilePath(this.app, rawRelativePath); if (!resolved.ok) { ctx.status = 400; ctx.body = { code: 400, message: resolved.message || '无效文档路径', }; return; } try { await sendDocsFile(ctx, resolved.filePath); } catch (error) { if (error.code === 'ENOENT') { ctx.status = 404; ctx.body = { code: 404, message: `未找到 docs 文件: ${resolved.relativePath}`, }; return; } ctx.status = 500; ctx.body = { code: 500, message: '读取 docs 文件失败', error: error.message, }; } } async list() { const { ctx } = this; try { const docs = await this.getDocNames(); if (!docs.length) { ctx.status = 404; ctx.body = { code: 404, message: 'methods 目录下没有可用的 JSON 文档', }; return; } const fallback = docs.includes('system') ? 'system' : docs[0]; await this.renderDoc(fallback); } catch (error) { ctx.status = 500; ctx.body = { code: 500, message: '读取文档失败', error: error.message, }; } } async api() { await this.list(); } /** * 渲染 OpenAPI 文档独立页面。 * @return {Promise} 无返回值。 */ async openapi() { await this.renderDoc('openapi'); } /** * 渲染仓库开放 API 文档独立页面。 * @return {Promise} 无返回值。 */ async warehouse() { await this.renderDoc('warehouse'); } async detail() { const { ctx } = this; const docName = ctx.params.docName; await this.renderDoc(docName); } async raw() { const { ctx } = this; const docName = ctx.params.docName; if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } const filePath = getDocFilePath(this.app, docName); try { const content = await fs.readFile(filePath, 'utf8'); ctx.type = 'application/json; charset=utf-8'; ctx.body = content; } catch (error) { ctx.status = 404; ctx.body = { code: 404, message: `未找到文档: ${docName}`, }; } } async changes() { const { ctx } = this; const docName = ctx.params.docName; if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } const filePath = getDocChangesFilePath(this.app, docName); try { const content = await fs.readFile(filePath, 'utf8'); ctx.type = 'application/json; charset=utf-8'; ctx.body = toArray(JSON.parse(content)); } catch (error) { if (error.code === 'ENOENT') { ctx.type = 'application/json; charset=utf-8'; ctx.body = []; return; } ctx.status = 500; ctx.body = { code: 500, message: `读取变更记录失败: ${docName}`, error: error.message, }; } } async getDocNames() { const docsDir = path.join(this.app.baseDir, 'methods'); const entries = await fs.readdir(docsDir, { withFileTypes: true }); return entries .filter(entry => entry.isFile() && entry.name.endsWith('.json')) .map(entry => entry.name.replace(/\.json$/i, '')) .sort(); } /** * 渲染指定 API 文档详情页。 * @param {string} docName 文档名称(不含 .json 后缀)。 * @return {Promise} 无返回值。 */ async renderDoc(docName) { const { ctx, app } = this; if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } const filePath = getDocFilePath(app, docName); try { const [ content, docs ] = await Promise.all([ fs.readFile(filePath, 'utf8'), this.getDocNames(), ]); const docData = JSON.parse(content); const groups = normalizeGroups(docData); const entryPath = resolveDocEntryPath(docData); const html = renderHtmlPage({ docName, docData, groups, docs, entryPath, }); ctx.type = 'text/html; charset=utf-8'; ctx.body = html; } catch (error) { ctx.status = 404; ctx.body = { code: 404, message: `未找到文档或 JSON 格式错误: ${docName}`, error: error.message, }; } } } module.exports = DocsController;