Commit Graph
100 Commits
Author SHA1 Message Date
qing 12ece9020c feat(libhttp,gateway): add admin-only WebSocket reverse proxy
libhttp v3.1:
- add ws_proxy(path, handshake) API with WsProxyHandshakeHandler callback
- implement full-duplex async bidirectional bridging (text+binary frames)
- support ws:// and wss:// backends with SNI, write queues for ordering
- proxy routes take priority over regular ws() routes
- 403 response on handshake rejection, graceful close propagation

gateway v0.6.0:
- add [WsProxy] config section (routes = /path=ws://backend;...)
- handshake callback verifies Token (Authorization/Cookie) is_admin=true
- non-admin / expired / missing token → 403, admin → transparent bridge
- fix LocalTime.hpp C++20 tzdb incompatibility on Apple clang (use strftime/get_time/mktime)
- update example.ini and README docs for both modules
2026-08-01 05:20:14 +08:00
qing 6ed88feaa4 feat(static): 新增 aibox 智能体 Web 客户端(移动端适配)
- aibox.html:自包含移动端聊天页,经 gateway [WsProxy] 反向代理与 aibox 通信
- 协议兼容 BotOps client.py:chunk 流式渲染 / reasoning 思考区 / task 任务面板 / 指数退避重连
- 移动端适配:100dvh 动态视口 + safe-area 刘海屏 + 44px 触控目标 + 任务面板抽屉式
- 安全:握手由 gateway 强制 is_admin 验签,Token 全程 HttpOnly Cookie,CSP 合规(本地 markdown-it)
- README 同步页面清单与功能说明
2026-08-01 05:18:30 +08:00
qing bf2b5d31f7 fix(botops): v1.2 - 彻底修复思考区域与正式回答顺序问题
问题根因:之前预创建空 AI widget,思考 widget 挂载在其后,即使动态重排也可能因 Textual 组件树更新时序导致顺序不稳定。

修复方案:
- 移除 prefab 空 AI widget 预创建逻辑
- start_ai() 仅标记状态,不创建任何 widget
- _ensure_ai_widget() 延迟到第一次 chunk 到来时才创建 AI widget
- 按消息到达顺序自然挂载:reasoning_start → reasoning → chunk → end_reasoning/finish_ai
- 思考 widget 必然先于 AI widget 挂载,顺序天然正确

同时:
- 简化 app.py 发送失败处理,不再需要移除空 widget
- 更新 README v1.2 说明
2026-08-01 05:00:56 +08:00
qing 9815ff44af feat(libhttp): integrate WebSocket client into HttpClient
Merge WebSocket client functionality into HttpClient using Boost.Beast,
enabling a single client instance to handle both HTTP (libcurl) and
WebSocket (ws:// and wss://) protocols. Backward-compatible type aliases
(WebSocketClient, WebSocketClientBase) preserve existing code.

Changes:
- Add synchronous WebSocket client: ws_connect/ws_send/ws_recv/ws_close
- Support ws:// (plain TCP) and wss:// (TLS with SNI) connections
- Layered stream architecture with beast::tcp_stream for timeout support
- Binary message support via ws_send_binary()
- Update Makefile to link libcurl (-lcurl)
- Add README.md documenting unified HttpServer + HttpClient API
2026-08-01 04:59:47 +08:00
qing 5edb67b46d docs(botops): update README with reasoning mode ordering fix and v1.1 changelog
- Update reasoning display limit from 2000 to 3000 chars in protocol docs
- Add widget ordering guarantee note (reasoning always before answer)
- Document info message filtering for conversation start notifications
- Add v1.1 changelog section listing reasoning mode features and fixes
2026-08-01 04:56:25 +08:00
qing 039d6acf37 fix(botops): fix reasoning panel appearing after AI response and filter conversation start notification
- Add _ai_prefab flag to track pre-created empty AI widget
- start_reasoning() now reorders widgets: remove empty AI widget, mount reasoning first, then remount AI widget
- This ensures reasoning always appears BEFORE the actual answer
- Filter out 'Conversation started'/'对话开始' info notifications (implicit event, no need to show)
- Increase reasoning display limit from 2000 to 3000 chars
2026-08-01 04:55:12 +08:00
qing ba9a77fe66 feat(libhttp): integrate WebSocket support into HttpServer
Merge WebSocketServer functionality into HttpServer so a single port can
serve both HTTP(S) and WebSocket(S) endpoints while preserving full backward
compatibility for existing HTTP interfaces.

Key changes:
- Add WebSocket route registration: ws(), onWsConnect(), onWsDisconnect()
- Add client management: sendToWsClient(), broadcastWs(), disconnectWsClient()
- Rewrite Session class using beast::tcp_stream for unified HTTP/WS handling
- Support automatic ws:// and wss:// upgrades on HTTP/HTTPS ports
- Thread-safe message queue with asio::post for cross-thread sends
- Update Makefile to link OpenSSL and pthread for TLS/WebSocket support
- Add test_server.cpp demonstrating HTTP + WebSocket mixed usage
2026-08-01 04:43:33 +08:00
qing e007990594 feat(dnfs,static): 新增管理员特殊节点(链接/网页代码/图片/文件)
- 信封格式:content 为 {"_sp":...} JSON,普通 Markdown 节点不受影响
- dnfs:add_note/update_note 按 is_admin 强制特殊节点发布权(非管理员 403),
  字段与大小校验(url≤2048、code≤512KB、base64≤3.5M 字符),AI 审核剔除 base64 负载
- dnfs:修复存量 bug —— 模块级 _sys.path.insert 未定义导致 import 即 NameError
- static:新增 GET /api/favicon 服务端代理(SSRF 防护:内网地址拦截 + 重定向校验 + 512KB 上限)
- 前端:管理员可见节点类型选择器;链接 favicon 卡片 / 网页可审计可运行 / 图片直显 / 文件下载
- theme.css 补充 select 与特殊节点样式;两个 README 同步更新
2026-08-01 04:34:23 +08:00
qing b79044d631 feat(aibox): add DeepSeek reasoning mode support with tool calling on deepseek-v4-flash
- Add api.reasoning_enabled config (default false) to enable thinking mode
- Uses deepseek-v4-flash native thinking capability (thinking param), supports tool calls while reasoning
- Real-time reasoning content streaming via reasoning_start/reasoning/reasoning_end WS messages
- Frontend shows reasoning in gray italic area, auto-folds long reasoning (>2000 chars)
- Dynamic reasoning detection: shows reasoning even if model returns it without explicit config
- Increase default API timeout to 120s for longer reasoning responses
- Remove duplicate _add_assistant_message_with_reasoning method
- Update docs: config example, message types table, v2.5 changelog
2026-08-01 04:33:55 +08:00
qing 81ae84851d feat(waf): add WebSocket proxy support and fix HTTP/2 proto version
- Implement http.Hijacker on responseRecorder to enable WebSocket upgrade
  (delegates Hijack() to underlying ResponseWriter, marks hijacked state)
- After WebSocket upgrade (101 Switching Protocols), skip HTTP response-phase
  WAF checks since connection becomes a binary frame stream
- Log WebSocket upgrades at Info level for observability
- Fix P2-3: use r.Proto instead of hardcoded "HTTP/1.1" in ProcessResponseHeaders
  for correct HTTP/2 protocol version reporting
- Add Write() method to responseRecorder to ensure WriteHeader is called
  before first Write (complies with http.ResponseWriter contract)
- Add bufio/net imports required by Hijacker interface
- Update README with WebSocket support section and v1.2 changelog
- Update SECURITY_AUDIT to mark P2-3 and P2-4 as fixed
2026-08-01 04:18:30 +08:00
qing 4e190953c0 feat(confs): integrate dnfs service with centralized config management
- Add dnfs.ini to confs/configs/ with server, database, ai_review, confs sections
- Refactor dnfs.py to use three-layer fail-safe config loading (defaults → confs → env vars)
- Unify timeouts for DB RPC and AI review calls via configuration
- Add _merge_ini() whitelist merging to prevent unexpected config injection
- Environment variables have highest priority for Docker networking (db/ai_review hostnames)
- Document config loading mechanism in both confs/README.md and dnfs/README.md

Follows the same pattern as static service integration; confs failure falls back
gracefully to built-in defaults + environment variables.
2026-08-01 04:13:39 +08:00
qing b4436b192a fix(waf): harden against OOM and Slowloris DoS attacks
- P0: add 10MB hard request body size limit with io.LimitReader,
  return 413 Request Entity Too Large when exceeded, prevents OOM
- P0: configure http.Server timeouts: ReadHeaderTimeout=10s (Slowloris),
  ReadTimeout=15s, WriteTimeout=30s, IdleTimeout=120s, MaxHeaderBytes=1MB
- P1: properly handle body read errors, log and return on client disconnect
- P2: drain and close r.Body in defer to ensure TCP connection reuse
- Log errors from ReadRequestBodyFrom and ProcessRequestBody
- Inject security headers on 413 responses
- Add security audit report (docs/SECURITY_AUDIT_20260801.md)
- Update README with timeout/body-limit docs and changelog
2026-08-01 04:13:39 +08:00
qing bd544a4181 docs(aibox): update file line count to ~8450 2026-08-01 03:51:17 +08:00
qing 164bc65b95 feat(aibox): add dedicated workspace directory to prevent file pollution
- Add WORKSPACE_DIR constant pointing to ~/.aibox/workspace by default
- Update file operations prompt to require writing temp files to workspace
- Update command execution prompt to use workspace as default work_dir
- Add command output size limit note in command execution prompt
- Update README with workspace directory structure and specification
- Add system.workspace_dir config item documentation
- Add v2.4 changelog entry
2026-08-01 03:49:25 +08:00
qing 53ce69c8dd docs(confs): update README for P1 fixes and clarify RpcClient usage
- Update title/description: pymsg RpcServer/TCP instead of plain pymsg/TCP
- Add new feature entries: cache copy return, list symlink guard, strict
  param validation, ConfigParser interpolation=None, Slowloris protection
- Fix Python call examples: RpcClient.call() returns data directly, not
  wrapped in {'success':..., 'data':...}; add RpcError try/except example
- Clarify reload semantics: empty string/non-string name returns error;
  only omitted name or explicit null triggers full cache clear
- Add parameter validation rules for get (name/key type checks) and reload
- Document INI % literal behavior (interpolation disabled)
- Add '返回值隔离' to cache mechanism section
- Expand security mechanism table: cache anti-tamper, list symlink guard,
  strict param validation, INI safe parsing
- Add docs/ directory and audit report reference to project structure
- Add notes about correct reload usage, INI % handling, and return copy
- Add audit report cross-reference in 注意事项
2026-08-01 03:46:39 +08:00
qing 2f3e63e499 fix(aibox): prevent OOM from large tool outputs with multi-layer safeguards
- ReadFileTool: replace readlines() with on-demand range reading; add reverse block reading for large file tail; limit single line to 10KB; hard-cap max_lines to 500
- SubprocessCommandExecutor: replace capture_output with line-by-line Popen reading; enforce 1MB output limit with immediate process termination; merge stdout/stderr counting for both sync and streaming modes
- Raise TOOL_MAX_RESULT_LENGTH default from 10KB to 1MB as final safety net
- Add SECURITY_AUDIT.md documenting vulnerabilities and remediation roadmap
- Update README with memory safety features and v2.3 changelog
2026-08-01 03:46:02 +08:00
qing 90761a723d docs(confs): fill in commit hashes for fixed issues in audit report 2026-08-01 03:43:01 +08:00
qing b53d4999ce fix(confs): harden parameter validation and prevent cache/info leaks
P1 fixes:
- P1-1 _handle_reload: empty string/0/false/falsy name no longer clears all
  caches; only explicit null/omitted name triggers full cache clear; non-string
  name raises ConfigError instead of being silently str()-converted
- P1-2 ConfigStore.get(): return dict(entry) shallow copy instead of direct
  cache reference to prevent callers from mutating the internal cache
- P1-3 list(): resolve symlinks via os.path.realpath() and skip entries whose
  real path escapes configs/ root; prevents leaking external file metadata
  (size, mtime) through directory-traversing symlinks
- P1-4 _handle_get key: validate key is a string (isinstance check); reject
  non-string/empty key with clear ConfigError instead of misleading str()
  conversion leading to "key not found" errors

P2 fixes:
- P2-1 ConfigParser: use interpolation=None to disable %(key)s interpolation,
  preventing InterpolationError on config values containing bare % characters
- P2-2 argparse: update description from "pymsg/TCP" to "pymsg RpcServer/TCP"
  to match module docstring

Also update SECURITY_AUDIT_20260801.md to mark issues 9-14 as fixed and
refresh the security mechanisms summary table; all P0/P1 issues are now resolved.
2026-08-01 03:42:46 +08:00
qing e4e9968d14 docs(confs): add security audit report 20260801
- Audit covers confs.py, log_client.py, startup scripts, and pymsg/rpc.py dependency
- Documents 8 issues fixed during this audit cycle (P0-P2) including Slowloris DoS,
  OOM, thread death, TOCTOU race, and log_client hardening
- Lists 4 remaining P1 issues (reload empty string clears all cache, mutable cache
  reference leak, list() symlink metadata leak, key type validation), 4 P2 issues,
  and 6 P3 issues with root cause, risk analysis, and fix suggestions
- Security mechanisms summary table for quick reference
- Follows project convention: gateway/docs/SECURITY_AUDIT_YYYYMMDD.md
2026-08-01 03:37:22 +08:00
qing 9efb96ea66 fix(confs): eliminate TOCTOU race in ConfigStore path resolution
- Split _resolve() into _validate_name() (pure string checks, lock-free
  fast-fail) and _resolve_locked() (filesystem checks, must be called
  under lock)
- Perform all filesystem operations (realpath → isfile → stat → open)
  inside self._lock in get(), eliminating the window between path
  validation and file open where a symlink swap could escape the
  configs directory
- Apply same fix to reload(): validate name outside lock, resolve path
  inside lock to prevent TOCTOU during targeted reload
- Hold lock during list() directory traversal so the `cached` flag
  (which reads self._cache) is consistent with directory state; wrap
  os.stat() in try/except to tolerate files disappearing mid-traversal
- Update docstring and README:
  - Protocol description corrected to pymsg RpcServer/TCP
  - Python client examples updated from legacy MsgClient to RpcClient
  - Security section now documents TOCTOU mitigation and Slowloris
    protection (added by earlier pymsg fix)
2026-08-01 03:32:19 +08:00
qing 6c587a22d8 docs(db): update README for log_client SDK template and hardening features
- Document that example_log_client.py now uses RpcClient (high-level RPC)
  instead of legacy MsgClient (low-level TCP frames)
- Add comprehensive client feature list reflecting all hardening fixes:
  - Thread exception protection (outer try/except prevents thread death)
  - Accurate enqueue-time timestamps
  - Queue maxsize with drop-oldest policy
  - Safe JSON serialization fallback
  - Event-based flush synchronization
  - Non-blocking push() guarantee
- Clarify length truncation: server-side _log_internal() truncates
  internal logs to 8KB/4KB, external clients should control length
- Add db_tools.py to file table (was previously undocumented)
- Update service description to mention RpcServer
2026-08-01 03:28:40 +08:00
qing bdbea6ac40 fix(log_client): update example_log_client template to use RpcClient
- Replace legacy MsgClient (low-level TCP frames) with RpcClient (high-level
  RPC) to match dbv2's RpcServer interface; the old MsgClient-based version
  was incompatible with the current RPC routing protocol
- Apply all hardening fixes from the service copies:
  - Outer try/except in _flush_loop to prevent any exception from killing
    the background thread
  - _safe_json() helper for unserializable extra fields (fallback to str/repr)
  - Timestamp generated at push() (enqueue time) instead of _send() time
  - Event-based flush() synchronization instead of unreliable sleep(0.6)
  - Queue maxsize=10000 with drop-oldest policy to prevent unbounded memory
  - put_nowait with Full handling ensures push() never blocks business threads
  - RpcClient construction wrapped in try/except
- Add explicit service_name parameter example for all 4 services in comments
- This is the template file referenced by db/README.md and copied by new
  services; keeping it in sync prevents propagating old bugs
2026-08-01 03:26:19 +08:00
qing 3be9e78335 docs(aibox): update README for v2.2 prompt system fixes
- Expand prompts directory listing to show all 10 skill files explicitly
- Update prompt system table: '1_*.md' → 'N_*.md (N=1~10)' with numeric ordering
- Document load order guarantee (identity → skills 1-10 → soul → status)
- Document is_continuation behavior (no repeated pre_prompt on recursive calls)
- Add v2.2 changelog: prompt ordering fix, token waste reduction,
  recursion pre_prompt dedup, large-file threshold, memory search tuning
2026-08-01 03:24:39 +08:00
qing 1b9c727e80 fix(log_client): harden background flush thread against exceptions
- Wrap _flush_loop main body in outer try/except to prevent any
  unexpected exception (network errors, serialization errors, etc.)
  from killing the background thread (which would cause unbounded
  queue growth and eventual OOM)
- Wrap _send() call in inner try/except as final safety net
- Wrap RpcClient() construction in try/except (connection failures
  during client creation were previously unhandled)
- Add _safe_json() helper: unserializable extra fields fall back to
  repr()/str() instead of raising TypeError that could kill thread
- Generate timestamp at push() (enqueue time) instead of _send() time,
  so timestamps reflect actual event time even when queue is backed up
- Replace unreliable time.sleep(0.6) in flush() with _flush_done Event
  for proper synchronization between caller and background thread
- Add _QUEUE_MAXSIZE=10000 with drop-oldest policy to prevent unbounded
  memory growth even in pathological cases
- Use put_nowait with Full handling to ensure push() never blocks
  business threads
- Sync fix to all 4 copies: confs/static/smtp/dnfs
2026-08-01 03:23:19 +08:00
qing e8fa26d79f fix(aibox): fix prompt ordering, reduce per-turn token waste, and improve defaults
Prompt system bugs and improvements:

1. **SKILL_PREFIX bug fixed**: SKILL_PREFIX = "1_" only matched files starting
   with "1_", causing 2_ through 10_ skill prompt files to be misclassified
   as "other" files and sorted in wrong order (e.g., 10_task_handling.md
   sorted before 2_memory_save.md due to lexicographic ordering). Replaced
   with regex _SKILL_FILE_RE = re.compile(r'^(\d+)_') and _skill_sort_key()
   that extracts the numeric prefix for proper numeric sorting.

2. **_init_system_prompts used unsorted list**: get_prompts_list() returned
   prompts in os.listdir() lexicographic order, which put 100_STATUS.md
   before 1_memory_search.md and 10_task_handling.md before 1_memory_search.md.
   Now uses get_sorted_prompts_list() for correct ordering:
   identity → skill prompts (1-10 by number) → soul → status.

3. **Verbose pre_prompt injected every turn (~30 lines)**: The pre_prompt
   contained detailed workflow instructions (search_skills first, memory
   search, ask_user, etc.) that duplicated what system skill prompts
   already say, wasting ~300+ tokens per user message. Worse, the same
   verbose prompt was injected on recursive think_and_respond calls after
   tool execution, confusing the model with repeated "第一步搜索技能"
   instructions when it was already mid-conversation with tool results.
   - Reduced pre_prompt to 5 concise bullet points as a reminder
   - Added is_continuation parameter: recursive calls after tool execution
     skip pre_prompt entirely and just pass "请基于以上工具执行结果继续回答。"
   - Removed post_prompt (save_memory/update_soul instructions already in
     2_memory_save.md and 8_identity_management.md)

4. **Unreasonable large-file thresholds**: 3_file_operations.md default
   said >50KB or >200 lines is "too large" — too conservative for code
   files. Raised to 500KB/2000 lines; added tail=true and binary file
   guidance.

5. **Overly rigid memory search instruction**: 1_memory_search.md said
   "每次都要做!" (must do every time), causing unnecessary memory searches
   for simple greetings/acknowledgments. Softened to "根据话题相关性判断",
   with explicit examples of when to skip (greetings, confirmations).

New/changed methods:
- PromptManager._skill_sort_key(cls, filename) - extract numeric prefix
- PromptManager._prompt_sort_key(self, p) - tuple-based sort key
- PromptManager.get_sorted_prompts_list() - returns correctly ordered list
- PromptManager.get_skill_prompts() - uses regex instead of startswith("1_")
- DeepSeekChat.think_and_respond() - added is_continuation parameter
2026-08-01 03:19:58 +08:00
qing da7f11d352 fix(confs): add MAX_CONFIG_SIZE (1 MiB) to prevent OOM on oversized configs
- Add MAX_CONFIG_SIZE constant (1 MiB) to limit single config file size
- Check file size via os.stat() before reading into memory
- Oversized files raise ConfigError with descriptive message instead of
  being fully read (which could cause OOM with multi-GB files)
- Use single os.stat() call to get both mtime and size atomically
- Update README: document size limit in security mechanisms and notes
- Existing small configs (ini/json/yaml, typically <10KB) are unaffected
2026-08-01 03:15:06 +08:00
qing 9708fbc87e fix(pymsg): add recv_timeout to MsgServer to prevent Slowloris DoS
- Add configurable recv_timeout (default 10s) to MsgServer
- _handle_client now uses recv(s, timeout=...) instead of infinite blocking recv(s)
- Catch TimeoutError and close the slow client connection
- This prevents a single stalled connection from blocking the entire main select loop
- Update README with recv_timeout parameter and Slowloris mitigation docs
- Backward compatible: keyword-only arg with sensible default
2026-08-01 03:12:49 +08:00
qing ae42ab8a91 docs(aibox): update README for v2.1 robustness fixes and correct entry filename
- Fix all references from main.py to aibox.py (actual entry file)
- Update installation to use pip install -r requirements.txt
- Expand WebSocket message types table: add line/task_error/task_added/
  notification/connection_ack/interrupt_ack, correct chunk/complete/error semantics
- Fix message flow example: tool calls are reported via 'line' messages,
  not a non-existent 'tool_call' type
- Document _sanitize_tool_result() and error recovery (_rollback_messages)
  in development guide
- Add FAQ entry for tool-call-induced API failures
- Add v2.1 changelog covering all robustness fixes (reasoning_content
  filtering, tool_call id fallback, control character sanitization,
  message rollback on API failure)
2026-08-01 03:09:34 +08:00
qing a80bd582da fix(aibox): prevent tool results from corrupting conversation and breaking API requests
Root causes of API request failures after tool calls:
1. reasoning_content (an API response field) was echoed back in assistant
   messages, which could cause API format errors
2. tool_call id could be empty string when model didn't return one in a
   streaming chunk, producing invalid tool_calls that caused 400 errors
3. Tool execute() could return None or non-string types; direct string
   operations (len(), + "\n", [:200]) raised TypeError and produced
   non-string content in tool messages, breaking JSON serialization
4. Tool output (e.g. from run_command) could contain control characters
   (NULL/BEL/BS) that corrupted JSON payloads
5. When API request failed (network/4xx/5xx/parse error), messages added
   in that turn (user msg, assistant msg with tool_calls, tool responses)
   remained in self.messages, permanently poisoning conversation history
   so all subsequent requests would also fail

Fixes:
- Stop sending reasoning_content back to API in message construction;
  normalize assistant message content: null when tool_calls present, ""
  when neither content nor tool_calls exist, str otherwise
- Sanitize tool messages: ensure tool_call_id is non-empty (fallback id)
  and content is always a string
- Generate fallback tool_call id when model omits it; handle streaming id
  delivery where id arrives in a later chunk
- Add _sanitize_tool_result(): coerce None/non-string to str, strip
  control characters (preserve \n \t \r) to prevent JSON/API corruption
- Wrap execute_tool call in try/except in _handle_tool_calls for double
  safety; ensure history logging never crashes
- Truncate oversized results with an explicit note instead of replacing
  with a generic error that lost all useful output
- Add _rollback_messages(to_length) and record msgs_before_turn at start
  of think_and_respond; on any exception (RequestException, JSONDecodeError,
  or unexpected Exception), rollback self.messages to the pre-turn state
  so the conversation is not left in a broken state
- In _handle_tool_calls, wrap execute_tool in try/except and always
  produce a safe string result
2026-08-01 03:06:34 +08:00
qing 1b9e6f6b3a fix(botops): resolve duplicate AI response rendering in ChatView
Root cause: aibox.py think_and_respond recursively calls itself after tool
execution, and each recursive call's complete callback carries only the
final-round full_response. The old finish_ai logic treated complete as a
full-text alignment signal — when full_text != self._ai_text (which always
happened after recursive tool calls because _ai_text accumulated all chunks
while complete only held the last round), it triggered remove+remount,
causing visible duplicate/flash of AI responses. A secondary issue was
dialogue_ended arriving before complete, which made a second finish_ai call
remount the message a second time.

Changes:
- Remove the full-text replacement branch in finish_ai; chunk streaming is
  now the authoritative content source, complete is a finalization signal only
- Add _ai_finalized flag: start_ai resets it, finish_ai sets it; repeated
  finish_ai calls (dialogue_ended + complete) return early to prevent remount
- append_ai drops late chunks after finalization to avoid dirty appends
- Empty pre-built widget without chunks still gets filled via w.update(full_text)
- Full lost-frame fallback (no widget + full_text) is preserved
- Update BotOps/README.md protocol section to reflect new complete semantics
2026-08-01 02:56:29 +08:00
qing f003b4dfaa style(static): 注册页图形验证码统一为 code-box 布局
- register.html 图形验证码改用 .code-box 行内布局,与邮箱验证码对齐
- theme.css 新增可复用 .captcha-img 类,替代内联样式
- README 功能列表补充表单组件说明
2026-08-01 02:51:55 +08:00
qing eb506e5cbf docs(confs): 更新 README 反映 static 已接入现状
新增"已接入的服务"表格,记录 static 的三层 fail-safe 接入方式
及实现细节;注意事项改为指向集成章节,避免重复描述。
2026-08-01 02:46:58 +08:00
qing ec1eb1e805 docs(gateway): 补充前端接入图形验证码说明
- README.md v0.5.4 变更记录补充前端改动(register.html/register.js 接入图形验证码)
- SECURITY_AUDIT_20260801.md P0-1 修复说明补充第 5 项前端同步,改动文件清单补全
2026-08-01 02:43:06 +08:00
qing 6ee1eca789 feat(static): 注册页获取验证码接入图形验证码
配合 gateway v0.5.4 邮件轰炸防护(/register/send_code 强制 CAPTCHA):

- register.html: 邮箱与邮箱验证码之间新增图形验证码区块(图片+输入框,复用 login 页结构)
- register.js:
  - 新增 refreshCaptcha() 复用 /captcha/image 代理路由(与 login.js 一致)
  - 新增 checkCaptcha() 校验图形验证码非空且 Token 已加载
  - 获取验证码按钮点击时先校验图形验证码,再携带 captcha_token + captcha_answer 发送
  - 无论发送成败都刷新图形验证码(Token 一次性消费)
  - 重置表单时清空图形验证码并刷新

方案 A:仅在「获取验证码」时要求 CAPTCHA,注册提交不加(邮箱验证码已是二次验证)
2026-08-01 02:42:15 +08:00
qing 0ef96c28f6 docs(confs): 新增服务 README
含功能特性、协议路由、缓存/安全机制、集成关系与项目结构
2026-08-01 02:38:20 +08:00
qing 49f0698b9d fix(gateway,smtp): 修复邮件轰炸漏洞(审计 P0-1)
gateway v0.5.3 → v0.5.4:

1. gateway/src/main.cpp
   - /register/send_code 强制 CAPTCHA 校验(经 captcha:8009,Token 一次性消费,fail-closed)
   - 新增邮箱级双窗口限流(3 次/小时 + 10 次/天,CAPTCHA 通过后才计入配额)
   - 新增 _EMAIL_ADDR_RATE_HOUR / _EMAIL_ADDR_RATE_DAY 限流器实例

2. smtp/smtp_v2.py
   - 新增邮箱级长期限流兜底(EMAIL_HOURLY_LIMIT / EMAIL_DAILY_LIMIT,默认 3/10)
   - 新增全局熔断(SMTP_HOURLY_LIMIT,默认 100 封/小时,防 smtp 账号被封)
   - 预占/回滚与 60s 冷却同模式,发送失败不计入配额

3. gateway/docs/SECURITY_AUDIT_20260801.md
   - 新增带日期的安全审计报告
   - P0-1 标记为已修复 v0.5.4

4. gateway/README.md
   - 更新 /register/send_code 接口文档(CAPTCHA 必填 + 5 层防护)
   - 更新版本变更日志

防护层次:IP 限流 → CAPTCHA → 邮箱级限流(gateway)→ 60s 冷却 → 邮箱级限流(smtp)→ 全局熔断
2026-08-01 02:37:15 +08:00
qing 2774c3471f docs(readme): 补充 confs 统一配置服务说明
- 架构总览/服务表格/端口表新增 confs(8010),日志链路加入 confs,新增配置链路
- 新增 confs 小节:路由说明、mtime 自动重载、消费方接入约定
- static 配置说明更新为 confs 分发 + 本地回退
- 修正安装序列(补 captcha/confs)、init.txt 启动顺序与实际一致
2026-08-01 02:34:51 +08:00
qing 287cab189d feat(static): 配置接入 confs 统一配置服务
- fsys.py 启动时优先从 confs(127.0.0.1:8010)拉取 static.ini,
  支持 CONFS_HOST/CONFS_PORT 环境变量覆盖
- confs 不可用时 fail-safe 回退本地 config.ini
- static.ini 纳入 confs/configs/ 统一分发
2026-08-01 02:30:14 +08:00
qing 7d7e3dc10a fix(confs): 删除错放的 .env 文件
confs.py 不读取 .env(无 dotenv 依赖),该文件实为 SMTP 凭据,
被误放入 confs 目录且会导致 python-dotenv 解析报错。
2026-08-01 02:20:46 +08:00
qing 55fbe2f1f1 feat(confs): 统一配置服务(pymsg/TCP :8010)
- confs.py 重写为统一配置服务:get/list/reload/health 路由,
  内存缓存 + mtime 自动重载,路径遍历防护,ini/json 按键提取
- 复制 log_client.py,新增 configs/example.ini 示例配置
- 注册到 core/init.txt(db 之后启动)与 _inst.sh 安装序列
2026-08-01 02:15:04 +08:00
qing ae92a6edde perf(pymsg): send/recv 零拷贝优化
send: sendmsg 散射-聚集 I/O 替代 header+payload 拼接,内核直接
从两块内存读取,省掉大消息的用户态拷贝。

recv: recv_into 写入预分配 bytearray 替代 bytearray 逐步 extend,
省掉 realloc 和 bytes() 转换。
2026-08-01 02:08:03 +08:00
qing 267d572906 fix(pymsg): 修复消息长度无上限导致 OOM DoS 漏洞
Python/Go 端 recv 缺失消息大小上限检查,恶意客户端发送 4 字节
超大长度头即可触发 OOM。新增 64 MiB 上限(与 C++ 端 Msg.hpp
对齐),在分配内存前拒绝并断开连接。新增 5 个单元测试覆盖。
2026-08-01 01:55:44 +08:00
qing e248290860 统一配置模块 2026-08-01 01:54:25 +08:00
qing 48b45cb44a 修复网关bug 2026-07-31 22:19:56 +08:00
qing e7f435dc4e refix 2026-07-31 21:07:41 +08:00
qing ada2af47af 增加handle_exp包装器 2026-07-31 19:47:27 +08:00
qing ea670adde2 feat(static): dnfs 内容输入框随内容自动调整高度
- textarea 输入时自动增长,最小 120px,最大 400px
- 超过最大高度后出现滚动条,避免页面无限撑开
- 编辑已有节点时自动适配内容高度
- 提交/重置/退出编辑后恢复初始高度
- 禁用手动拖拽 resize,由自动增长统一控制
2026-07-30 22:21:24 +08:00
qing 5839172dae 迁移/whoami视图 2026-07-30 22:05:12 +08:00
qing 3f97dd92ef update 2026-07-30 21:57:04 +08:00
qing f935448389 refix 2026-07-30 21:33:03 +08:00
qing 32d3a5a19f 重构db 2026-07-30 20:15:02 +08:00
qing 74610c32c8 微调 2026-07-30 19:03:34 +08:00
qing eec869a28d style(dnfs): 增大节点表单输入框尺寸 2026-07-30 15:56:06 +08:00
qing d309f41e47 refix 2026-07-30 15:52:18 +08:00
qing 7589b77916 docs: 更新 README.md - 补充 bot4cj、libtry、tests 等缺失模块说明 2026-07-30 12:44:29 +08:00
qing e4831522a4 docs: 新增 libhttp/libtry/pymsg/README.robot.md 技术手册,更新 BotOps/README.md 2026-07-30 12:38:31 +08:00
qing 8a14247aed docs(BotOps): 安装指引改用脚本 + 补全项目结构树 + 新增 Nuitka 编译说明
- 安装章节改用 bash _set.sh / _run.sh 一键脚本
- 新增 _inst.sh Nuitka 编译为 botops.bin 单文件的说明
- 项目结构树补全 _set.sh / _run.sh / _inst.sh / requirements.txt / __init__.py
2026-07-30 12:38:14 +08:00
qing 803d176066 docs(db): 修正 log_client 描述并补充 message/extra 截断说明
- "纯标准库实现" → "无第三方依赖(仅依赖 pymsg 项目内置库)",更准确
- 新增长度保护说明:message 上限 8KB、extra 上限 4KB,超长自动截断

fix(db): _set.sh Nuitka 注释 main.py → dbv2.py
2026-07-30 12:34:37 +08:00
qing ac8f3da9df docs(libcrypt): 完整 README,覆盖 5 个类 API、构建、示例与注意事项
- 5 个类的完整 API 文档(Crypto_Basic/AES_CBC/Base64/SHA256/MyRSA)
- 架构层级图与 header-only 设计说明
- 构建/安装/链接指引(含 OpenSSL 3.x 依赖说明)
- 可运行的使用示例
- Private_Key 私有继承、链接 -lssl -lcrypto 等注意事项

fix(libcrypt): SHA256.hpp 删除重复 bytes_to_hex,改用基类版本

- 私有 static bytes_to_hex 与 Crypto_Basic::bytes_to_hex 重复,已删除
- include 路径统一为 "Crypto_Basic.hpp"(与其他三文件一致)
- 移除随之无用的 <iomanip> <sstream> 头文件

fix(libcrypt): AES_CBC.hpp 补充缺失的 #include <iomanip>
2026-07-30 12:26:15 +08:00
qing 6649b31e17 feat(static): add frontend token auto-refresh for dnfs page
- New token_manager.js: silent refresh timer (80% lifetime) + global
  fetch 401 interceptor with one-shot retry.
- dnfs.py /whoami now returns iat, created_at, keep_time for expiry
  estimation.
- Dnfs.html loads token_manager.js before dnfs.js (zero change to dnfs.js).
- Graceful fallback: stale tokens without new fields, refresh failures,
  and /refresh_token 401 itself all degrade to the existing 401→login flow.
2026-07-30 12:25:11 +08:00
qing 254fbf4628 docs(aibox): 更新 README.md 并新增 README.robot.md 技术手册
README.md 修复:
- 新增 ask_user 工具到工具列表
- 补充配置表中缺失的 17 个字段(system/scheduler/api/context/memo/files/commands/web/memory/conversation/tools/compressor/proxy)
- 补充对话压缩完整配置项

README.robot.md 新增:
- 17 章节完整技术手册(~500 行)
- 架构图、数据流、协议详情
- 19 个工具的完整实现信息
- 配置参考(含所有字段说明)
- 已知限制与安全建议
- 部署与故障排查指南
2026-07-30 12:08:17 +08:00
qing 931e134796 docs(smtp): 新建完整 README,覆盖协议、路由、配置与安全机制
- 3 个路由的完整请求/响应文档(send_email / verify_email / health)
- .env 配置项说明(4 种格式支持、必填/可选字段)
- 验证码生命周期:生成→冷却→消费→过期→作废→失败回滚
- 安全机制:发送冷却、失败次数上限防枚举、SMTP 失败回滚
- 集成关系:gateway 调用流程、core 守护、log_client 日志推送
- 旧版 smtp.py 的安全风险标注

fix(smtp): _set.sh 中 nuitka 编译目标 smtp.py → smtp_v2.py
2026-07-30 12:02:25 +08:00
qing 63a80694ae docs(core): 新增代码审查日志 CODE_REVIEW_LOG_20260730.md
- 审查日期:2026-07-30 14:30:00 (Asia/Shanghai)
- 发现 16 个问题(4 Critical / 6 Medium / 6 Low)
- 核心风险:命令注入、无鉴权、空指针解引用
- 包含分阶段修复计划与优先级建议
2026-07-30 12:01:04 +08:00
qing 4506601773 docs(libth): 完整的 README 文档,覆盖 API、架构、构建与使用示例
- 新增 4 个类的完整 API 说明(Thread/Fsm/ITask/Cv_wait)
- "回字形"执行循环和两阶段构造的设计说明
- 构建、安装、链接、卸载的完整指引
- 可运行的使用示例代码
- 设计要点与注意事项(死锁风险、单次使用限制等)
- 修正 C++ 标准版本为 C++20(与 Makefile 一致)

fix(libth): Cv_wait.hpp 中 lcok 拼写错误修正为 lock
2026-07-30 11:58:26 +08:00
qing f214c862d3 docs(bot4cj): 新增 README.robot.md 完整技术手册
- 补充 5 层架构分层图(脚本→解析器→结构构建→硬件实现→系统库)
- 详解 .mt 脚本语法、块类型、占位符规则
- 补充 PCA9685/Servo/MPU6050/Speaker 各硬件寄存器与校准参数
- 说明执行流程:stdin→FSM 解析→链表→build/play/free
- 列出 I2C 总线保护、GC 析构、pthread_cancel 等安全限制
- 补充 11 条已知缺陷清单(D1-D11)
- 新增 NN/CNN 测试命令与 DRL 预留接口说明
2026-07-30 11:54:51 +08:00
qing a8a190571c feat(gateway): add /refresh_token API with grace window + refresh limit
- POST /refresh_token: accept current Bearer token (or Cookie fallback),
  verify RSA signature, check grace window (iat + keep_time * multiplier)
  and refresh count limit, then issue a new token.
- Token payload extended with iat, refresh_count, max_refresh fields.
- iat preserves original issue time; created_at updates on each refresh.
- Rate limited: 5 req / 5 min / IP via RateLimiter.
- Config: Token.refresh_grace_multiplier (default 2), Token.max_refresh (default 10).
- Backward compatible: old tokens without new fields still pass proxy checks.
2026-07-30 11:54:31 +08:00
qing aa3a99825c docs(captcha): 项目结构树和安装指引补全遗漏项
- 安装章节新增 bash _set.sh 初始化步骤
- 项目结构树补全 _set.sh 和 requirements.txt
2026-07-30 11:53:30 +08:00
qing dcfdbcb9f2 docs(waf): 更新 README 文档与代码实现对齐
- 新增「安全响应头」章节,列出 7 个 WAF 注入的响应头及说明
- 修正「已知限制」中响应体检测描述,明确响应头检测已启用
- 澄清拦截日志等级区分(WARNING 命中拦截 / ERROR 加载错误)及 extra 字段类型
- 补充规则 ID 分段表的 CRS 可选说明
- 更新目录结构列表补充 logclient 子包
- 请求处理流程新增 ModifyResponse 步骤
2026-07-30 11:49:10 +08:00
qing 62007e7848 docs(static): README 路由表、架构图、配置、依赖与实际代码同步
- 修正根路径 / 描述:index.html → login.html
- 补全全部 19 个路由(原仅 6 个),分组为核心/内部工具/OAuth/代理
- 架构图补全 waf:443 → gateway:8443 → static:9200 完整链路
- 配置示例新增 [cors] 段
- 依赖列表补全 waitress 和 pymsg
- 页面和功能列表补全遗漏项
2026-07-30 11:48:54 +08:00
qing 91e6659dac docs(waf): 拦截日志章节更新为 logclient 推送 db Logs 表的说明 2026-07-30 11:01:34 +08:00
qing 9765edac9b fix(static): 前端脚本识别 WAF 拦截响应并正确提示
- validation.js 新增 WafTip 公共检测:403 + 响应体含 blocked by WAF 双重特征,
  与 gateway 白名单拒绝的 403(JSON 错误消息)精确区分
- login/register/dnfs/view 各请求点在 JSON 解析前识别拦截,统一提示
  「请求被 WAF 安全规则拦截,请检查输入内容」
- 修复 dnfs getNode 被 WAF 拦截时落入 catch 误跳登录页的问题
- 验证码图片加载识别 403 拦截,alt 提示点击重试
- __view.html 补充引入 validation.js
2026-07-30 11:01:34 +08:00
qing 40175eddb5 Revert "style(dnfs): 用户信息面板移到左边中间,与右侧 minimap 镜像对称"
This reverts commit 5c33dbe027.
2026-07-30 09:52:08 +08:00
qing 5c33dbe027 style(dnfs): 用户信息面板移到左边中间,与右侧 minimap 镜像对称 2026-07-30 09:44:15 +08:00
qing a58a0f97e3 feat(dnfs): minimap 与用户面板按视口宽度决定初始折叠态
新增 PANEL_EXPAND_MIN_WIDTH=768 断点:宽屏默认展开、窄屏默认折叠避免
遮挡内容;仅决定初始状态,用户手动折叠/展开不被 resize 覆盖。
2026-07-30 09:40:58 +08:00
qing 55b127747a fix(dnfs): 用户面板用户名/角色改为纯展示,去除手型光标与 hover 变色
新增 .tag.no-hover 修饰类还原交互态;折叠按钮与退出登录保持可点样式。
2026-07-30 09:34:53 +08:00
qing 8c1956cdeb feat(dnfs): 左上角用户信息面板(默认折叠),新增 /whoami 身份接口
dnfs 新增 POST /whoami:解 Token payload 返回 user/is_admin,无或畸形
Token 返回 login=false(HttpOnly Cookie 模式下 JS 无法读 Token,身份
必须由后端下发);static 加 /whoami 代理(Cookie 转 Bearer);前端
dnfs.html 左上新增 userpanel,镜像 minimap 样式默认折叠,展开显示
用户名/角色/退出登录(POST /logout 清 Cookie 后跳登录页)。
2026-07-30 09:31:28 +08:00
qing 1388fcb72b feat(dnfs): 卡片移动按钮一并纳入 can_operate 权限显隐
编辑/移动/删除三个按钮合并为单次权限判断(移动本质也是 update_note),
未登录或无权时不渲染整个按钮组。
2026-07-30 09:21:15 +08:00
qing b4e1cf462a feat(dnfs): get_notes 按当前用户注入 can_operate,前端按权显隐编辑/删除按钮
dnfs get_notes 可选解析 Authorization(畸形 Token try 兜底),为每个节点
附带 can_operate 标记(is_admin 或 owner,口径与 delete/update 一致);
dnfs.js 卡片编辑/删除按钮仅 can_operate === true 时渲染,未登录或无权隐藏。
2026-07-30 09:17:28 +08:00
qing 46c3a197be refactor(auth): 管理员判定上移至 gateway,经 Token payload 下发 is_admin
gateway 登录签发 Token 时,账号命中 [Admin] users 白名单即在 payload
写入 is_admin=true(随 RSA 签名保护);dnfs 移除本地 ADMIN_USERS 硬编码,
delete_note/update_note 豁免判断改读 payload 的 is_admin 字段。
旧 Token 无此字段按非管理员处理(安全方向)。
2026-07-30 09:08:33 +08:00
qing e9f9860fe1 fix(dnfs): review_content 兼容布尔/字符串审核结果,修复安全内容误拦
仅明确判定安全(布尔 false 或字符串 "false")才放行,其余一律拦截,
保持 fail-closed;同时消除 invalid 字段缺失时的 KeyError。
2026-07-30 08:38:14 +08:00
qing 949d274c22 获取节点失败后跳转 2026-07-30 08:22:53 +08:00
qing bcd6c84e3b Merge branch 'dev_qing' of https://git.cancerai.top/qing/micro_servers into dev_qing 2026-07-29 21:57:47 +08:00
qing 5275b8bf75 feat(smtp): 邮箱验证码连续校验失败 5 次自动作废,防枚举 6 位数字码 2026-07-29 21:57:16 +08:00
qing e6e5dab4cd 智能体提问 2026-07-29 21:54:22 +08:00
qing 3c02ba43ad AskUserTool 内置技能 2026-07-29 21:23:04 +08:00
qing c5dd8d198d feat(smtp): 同一邮箱 60 秒发送冷却,gateway 429 透传 + 前端重发倒计时(gateway v0.5.3) 2026-07-29 20:54:56 +08:00
qing f4a7aca2fa update: smtp 验证码有效期 60s 调整为 10 分钟,邮件正文从 CODE_TTL 派生
60 秒对邮件送达延迟过于紧张;正文有效期文案改为按 TTL 自动生成避免漂移,前端提示与 README 同步。同时移除 .env 排查用的凭证明文调试打印。
2026-07-29 19:32:44 +08:00
qing f5b69d0b4c fix: smtp .env 解析兼容 KEY: VALUE 冒号格式,MAIL_FROM 默认跟随 SMTP_USER
服务器 .env 误用 YAML 冒号格式导致凭证全部加载为空;163 等服务商强制 From 头与登录账号一致,写死的 MAIL_FROM 会触发 553,现默认取 SMTP_USER、可用 .env 显式覆盖。
2026-07-29 19:08:13 +08:00
qing 53c742c26e refactor: smtp.py.remote 更名为 smtp_v2.py,恢复 .py 后缀以便工具链识别
_run.sh 同步指向新文件名;start() 新增启动时凭证明文打印(仅 stdout 不落日志库),用于排查 .env 加载问题,调试完成后需移除。
2026-07-29 18:36:21 +08:00
qing 11993e178b smtp dev 2026-07-29 18:22:38 +08:00
qing 3bc4f9720f fix(dnfs): 移动请求期间禁用按钮防止重复提交
后端 update_note 走 AI 审核耗时较长,confirmMove 期间禁用移动条
与表单按钮,finally 统一恢复
2026-07-29 14:37:27 +08:00
qing 751866d9c1 refix 2026-07-29 11:52:46 +08:00
qing 3f9bffb9ea feat(dnfs): 节点移动功能
- dnfs.js: 卡片新增移动按钮,startMove 暂存节点,底部悬浮移动条
  提供移动到当前层/取消;confirmMove 经 update_note 改 pid 完成迁移;
  拦截移动到自身与已在当前层的情况
- dnfs.html: 新增 #movebar 容器
- theme.css: act-move 描边按钮与 movebar 底部悬浮条样式
2026-07-29 11:40:35 +08:00
qing ace98caff6 feat: 卡片编辑/删除按钮 + dnfs 管理员豁免
- dnfs.js: 卡片底部新增编辑/删除按钮,复用下方表单支持编辑模式
  (startEdit/cancelEdit/updateNode/deleteChild),stopPropagation 防误触
- theme.css: 新增 card-actions/act-btn 按钮样式,编辑橙色/删除红色软底
- dnfs.py: ADMIN_USERS 统一管理豁免名单(admin, admin@qsont.me),
  update_note 新增管理员豁免,delete_note 同步改用名单
- dnfs/README.md: 同步更新所有权豁免说明
2026-07-29 11:22:30 +08:00
qing a0f6a14b5d style(dnfs): 笔记卡片尺寸随内容自适应
- recommend-list 改为 flex 纵向布局,gap 统一间距,隐藏 JS 遗留 <br> 分隔符
- 卡片宽度 fit-content 包裹内容,min-width 240px 保底、max-width 100% 封顶
- 内容图片限宽防撑破自适应布局
2026-07-29 11:05:20 +08:00
qing 2fc12e7b00 feat(dnfs): 卡片增加观看/点赞/分享互动统计图标
- dnfs.js: 新增眼睛/爱心/转发 SVG 图标常量与 makeStatItem 构造函数,
  统计行挂载在 owner 胶囊下方,计数缺省显示 0(后端暂无该字段)
- theme.css: 新增 card-stats/stat-item/stat-num 样式
2026-07-29 10:59:40 +08:00
qing dae81ba4a1 style(dnfs): 美化卡片发帖用户显示为头像+昵称胶囊
- dnfs.js: owner 纯文本改为首字符圆形头像 + 昵称,空值兜底匿名
- theme.css: 新增 Owner Chip 样式段,复用主题变量自动适配深色模式
2026-07-29 10:53:29 +08:00
qing a905dac00d display note ownerx 2026-07-29 10:47:20 +08:00
qing b8ec752a12 docs(pymsg): 添加中文 README 文档,涵盖协议、API 参考和实际用例 2026-07-29 09:39:49 +08:00
qing b86b089634 fix(BotOps): 修正 aibox 协议语义错配导致的输出丢失
- 服务端 chunk 为增量片段(chunk_buffer 发送后即清零),原 _delta
  按累计全文假设计算,相邻 chunk 前缀撞字时静默丢字符;改为直接拼接
- complete 携带完整全文,finish_ai 改为全文对齐(不一致时整体替换,
  可自愈丢帧/乱序),修复结尾全文重复 append
- 新增 line/reasoning/task_added/dialogue_reset/pong 消息路由:
  line(🔧 工具调用提示、工具输出)不再落入兜底污染聊天区,改投任务侧栏
- 发送失败时移除预建的空 AI 消息框并提示,避免空等回复
- 断线提示补充重连窗口期服务端输出丢失说明
- 同步修正 ws_client/README 中的协议描述
2026-07-29 09:32:30 +08:00