Conversation
Browser-based chat frontend for the mcode agent runtime. Streams
mcode acp / exec sessions with real-time tool events, plan review,
ask-user prompts, context usage, and quota. Zero npm dependencies;
runs on Node 22+.
- New plugin at plugins/Wzdhehe/mcode-webui/ per Agent Plugins 1.0
- plugin.json (10 white-listed top-level fields, 13 capabilities)
- skills/mcode-webui/SKILL.md (frontmatter name + description 343 chars)
- LICENSE (MIT)
- README.md + README.zh-CN.md (bilingual)
- references/SECURITY-NOTES.md (canonical security disclosure)
- docs/ (ARCHITECTURE, API, CAPABILITIES, DEVELOPMENT, TROUBLESHOOTING)
- server/, public/, test/ (real directory copies, kept in sync with
the project root at github.com/Wzdhehe/mcode-webui)
- PR_DESCRIPTION.md + CONTRIBUTING.md
Source: github.com/Wzdhehe/mcode-webui (v1.0.0 + doc polish)
Validate: OK plugin Wzdhehe/mcode-webui
Mirror of the source-repo follow-up: - SKILL.md frontmatter name back to mcode-webui (spec requires it to match the directory name) - Strip CR from UTF-8 text files so the official validator sees LF-only frontmatter - Revert product-name mcode->Mcode in CLI/trigger references
…owercase by spec)
…y mode Addresses PR MiniMax-AI#16 reviewer feedback (Please fix the authentication boundary before merge). New behavior: - Token auth gate: server-side constant-time token validation on every non-local /api/* request via new server/lib/auth.js. Token resolved from TOKEN env > settings.currentToken > auto-generated 32-hex on first start (printed to stdout once, never to .server.log, persisted to ~/.mcode-webui/settings.json with mode 0600). - LAN sub-card: 顶栏 LAN chip 下弹出子卡片, 4 个子功能 (read-only toggle, token rotation with SSE auth.token_rotated broadcast, token acknowledged state machine, 复制可分享 URL 含 token). - Read-only mode: 非本机 POST/DELETE 到 /api/* 返 403, 远程只能读. 顶栏红色脉动 chip 提示只读状态. /api/settings 例外 (escape hatch). - Top-bar read-only chip + bilingual single-page LAN reject page (zh + en stacked, dynamic PORT). Sub-mechanisms documented separately in CHANGELOG, README (× 2 langs), CAPABILITIES, SECURITY-NOTES. Tests: 372/372 pass. Lint: 0 warnings. Independent audit: FUNCTIONAL.
…on support Same commit as Wzdhehe/Mcode-webui ea896d1, mirrored to plugin layout for MiniMax-Code-Plugins registry. Round 2 audit (reviewer mentioned 'CORS/URL-token leakage considerations') found two related bugs: 1. L281: Access-Control-Allow-Headers only listed 'Content-Type', so any cross-origin fetch with 'Authorization: Bearer' would fail CORS preflight. 2. Gate 3 (token auth) had no exemption for OPTIONS preflight, so even with the L281 fix, OPTIONS preflight to /api/* would hit Gate 3 and return 401 (browsers cannot attach Authorization to a preflight). The real POST would never reach the server. Fixes: - server/router.js L281: Allow-Headers now lists 'Content-Type, Authorization' - server/router.js Gate 3: add req.method !== 'OPTIONS' exemption (matches Gate 4 read-only's existing pattern) - test/router-cors.test.js: 9 new tests covering CORS headers + Gate 3 preflight behavior. Tests: 381 pass / 0 fail. Lint: 0 warning. Independent audit: FUNCTIONAL.
…ke test + doc sync)
Mirror of Wzdhehe/Mcode-webui commits decceb6 + 91d0bb0 to plugin layout.
Round 3 review (reviewer: 'setTokenAuthEnabled load-time blocker' +
'add a startup/import smoke test that exercises the real server bootstrap')
found two real bugs plus 13 stale doc claims. All addressed:
Code fixes (commit decceb6):
- plugins/.../server/lib/auth.js: synced from root, now exports
setExpectedToken + setTokenAuthEnabled (mirror was stale since
v1.0.1 LAN sub-card commit 999115d — setTokenAuthEnabled is
imported by server.js:26, missing export was a load-time blocker)
- plugins/.../test/lib-auth.test.js: synced from root (4 new tests
for the setters + clean try/finally state reset)
- plugins/.../test/server-startup.test.js (new): spawns \
ode server.js\,
captures stdout/stderr, SIGTERMs after 2s, asserts no ESM load
errors and 'listening on' reached
Doc fixes (commit 91d0bb0):
- docs/API.md: remove availableInterfaces (v1.0.1 cleanup removed it
but doc still had it)
- docs/ARCHITECTURE.md: remove pushEvent from state-bus exports,
correct the mcodeCommandsCache claim (lives in state-bus.js not
acp-client.js), expand config.js exports list
- docs/DEVELOPMENT.md: remove pushEvent from example code + import +
transport-layer description
- plugins/.../references/SECURITY-NOTES.md: remove 'set-headers' and
'crash-now' debug endpoints claims (those endpoints never existed
in the v1.0.1 source)
- README.md / README.zh-CN.md / CHANGELOG.md / CONTRIBUTING.md /
plugins/.../README.zh-CN.md / scripts/verify.mjs: stale test counts
fixed (302/372 → 382 passing + 1 skipped, 383 total)
- plugins/.../package.json: validate:plugin and verify scripts added
(mirror was missing them; CONTRIBUTING.md references them)
- All 4 docs/{API,ARCHITECTURE,DEVELOPMENT,TROUBLESHOOTING}.md:
brought back in sync with root (mirror drift fixed)
Verified: lint 0 warning, ROOT vs mirror SHA256 match for all synced
docs and code files.
Tests: 382 passing + 1 skipped (383 total).
…n-canonical install layouts Mirror of Wzdhehe/Mcode-webui commit 4abf56c to plugin layout. Round 4 review (modacker follow-up on PR MiniMax-AI#16) found that server/lib/db.js's getMcodeBetterSqlite3() hardcoded \__dirname/../../../node_modules/@minimax-ai/code/node_modules/better-sqlite3\. This path only works in the canonical dev layout where webui is at \<mcode-root>/webui/\. On macOS, registry install, or any non-canonical layout, mavis returns null → DELETE /api/sessions/:id fails (500) → 5 db.js tests fail on macOS reviewer. Fix: candidate-list fallback with priority: 1. \ env (explicit user override) 2. <MCODE_CMD>/../../node_modules/@minimax-ai/code/node_modules/better-sqlite3 3. <__dirname>/../../../node_modules/@minimax-ai/code/node_modules/better-sqlite3 (dev layout fallback — unchanged) Changes: - plugins/.../server/lib/db.js: replaced single hardcoded path with candidate-list fallback. Exports _getBetterSqlite3Candidates() for install-layout tests. - plugins/.../test/lib-db-resolver.test.js (new): 5 tests covering env override priority, dev layout fallback, candidate count invariant, MCODE_CMD branch. - plugins/.../references/SECURITY-NOTES.md §7: documents MCODE_BETTER_SQLITE3 env override next to existing MCODE_RUNTIME_DB and MCODE_WEBUI_SETTINGS_PATH entries. Tests: 387 passing / 0 failing / 1 skipped. Lint: 0 warnings. Independent audit: PASS.
Round 5 addresses the two remaining CHANGES_REQUESTED items from hetaoBackend's 2026-08-27 01:34Z review on PR MiniMax-AI#16 (commit 99dd587). 1. server/lib/db.js::_getBetterSqlite3Candidates Round 4 used `join(MCODE_CMD, '..', '..', ...)` which treated the mcode executable file as a directory. The fix uses `dirname(mcodeCmd)` directly: mcode.cmd is a file in the install dir, and the package's node_modules/ sits next to it. Round 4 accidentally went 3 levels above the install root (e.g. `/Users/moc/node_modules/...` instead of `/Users/moc/.minimax-code/node_modules/...`). The function is now parameterized as `_getBetterSqlite3Candidates({ mcodeCmd = MCODE_CMD } = {})` so install-layout tests can simulate any layout without mutating the module-level constant. 2. server/lib/db.js::deleteMcodeSessionFromDb The db-path check now runs BEFORE better-sqlite3 load. Round 4 had these reversed: callers passing a missing MCODE_RUNTIME_DB got `better_sqlite3_not_loaded` even when the db path was the actual problem. The test in lib-db.test.js:65 already documents the expected order (`mcode_db_not_found` must win) — implementation now matches. 3. test/lib-db-resolver.test.js - Test 5 ('MCODE_CMD-derived candidate is present...') updated to expect the corrected `dirname(MCODE_CMD)` prefix instead of the round 4 buggy `dirname(MCODE_CMD)/..` prefix. Adds a guard assertion that the buggy prefix is NOT used. - 3 new install-layout tests covering: • mcode binary at <install>/mcode.cmd → <install>/node_modules/... • mcode binary at /usr/local/bin/mcode → /usr/local/bin/node_modules/... • MCODE_CMD = 'mcode' (PATH placeholder) → no MCODE_CMD-derived candidate Test results in modacker env (no mcode install): • lib-db-resolver.test.js: 8/8 pass (5 existing + 3 new) • lib-db.test.js input validation: 5/5 pass • lib-db.test.js happy path / table-missing: 2/8 fail with reason='better_sqlite3_not_loaded' — environmental (no real better-sqlite3 binary at any candidate path). The fix doesn't cause this; these tests require a real mcode install to pass. Reviewer should re-run in a mcode-installed env. Refs: hetaoBackend review 2026-08-27 01:34Z on MiniMax-AI#16
…egration tests on macOS)
Round 5 closed two of hetaoBackend's open items, but the candidate
list still missed the actual mcode install layout on a real macOS dev
box (where the user is running mcode as their agent runtime).
Symptom: MCODE_CMD in config.js resolves to the PATH placeholder
'mcode' (not a full path) because the detection chain only looks for
'mcode.cmd' / 'MCODE_ROOT/mcode.cmd' / '~/.minimax-code/mcode.cmd',
and on macOS the binary is just 'mcode' at '~/.minimax-code/bin/mcode'.
With MCODE_CMD='mcode' the MCODE_CMD-derived branch is skipped
altogether, and the dev-layout fallback points at the plugin source
tree, not the real mcode package. Integration tests that actually
load better-sqlite3 fail with reason='better_sqlite3_not_loaded'.
Fix: emit three additional candidates.
1. From MCODE_CMD (when it IS a real path), try BOTH the npm-style
layout (<root>/bin/mcode → <root>/lib/node_modules/...) and the
flat layout (<root>/mcode → <root>/node_modules/...). Round 5 only
emitted the flat one.
2. Always emit <home>/.minimax-code/lib/node_modules/... as an
unconditional standard-install candidate. This is where mcode
actually ships its bundled deps on macOS dev installs
(verified: 'find ~/.minimax-code' shows
lib/node_modules/@minimax-ai/code/node_modules/better-sqlite3).
The function is now parameterized as
_getBetterSqlite3Candidates({ mcodeCmd, home } = {}) so tests
can simulate any install layout without env mutation.
Tests added:
- standard ~/.minimax-code/lib/node_modules/... is always tried
- mcode at <root>/bin/mcode emits BOTH npm-style and flat candidates
Test results in modacker env (real mcode install, no env override):
Before round 6: 387 pass / 4 fail / 2 skipped (all 4 fails =
better_sqlite3_not_loaded on the 2 happy-path integration tests
in lib-db.test.js and 2 in sessions.test.js)
After round 6: 391 pass / 0 fail / 2 skipped — all integration
tests now find and load better-sqlite3 via the standard-install
candidate
Refs: MiniMax-AI#16 round 5 follow-up, modacker env verification
5 个独立修复 + 1 个外部 key 源特性,全部端到端验证 + 测试覆盖。
=== Core bug fixes ===
1. SSE clobber wiped quotaEnabled on every push
- server/lib/state-bus.js: 3 snapshot builders + pushOnlineCount now
include quotaEnabled / hasTokenPlanKey / tokenPlanApiKeyMasked
- server/routes/state.js: handleEvents (SSE first push) + handleState
(GET /api/state fallback) carry the same fields
- public/app/state.js: SSE onmessage defensively preserves these
three (mirrors the askUserAnswers / mcodeSessions pattern)
- Root cause was the appearance-card '显示套餐用量' toggle looking
like a no-op: server's snapshot was missing the field, so the
next SSE onmessage state=JSON.parse(ev.data) replaced local
state.quotaEnabled with undefined, btn.classList.toggle re-added
usage-hidden, button hid. All pushed on every /api/settings POST.
2. 4 missing imports in events.js (closeApiKeyModal / openApiKeyModal /
setLeftOpen / setRightOpen) — ReferenceError at attachEvents init.
Previously the modal handlers crashed the whole JS bootstrap.
3. usage.js parser read wrong field path + typo
- Read data?.current_interval_remaining_percent (top level) which
is always undefined. Real API nests it under
model_remains[i].current_interval_remaining_percent.
- Used 'pct' suffix instead of 'percent':
data?.current_weekly_remaining_pct (always undefined)
correct:
data?.current_weekly_remaining_percent
- Extracted to pure parseTokenPlanResponse(data, cs) for testability.
- Now also stores cs.usage.raw (8 KB cap) for future debugging.
- Real key 端到端验证: fiveHourPercent=25, weekly=51%,
fiveHourReset=1787864400, error=None, raw=990 bytes.
4. api-key-modal type=password made the whole page a 'credential form'
for Chrome autofill, so every text input on the page got email
autofill injected (including the search input).
- type=password → type=text + secret-input class
- CSS: -webkit-text-security: disc + monospace + letter-spacing
(visually a password box, semantically NOT a password field)
- This was the actual root cause of the stubborn autofill.
The other mitigations (readonly / autocomplete=off / data-1p-ignore)
were all bandaids; removing the page-level credential signal is
the real fix.
5. 5 <label class='lan-card-row-label'> had no associated form field
(DevTools a11y warning). Converted to <div> (they're row titles,
not form labels) and added explicit for= on each toggle's label.
=== Feature ===
6. Token Plan key can now be injected via env or file (priority chain
env > file > settings.json), per user request.
- env: MCODE_WEBUI_TOKEN_PLAN_KEY (env always wins, like the
existing process.env.TOKEN pattern for the LAN auth token)
- file: ~/.minimax/credentials/token-plan.json (raw or
{"key":"..."} JSON), path overridable via
MCODE_WEBUI_TOKEN_PLAN_KEY_FILE
- When env or file provides a key, quotaEnabled auto-enables so
the user doesn't have to flip the toggle.
- Webui surfaces the source ('env' / 'file' / 'settings') in the
popover + modal, hides the 'delete' button when the key is
external (operator must unset at the source).
=== i18n / UX ===
- 启用 → 显示套餐用量 (and synced en 'Enabled' → 'Show usage')
- New strings: quota_source_env / quota_source_file / delete disabled
hint / input placeholder hints for external sources
- Help text: was '关闭后,按钮仍显示,但点开是降级提示' (old behavior),
now '关闭后,套餐用量按钮在主界面消失' (matches current behavior)
=== Tests ===
- 3 new quota-field tests in test/state-bus.test.js (per-cid / broadcast /
pushOnlineCount all carry the 3 quota fields, setQuotaEnabled(false)
clears them in the next push)
- 6 new external-key-source tests in test/state-bus.test.js (settings /
file / env / live downgrade chain / broadcast / empty state)
- 7 new parser tests in test/usage.test.js (real API fixture pins
exact field names + 'general' model picking + end_time ms→s)
- test/_setup.js mock: mirrors real priority chain in getTokenPlanApiKey
+ getTokenPlanApiKeySource + maskTokenPlanKey so tests don't lie
Full suite: 409 pass / 0 fail / 2 skipped (was 393 / 0 / 2 → +16 tests).
Files: 13 modified + 1 new test + .gitignore (drop webui runtime
artifacts .server.err / .webui-sessions.json). Excluded from this
commit: 2 docs (REVIEW-SiHankor-baselines + BORROW-dsh) — modacker
perspective work product, not part of the PR.
Co-authored-by: mavis <noreply@example.com>
…enshots v2.0.0 supersedes MiniMax-AI#16 (28-day-stale v1.0.0 marketplace PR) and closes all 4 CHANGES_REQUESTED findings from @hetaoBackend by structural rewrite rather than patch. 19 implementation leases (A:4 docs / B:5 core / C:8 extras / D:3 tests) plus §6 reconcile. Industrial properties delivered: 1. Verifiability — append-only NDJSON event stream + SHA-256 hash chain (B01) 2. Observability — independent anomaly SSE channel + bell-icon data feed (B02) 3. Portability — zero npm deps maintained; all in Node 22 stdlib 4. Governability — per-request authorize() Promise, 5-min fail-closed (B03) 5. Reproducibility — pinned package-lock + CycloneDX 1.5 SBOM (C02) 6. Testability — Node 22/24 × macOS/Linux/Windows matrix (C02) 7. Discoverability — 13 plugin.json capabilities, each with description (B05) 8. Math-grounded — every subsystem cites a sih-math theorem (A02) 9. Single source — check-docs-alignment.mjs exits 0 in CI (B05 + §6 reconcile) New on top of v1.x: virtual chat list (C04), cross-workspace session search (C05), session export to MD/JSON (C06), quota forecast (C07), token-onboarding modal replacing stdout 14-line ASCII box (C08), per-{IP,token} rate limiting + HTTPS reverse-proxy docs (C03). Closes MiniMax-AI#16 (will auto-close on merge via the new PR's `Closes MiniMax-AI#16` directive — modacker will file that PR from this feat/v2-refactor branch). Test evidence: - 832 tests / 826 pass / 4 fail / 2 skipped - 4 fail = pre-existing better-sqlite3 NODE_MODULE_VERSION ABI drift - npm run check exit 0 (all 6 drift groups green) - coverage 92.93% lines / 82.99% branches / 100% functions - npm audit 0 vulnerabilities - CycloneDX SBOM 115 components
…load + docs Addresses 5 findings from V01 hetaoBackend-style review on commit 609bf05: F01 — alerts.js bugfix + regression tests • Finding 1 (pushRing dedupIndex stale after ring wrap): _dedupIndex now stores {alert, ts} instead of {idx, ts}. pushAlert uses existing.alert reference (live) instead of _buffer[existing.idx] (stale). Verified: re-push of m50 after ring wrap correctly increments m50.count to 2 with m55.count unchanged at 1. • Finding 2 (audit write drops all alert fields): tryWriteEvent now wraps alert fields inside payload:{...} per events.js contract. Verified: events.ndjson line data={id,msg,count,sessionId,data:{exitCode:1}} • +2 regression tests in test/lib-alerts.test.js (20/20 pass, was 18/18) F02 — docs fix + SECURITY-NOTES disclosure • Finding 3: README.zh-CN.md now has 5 screenshot references matching README.md structure (界面预览 section between 功能 and 快速开始) • Finding 5: SECURITY-NOTES.md new top-level section 'CORS / 跨源 资源共享' between §2 and §3, with verbatim router.js:346-348 quote, threat model, cross-origin CSRF risk, and 5-tier mitigations F03 mechanical • package.json: version 1.0.0 → 2.0.0 (matches plugin.json@2.0.0) • package.json: dead npm scripts removed (validate:plugin, verify → referenced non-existent scripts) • sbom.cdx.json: regenerated to reflect new version + timestamp Validation: npm test 828/834 pass (4 better-sqlite3 ABI fails unchanged from baseline); npm run check exit 0; both bug repros return correct output; grep _buffer[existing.idx] → 0 matches; grep ^\s*id: alert.id → 0 matches
…ass, 20 alerts tests) After F01 added 2 regression tests in lib-alerts.test.js, the full suite is now 828/834 pass (was 826) and lib-alerts is 20/20 (was 18). PR_DESCRIPTION.md updated to reflect the post-F01 numbers without re-running the v2 review loop.
…+ remove BORROW TODOs
Two marketplace CI blockers surfaced by siinfer remote CI run:
G01 — clean plugins/Wzdhehe/.webui-uploads/
• Empty dir created by mcode-webui server's default MCODE_WEBUI_UPLOAD_DIR
at startup. Marketplace validate.mjs flags it as 'invalid Plugin
directory .webui-uploads'. Removed on both local and siinfer copy.
G02 — replace TODO markers in docs/BORROW-harness-v2-2026-09-20.md
• Line 34 'closes one TODO in plugin.json' → 'closes one outstanding entry
in plugin.json' (avoids \bTODO\b trigger)
• Line 327 '(or webui-instructions.md — file name is a TODO; pick one in
PR)' → '(uppercase, conventional — chosen over the lowercase variant
webui-instructions.md)' (concrete filename decision: WEBUI.md)
sbom.cdx.json regenerated to keep version/timestamp in sync.
… bootstrap PORT pin Five tests that failed on siinfer (Ubuntu 24.04 + Node 24) but passed on Mac (Node 26) all had **environmental, not version-related** root causes. Production fix: server/lib/mavis-usage.js refactored to prefer node:sqlite builtin (Node 22.5+, already covered by engines >=22.19) over spawning the sqlite3 CLI binary. siinfer Ubuntu runner has libsqlite3-0 but not the sqlite3 CLI package, so the spawn path returned ENOENT → resolve(null) → test asserts failed. node:sqlite is sync, ~10× faster (0.15ms vs 5ms per query on Mac), cross-platform, no external dep — preserves zero-init stance. Bootstrap fix: test/server-startup.test.js now sets PORT=18082 via spawn env (was 8080, conflicted with orphaned LISTEN socket on runner). Verified on siinfer (after manual file sync): fail 7 → 2. Remaining 2 are pre-existing better-sqlite3 ABI mismatches (CAPABILITIES.md §CI matrix documents as env-specific), out of G03 scope. Verified on Mac (Node 26.7.0): 831/837 pass (no regression from baseline 828/834). 3 new regression tests added: - mavis-usage: node:sqlite resolves against sqlite3-less env - mavis-usage: getMavisTokenUsageModel direct unit tests ×2
…EVENTS to /tmp
Recurring issue: server.js mkdirSync(UPLOAD_DIR) creates .webui-uploads/
in MCODE_ROOT (i.e. plugins/Wzdhehe/). Bootstrap test (G03) starts
server.js → directory reappears after every test run, breaks marketplace
validate.mjs 'invalid Plugin directory' check on tar+siinfer CI.
Patch: bootstrap test spawns server.js with explicit env overrides pointing
to /tmp/mcode-webui-test-{uploads,settings.json,events.ndjson}. Tested
locally: 837 pass, 4 pre-existing sqlite3 ABI fails unchanged; no
.webui-uploads/ created in plugins/Wzdhehe/.
…eQL fixes, root-gate compatibility Responds to the three inline CodeQL alerts plus a DSH-benchmark rigor audit: - auth.js: disjoint-class Bearer regex (linear match); main.js + render.js: DOM construction + textContent instead of HTML string reinterpretation; mcode-exec.js: cmd.exe trampoline removed — local zero-dep resolver spawns the node entry directly, fail-closed at every step; router.js: tainted console template moved to printf arg form, name-literal match sink removed. - events.js append now throws (fail-closed audit, no truncating writes); write-ahead intent/outcome events at every destructive surface; the authorize() test-mode auto-approve branch is gone — tests drive real decisions via withDecisions/decideNextAuthorization. - routes/chat.js imports the gate-bearing lib/slash.js shell (the B03 gate and audit were dead code in production); wiring proven by subprocess integration tests incl. a mutation check. - 23 module-mocked suites moved test/ -> checks/*.check.mjs: t.mock.module needs --experimental-test-module-mocks through Node 26 and the marketplace root gate runs flagless node --test with directory-rule discovery — the flagless subset (537 tests) now passes with zero mock errors. - CI honesty: the never-triggering plugin-level workflow is deleted (GitHub only reads repo-root workflows); CI.md documents the real gates; dead lint/format scripts and never-used devDeps removed (SBOM 115 -> 52); 52 committed coverage tmp files dropped; test isolation leaks (stray .webui-uploads/.webui-sessions in the plugin tree) fixed via env redirects. - Evidence: dual-mode suites 929/923 and 537/535 (fails are pre-existing local-env better-sqlite3 ABI, pass on CI), check-docs-alignment green, root validate green, fork preview runs for CodeQL/Windows.
…n Windows
checks/lib-authorize.check.mjs went whole-file red on windows-latest
Node 22 (fork preview run 35493384574): the timeout test awaits an
authorize() promise that is resolved solely by its unref()'d timeout
timer, so with no other ref'd handles the event loop drained before
the 25 ms timer fired ('Promise resolution is still pending but the
event loop has already resolved'); the rest of the file fell to
cancelledByParent. POSIX only passed on IO/scheduling noise.
Fix: a REF'd 5 s watchdog holds the event loop across the await and
is cleared in a finally as soon as authorize settles. Liveness only —
zero assertion change (decidedBy:'timeout' / fail-closed semantics
verbatim).
Swept the rest of checks/ for the same direct-await-on-unref'd-timer
shape: zero further hits (state-bus throttle tests await self-ref'd
sleep() windows; alerts heartbeat and chat 2 s force-kill are never
awaited; all other authorize() consumers go through withDecisions).
…rain Fork preview run 35493902383 (windows-latest, Node 22) failed the whole checks/routes-export.check.mjs file with 'Promise resolution is still pending but the event loop has already resolved' + cancelledByParent: mock unit tests drive route handlers with zero real IO, so while fn() awaits authorize() the 2ms poll interval was the only ref'd handle in the loop — unref'ing it let the loop drain before _decideForTests could fire (POSIX passed only on incidental IO noise). Same fix shape as lib-authorize's REF'd watchdog (run 35493384574). - remove poll.unref(); interval stays REF'd for the whole fn() window - add 5s safety self-clear: clear the interval + reject if fn() never settles, so a broken test fails fast instead of hanging the run - decision-completion path keeps clearInterval semantics (finally) - liveness only: zero assertion or production-code change
…x/Node 24 router-boot hang (U4)
Repro evidence (siinfer, Ubuntu 24.04 / Node v24.21.0, mcode absent):
- timeout 60 node --test test/integration/router-boot.test.js hung
permanently after test 2; killed at 60s with "Promise resolution is
still pending but the event loop has already resolved" (/tmp/rb-repro.log).
- Standalone bisect (no node:test): spawn real server.js, GET /api/state
-> no response within 10s; /api/health and 404 path respond in ~100ms.
- Micro-repro: McodeAcpClient.start() neither resolves nor rejects on
spawn ENOENT — Node 24 fires error+close but NOT exit for spawn
failures, and pending requests were rejected only in the exit handler.
Root-cause chain: handleState -> getMcodeSessionsForWorkspace ->
getMcodeAcpClient -> start() -> request("initialize") pending forever ->
response never sent -> test httpRequest (no timeout) hangs -> spawned
server child keeps the event loop alive. Local macOS runs green only
because ~/.minimax-code/bin/mcode is in PATH — environmental-noise green.
Fix (settlement guarantee — waiters must not depend on peer or
environment liveness):
- acp.mjs: reject all pending on child "error" and "close" (idempotent
drain helper; "exit" alone misses spawn failures). Guard the error
re-emit with listenerCount — bare emit("error") throws Unhandled
"error" event in embedders without a global handler; the server's
uncaughtException logger swallowed it into a live hang.
- router-boot.test.js httpRequest: 10s timeout bail-out (was none).
- _setup.js decideNextAuthorization: bail-out timer now covers the
decision POST phase too (previously cleared on frame arrival).
Runs:
- siinfer: timeout 60 node --test router-boot.test.js -> 14/14 pass,
exit 0, ~4.8s. router-boot/sse-channel/event-chain/chat-wiring all
green under timeout 120 in both plain and module-mocks modes, exit 0.
- local (macOS, Node v26.7.0): mocks full suite 929 tests, 923 pass,
4 fail (pre-existing better-sqlite3 NODE_MODULE_VERSION ABI); plain
unit suite 493 tests, 491 pass, 2 fail (same pre-existing ABI).
…mptions Windows-latest fork-preview run 35495306680 left ~26 failures, all environment/platform assumptions, none production defects (macOS and ubuntu-latest stay green). Honest gating per the real preconditions; zero assertion weakening anywhere the environment genuinely provides them: - lib-db.test.js / sessions.check.mjs: the sqlite3-fixture suites now gate on BOTH a working sqlite3 CLI (spawnSync --version probe via config.SQLITE3_BIN) AND a truly loadable better-sqlite3 probed through db.js's own resolver. Truthiness of getMcodeBetterSqlite3() is not enough — the package require()s cleanly on ABI mismatch and only new Database() throws — so the gate constructs a :memory: database. Skip reason names the missing precondition. - lib-db-resolver(.test.js / -c01.test.js): 10 POSIX forward-slash literal expectations rewritten to mirror the resolver's own host path.join construction (plus a segment-tail comparison for the PATH-placeholder filter) — assertions now run on every platform. - lib-events.test.js: chmod-on-directory fail-closed test skips on win32 (chmod lacks write-permission semantics there); POSIX runs it in full. - lib-mcode-exec.test.js: POSIX bare-name PATH fixture joins entries with node:path delimiter instead of a hardcoded ':' so the probe resolves on a win32 host too; no-entry-rewriting assertion kept. Local (macOS, ABI-mismatched better-sqlite3): full surface 929 tests/923 pass/4 fail -> 925/923/0 fail + 3 reason-carrying suite skips covering the 4 formerly-failing fixtures; flagless 537/535/2 fail -> 535/535/0 fail + 2 suite skips; check-docs-alignment exit 0. Refs: fork-preview run 35495306680 (windows-latest, Node 22).
|
Rigor batch landed at exact head CodeQL — all six alerts fixed, zero remaining. The three inline ones (polynomial Bearer regex → disjoint character classes; exception-text-as-HTML in main.js → DOM construction + Deeper findings the same pass uncovered:
Verification matrix (all at |
…lure surfacing Browser-level manual audit of every interactive surface found the v2 interaction breaks reported by users; five fixes land here: - needs_authorization SSE -> #auth-modal (queue + countdown + i18n) -> POST /api/auth/decision; authorization_decided closes cross-tab. Every gated action (delete/export/search//clear/token reset) was hanging 5min invisibly before this. - Session switch: title resolved from the walked cache (no ACP boot in the hot path) and transcript backfilled from the runtime DB (new server/lib/transcript.js with v2 data_json probes; caps 400 lines / 200KB; fail-soft). Switching showed an empty chat before this. - Failed sends reset the thinking claim (chat fail path, handleStop zombie claim, resetContext on switch/create/new) and surface via the new alerts bell (#btn-alerts + popover) instead of an eternal spinner. - Usage button un-hidden for local operators; appearance click now toggles data-theme; i18n parity for workspace_* and mode_read keys. - lib-db-resolver-c01 not-loaded fixtures pinned per-tier (env/module/ resolver/home) so they stay deterministic on hosts where the bundled better-sqlite3 loads. Co-Authored-By: Claude Fable 4.5 <noreply@anthropic.com>
Windows preview CI (real windows-latest) failed the two checks added in 4d1f4a5 while macOS/Ubuntu stayed green: - alerts-theme static guards sliced marker comments containing literal \n out of raw readFileSync output — never matches a CRLF checkout. Sources are now \r\n-normalized at read time. - routes-sessions-switch backfill tests were green locally only because this dev machine happens to have a real ~/.minimax runtime-state. sqlite; the existsSync gate in readMcodeTranscript read the machine's home, so a clean runner got mcode_db_not_found and zero rows. The check now pins MCODE_RUNTIME_DB to a scratch file before first SUT import (config.js evaluates the env at module load). Co-Authored-By: Claude Fable 4.5 <noreply@anthropic.com>
Interaction audit round — every clickable surface, by handWe reproduced the "clicking a session does nothing" report in a real browser against a 1000+-session workspace and then walked every interactive surface (switch/new/delete/search/slash/send/upload/theme/language/usage/export). Findings and fixes, in 4d1f4a5 + 7b4aae8: The big one — the authorize gate had no UI half. Session switch showed an empty chat. Switching to an mcode session created a wrapper with Failed sends were invisible. A broken/missing CLI produced an eternal spinner. Now the thinking claim resets on every terminal path (failed send, stop, switch/create/new via Smaller: usage button was zero-sized for local operators; the appearance button had no observable effect; five i18n keys leaked raw ( Verification: browser matrix re-run by hand (approve/deny paths, queue drain, history round-trips, regressions on search/slash/language); local suites 1034 tests 0 fail; siinfer Ubuntu authoritative gate 671/0 (no allowlist); fork preview on real windows-latest green (codeql + windows) — which caught two check-robustness gaps (CRLF marker slicing; a fixture that was only green because the dev machine happened to have a real runtime DB), both fixed in 7b4aae8. |
hetaoBackend
left a comment
There was a problem hiding this comment.
Request changes for exact current head 7b4aae80fc3ff6da4dac600b2c2872cd3a4a33d9.
The old #16 database-precedence and real-delete fixtures are substantially improved, but this new WebUI still exposes high-impact host capabilities with unsafe browser/network boundaries:
- Wildcard CORS combines with the local-request token bypass.
server/router.js:344-348sendsAccess-Control-Allow-Origin: *;server/lib/auth.js:119-126accepts local requests without a token, andserver/lib/lan.js:19-27classifies loopback/local addresses as local. A malicious page can target127.0.0.1:8080, receive the local bypass, and read responses.GET /api/settingshas no Origin gate (server/routes/settings.js:55-57) andserver/lib/settings.js:826-840,873returnslanUrlWithTokeneven after the token is acknowledged. Replace wildcard CORS with a trusted-origin policy, enforce browser Origin/CSRF boundaries, and stop returning a long-lived token-bearing URL. - The high-privilege server still binds
0.0.0.0by default.server/lib/config.js:47-54andserver/lib/settings.js:45-50default to LAN exposure, writable mode, and enabled agent/filesystem/session controls. Default to loopback; make LAN sharing an explicit, clearly disclosed opt-in. - Uploads are unbounded.
server/lib/upload.js:47-65buffers the entire multipart body in memory and synchronously writes it;server/routes/upload.js:38-60imposes no request/file/quota limit. Add bounded streaming and storage quotas. - Session deletion reports success after arbitrary SQL/IO errors.
server/lib/db.js:347-357catches every per-table error as if the table were merely absent, and:386still returns success. Ignore only a confirmed missing-table error; rollback and fail on lock, prepare/run, schema, or IO failures, and define deleted/already-absent/unsupported-schema outcomes. - Workspace and persistence boundaries remain unsafe.
server/lib/workspace.js:43-51,77-106accepts arbitrary absolute directories without allowed roots or realpath/symlink containment.server/lib/sessions.js:10-22rewrites JSON non-atomically without locking and treats parse corruption as an empty database, enabling lost updates/data disappearance.
Positive evidence: direct CLI spawn, authorization-gate wiring, write-ahead audit, database existence-before-driver loading, and real delete/missing-table fixtures are improved; local root tests were 673/673 and canonical Ubuntu/CodeQL checks are green. The issues above remain independently blocking. [code]smith is skipped and was not used as evidence.
…bind (PR MiniMax-AI#55 review points 1+2) Review point 1 — "Wildcard CORS combines with the local-request token bypass": router.js sent Access-Control-Allow-Origin: * on every response while auth.js#isRequestAuthorized + lan.js#isLocalRequest let loopback sockets bypass the token, so any web page could target 127.0.0.1:8080, receive the local bypass, and read responses (incl. GET /api/settings' lanUrlWithToken, which stayed token-bearing even after acknowledgment). Fix mapping: - router.js Gate 1: wildcard replaced with trusted-origin reflection. Only the server's own serving origins (loopback/localhost/[::1] + the LAN address while LAN sharing is on) plus the explicit trustedOrigins settings allowlist get CORS headers, reflected verbatim (never *), with Vary: Origin. Untrusted/absent Origin gets zero Access-Control-* headers, preflight OPTIONS included. - router.js Gate 1b (new, before all other gates): mutating requests carrying an Origin that is not trusted are 403'd. Crucially NOT exempted by socket locality — the loopback token bypass never doubles as a browser cross-origin exemption (the exact combination hole). Origin-less clients (curl/MCP/CLI) pass through unchanged. - settings.js: lanUrlWithToken is now a first-run bootstrap surface only — omitted entirely from GET /api/settings once the token is acknowledged (frontend falls back to bare lanUrl). Rotation re-arms the one-time surface. New persisted trustedOrigins allowlist with strict sanitize (http(s) origin shape, 16x200 caps, fail-closed). - lan.js: pure origin helpers (normalizeOriginHeader / buildTrustedOrigins / isLoopbackHost); socket identity and browser origin are now two distinct trust dimensions. - auth.js: doc note only — the local bypass is socket identity, the browser boundary lives in router.js Gate 1b. Review point 2 — "The high-privilege server still binds 0.0.0.0 by default": config.js HOST defaulted to 0.0.0.0 (v0.5.ao), settings.js defaulted to LAN exposure. Fix mapping: - config.js: default bind is loopback 127.0.0.1 via resolveBindHost(): explicit env HOST (trimmed) > persisted lanBind opt-in > loopback. Explicit configs (env / settings file) keep winning — upgrading users who opted in explicitly are undisturbed; implicit-default users land on the new secure default, as the review demands. - settings.js: new persisted lanBind opt-in (POST /api/settings), applied at next boot; snapshot discloses the exposure surface explicitly (lanBind / bindHost / lanExposed / bindRestartPending / bilingual lanExposureNotice). Tests (suite 1034 -> 1084, zero regressions, exit 0): - checks/router-origin-gate.check.mjs: malicious-page simulation — evil-origin GET gets no CORS headers; evil-origin POST is 403 even from a 127.0.0.1 socket; Origin: null and lookalike origins rejected; trusted origin reflected + passes; curl-shaped requests unaffected. - checks/settings-sec-net.check.mjs: lanUrlWithToken omitted after acknowledgment, re-armed by rotation; lanBind disclosure fields; trustedOrigins sanitize + route 400 fail-closed. - test/lib-lan-origins.test.js: trust-set membership pins (lookalikes, scheme/port mismatches, LAN gate, default-port elision). - test/lib-config-bindhost.test.js: resolveBindHost pure rule + HOST default. - test/integration/default-bind.test.js: live boot proves 127.0.0.1 default, 0.0.0.0 via persisted lanBind, env HOST keeps winning. - test/router-cors.test.js + test/integration/router-boot.test.js: the two wildcard-pinning tests were pinning the condemned behavior and now pin the trusted-origin policy instead.
PR MiniMax-AI#55 review point 3 — "Uploads are unbounded": server/lib/upload.js:47-65 buffered the entire multipart body in memory and synchronously wrote it; server/routes/upload.js:38-60 imposed no request/file/quota limit. - lib/upload.js: rewrite the multipart parser as a bounded streaming state machine (Transform). File bytes stream chunk by chunk into an eagerly-opened temp file and are rename()d to the final name only after the closing boundary + clean stream end; resident memory is O(chunk + boundary length), never O(body). - Three limits enforced DURING the stream (rejection at the (N+1)-th byte, never read-then-decide): request total 50 MiB, single file 25 MiB, upload-dir quota 200 MiB — overridable via MCODE_WEBUI_UPLOAD_MAX_REQUEST / MCODE_WEBUI_UPLOAD_MAX_FILE / MCODE_WEBUI_UPLOAD_QUOTA, following the existing env-knob convention (config.js untouched; limits resolve lazily per call, events.js pattern). Rationale documented inline. - Boundary candidates verified against the following bytes (RFC 2046): file content containing "\r\n--<boundary>X" no longer terminates a part. Part header blocks capped at 16 KiB, padding at 64 bytes. - Any abort/failure unlinks the temp file (eager fd + close-time backstop unlink) — no half-written artifact survives, including a client that tears the socket mid-upload. Abort leaves the request unpiped+paused (bounded), response first, teardown after. - routes/upload.js: limit rejections map to 413 with the failing knob named in the error and code echoed in JSON; malformed/abort map to 400 (previously everything was 500). 413 sets Connection: close and runs a post-response discarding drain so the TCP RST from an unconsumed body cannot overtake the response. upload.create audit event now carries the file size (fills the null-size TODO). Tests (+29, suite 1034 -> 1063, all green): - test/lib-upload.test.js (22): happy path byte-exactness, generated names, chunk-split boundaries + boundary-like content, first-file- only semantics, malformed/truncated/no-file rejections, mid-stream abort consumption bounds (request/file/quota), quota upfront + exact-fit edges, cleanup hygiene after every failure. - test/integration/upload-limits.test.js (7): real server.js stack — 200 happy path with size, 413 mid-stream with client write stall evidence, 413 file-limit, quota exhaustion with earlier files intact, non-multipart 400 pinned, no-file-part 400, client-abort cleanup with server still healthy. Files: server/lib/upload.js, server/routes/upload.js, test/lib-upload.test.js, test/integration/upload-limits.test.js
…PR#55 review pt 4) Review (hetaoBackend, CHANGES_REQUESTED on MiniMax-AI#55 @ 7b4aae8): > Session deletion reports success after arbitrary SQL/IO errors. > server/lib/db.js:347-357 catches every per-table error as if the > table were merely absent, and :386 still returns success. Ignore > only a confirmed missing-table error; rollback and fail on lock, > prepare/run, schema, or IO failures, and define > deleted/already-absent/unsupported-schema outcomes. Fix (server/lib/db.js): - per-table error CLASSIFICATION replaces the blanket catch: "no such table" is believed only when the schema catalog read on the same connection confirms the table is absent; "no such column: session_id" is confirmed via table_info() as unsupported schema; everything else (SQLITE_BUSY/LOCKED, prepare/run, schema, IO) rethrows - the real delete stays one explicit transaction; any non-absent error now throws out of the tx body so better-sqlite3 issues ROLLBACK — partial deletes never commit - explicit outcome enumeration: ok:true + outcome:"deleted" | "already_absent" (with totalRowsDeleted / tablesAbsent), and ok:false + reason:"unsupported_schema" (with table) | "db_error" (with code); the outcome also lands in the session.delete audit event. All three route callers embed mcodeDbDel verbatim in their JSON responses, so responses now carry the outcome too — no route change needed - dry-run preview applies the same classification: a preview can no longer fake success by silently undercounting Tests (test/lib-db-outcomes.test.js — real sqlite3 fixtures, same env-gating as lib-db.test.js): - deleted: row gone, outcome + audit parity asserted - already_absent: all tables missing (full tablesAbsent count) AND tables present with zero rows (other sid's row untouched) - unsupported_schema: keyless table -> ok:false with rollback proof (earlier-deleted row survives; no outcome audit event) and the dry-run surfaces the same failure - lock: concurrent BEGIN IMMEDIATE writer -> ok:false reason:"db_error" code SQLITE_BUSY, busy_timeout honored, row survives, clean retry after release succeeds Files: server/lib/db.js, test/lib-db-outcomes.test.js npm test: 1040 tests, 1038 pass, 0 fail, 2 skipped (pre-existing Windows-only skips), exit 0.
…on persistence PR MiniMax-AI#55 review point 5 (hetaoBackend CHANGES_REQUESTED): > 5. Workspace and persistence boundaries remain unsafe. > `server/lib/workspace.js:43-51,77-106` accepts arbitrary absolute > directories without allowed roots or realpath/symlink containment. > `server/lib/sessions.js:10-22` rewrites JSON non-atomically without > locking and treats parse corruption as an empty database, enabling > lost updates/data disappearance. Fix vs review, point by point: workspace.js — allowed roots + realpath containment: - New allowed-roots boundary: a candidate dir must resolve() then realpathSync (all symlinks resolved) inside an allowed root to be usable. Traversal (../) folds back at resolve(); symlink escape is exposed at realpath() — both hit the containment check and get an actionable error (lists the roots, names the env override). - Root source is a minimal face: env MCODE_WEBUI_WORKSPACE_ROOTS (path-delimiter separated; when set it REPLACES the default face so operators can narrow or widen). Default face keeps current behavior: homedir + configured DEFAULT_WORKSPACE + tmpdir. - handleWorkspaceChange: set/useTui/reset all pass through the gate; cs.workspace unchanged on rejection. - browseWorkspace: same boundary — listing only inside allowed roots; the no-path root view now exposes ONLY the allowed roots (previously POSIX enumerated "/" and Windows enumerated drive letters — an enumeration oracle). Response shapes stay compatible (POSIX dir "/", Windows dir:null + roots; the frontend already renders data.roots). Parent navigation stops at the boundary (parent nulled above a root). - Known residual, documented in-source: stored dir keeps the resolve() form (not realpath-normalized) for behavior/test compatibility. sessions.js — atomic, serialized, corruption-explicit persistence: - Atomic write: same-dir tmp file + renameSync; the main file is never a half-written JSON. Failure paths clean up the tmp file. - Write serialization: server.js is a single process (no cluster/fork/ worker) and all fs calls here are synchronous — sync calls run to completion on the single-threaded loop, so two saveSessions cannot interleave at the syscall level (documented as the in-process lock equivalent; no cross-process writer exists for this DB). - Corruption is explicit, never a silent empty store: parse failure (or non-array root) quarantines the exact corrupted bytes to SESSIONS_DB.corrupted-<ts> (original file left untouched), logs an actionable error (quarantine path + restore instructions), and only then returns [] to keep the caller contract. The old corrupted -> [] -> save-wipes-data disappearance chain is cut; the quarantine copy survives any subsequent save. Repeat loads of the same corrupted state don't re-quarantine or re-log ((mtime,size) memo; parsing itself is never skipped). - cleanupEmptyDefaultSessions now routes through loadSessions(), so it can never overwrite a quarantined corrupted DB. Tests (zero-dep, node:test): - test/lib-workspace-containment.test.js (13): default face contents, env replaces/skips/dedups; set inside ok (zero regression), outside rejected with actionable error + cs untouched; ../ traversal rejected; symlink escape rejected via realpath (error shows resolved target); benign in-root symlink ok; reset gated both ways; browse inside/outside/symlink-escape; root view exposes only allowed roots; parent nulled at boundary. - test/lib-sessions-persist.test.js (12): roundtrip + no .tmp leftovers; BOM regression pin; corrupted -> [] + bytes intact + single quarantine + single error log; non-array root = corruption; corrupted -> fresh save keeps old bytes in quarantine; cleanup never overwrites corrupted DB; circular-ref stringify failure and read-only-dir tmp-write failure leave DB untouched with no tmp leftovers; 50 interleaved load-modify-save units all committed, every intermediate read parses. npm test: 1059 tests (was 1034), 1057 pass, 2 platform-gated skips, 0 fail, exit 0. No CLI/curl/MCP-relevant behavior touched (browser-face boundary only; errors are honest ok:false, no fake success). Files: - plugins/Wzdhehe/mcode-webui/server/lib/workspace.js - plugins/Wzdhehe/mcode-webui/server/lib/sessions.js - plugins/Wzdhehe/mcode-webui/test/lib-workspace-containment.test.js (new) - plugins/Wzdhehe/mcode-webui/test/lib-sessions-persist.test.js (new)
…sters Documentation-only sync. The four code clusters (webui/sec-net, webui/sec-upload, webui/sec-db, webui/sec-ws) landed the PR MiniMax-AI#55 review fixes; plugin.json names references/SECURITY-NOTES.md as the single source of truth for security disclosure (red-line 7), and it plus the API / reverse-proxy docs still described the pre-fix behavior (wildcard CORS, 0.0.0.0 default bind). This aligns all three to the accepted implementations — eight facts, verified against the four cluster branches: 1. CORS: wildcard removed; verbatim trusted-origin reflection only (own serving origins + LAN origin while sharing on + explicit trustedOrigins allowlist). Untrusted/absent Origin gets zero Access-Control-* headers, preflight consistent with actuals, Vary: Origin on every response. 2. Origin/CSRF gate: mutating request with present-but-untrusted Origin is 403'd before every other gate, no loopback exemption; Origin-less clients (curl/MCP/CLI) unaffected. 3. lanUrlWithToken is a first-run bootstrap surface: omitted after token acknowledgment (UI falls back to bare lanUrl), re-issued once per rotation. 4. Default bind 127.0.0.1 (resolveBindHost: env HOST > persisted lanBind > loopback); LAN exposure is explicit opt-in, disclosed via lanBind/bindHost/lanExposed/bindRestartPending/ lanExposureNotice in the settings snapshot. 5. Uploads: bounded streaming, three mid-stream limits (50MiB request / 25MiB file / 200MiB quota; MCODE_WEBUI_UPLOAD_MAX_* env overrides), 413 with code + Connection: close, malformed 400, no half-written artifacts. 6. Session deletion: explicit outcomes (deleted / already_absent / unsupported_schema / db_error) with transaction rollback and audit-carried outcome; fake success forbidden. 7. Workspace containment: resolve + realpath within allowed roots (default home + default workspace + tmp; MCODE_WEBUI_WORKSPACE_ ROOTS replaces the set); browse enumerates allowed roots only. 8. Session persistence: atomic tmp+rename writes, single-process synchronous serialization, corruption quarantined to SESSIONS_DB.corrupted-<ts> with the original file untouched. Files changed (docs only, no code or tests): - references/SECURITY-NOTES.md — TL;DR, §1 bind table + rationale, §2.3 token URL, CORS section rewritten (policy + gate + history), §3.1 outcome table, §3.2 upload limits, §3.3, §4 + new §4.1/§4.2 - docs/API.md — settings snapshot + settable fields (lanBind, trustedOrigins, one-time lanUrlWithToken, 400 on invalid batches), upload 413/400 error shapes + env knobs + response size field, session-delete outcome shapes, workspace browse containment, 413 in the error-status list - docs/HTTPS-REVERSE-PROXY.md — §1 bind row, new §2.1 trustedOrigins guidance for proxy-fronted origins, nginx upstream comment, verification steps 5-6 (CORS reflection + 403 gate), two troubleshooting rows Source of truth: PR MiniMax-AI#55 review points 1-5 + the accepted cluster implementations (webui/sec-net f0862e1, webui/sec-upload d923be8, webui/sec-db 9b70cad, webui/sec-ws d32348f). npm test green (1032 pass / 0 fail / 2 platform-gated skips); npm run check (check-docs-alignment) green.
…ult bind Follow-up to 598f0e7 (narrow cluster): the security-fix clusters changed the default bind to loopback, and the manifest + README still declared the old 0.0.0.0 behavior — a drift this batch itself introduced, so the disclosure surfaces must move together. plugin.json: - config.HOST default 0.0.0.0 → 127.0.0.1; description now states the loopback default and the explicit LAN opt-in (HOST env or the persisted lanBind setting, restart-effective) - securityNotes: "network bind 0.0.0.0" → loopback default with explicit LAN opt-in; also names trusted-origin CORS, bounded upload, and workspace containment; still points to references/SECURITY-NOTES.md as the single source of truth (red-line 7) - lan-sharing capability: rewritten to the opt-in semantics (loopback default, HOST/lanBind opt-in, lanBroadcast runtime gate, exposure disclosed via lanExposed/bindRestartPending/lanExposureNotice) - configHints audited against the four cluster implementations: no contradicting values found in PORT / TOKEN / MCODE_MODEL / MCODE_CMD / MCODE_WEBUI_UPLOAD_DIR / DEBUG_INJECT (all still match server/lib/config.js). Added the four knobs the clusters introduced: MCODE_WEBUI_UPLOAD_MAX_REQUEST (52428800 = 50 MiB), MCODE_WEBUI_UPLOAD_MAX_FILE (26214400 = 25 MiB), MCODE_WEBUI_UPLOAD_QUOTA (209715200 = 200 MiB), and MCODE_WEBUI_WORKSPACE_ROOTS (unset = home + default workspace + system tmp; setting it fully replaces the set) README.md: - env table: HOST default → 127.0.0.1 with the opt-in note; added the four new rows above with the same names/defaults as upload.js and workspace.js - security key points: "Default binds 0.0.0.0" replaced with the loopback default + LAN opt-in + trusted-origin CORS pointer - capabilities table lan-sharing row aligned (same file, same drift) Source of truth: the accepted cluster implementations (webui/sec-net f0862e1, webui/sec-upload d923be8, webui/sec-db 9b70cad, webui/sec-ws d32348f; integrated upstream). npm test green (1032 pass / 0 fail / 2 platform-gated skips); npm run check (check-docs-alignment, includes plugin.json surface) green.
… gate)
The repo's test/checks split convention: test/*.test.js must be ZERO
mock (runnable by plain `node --test` — this is what the siinfer root
gate does, without --experimental-test-module-mocks); any test using
_setup.js setupMocks (t.mock.module) belongs in checks/*.check.mjs,
which only the plugin-level npm test discovers with the mocks flag.
test/lib-workspace-containment.test.js (from d32348f) used setupMocks
in its before() hook, so the flagless root gate blew up on it with
"TypeError: t.mock.module is not a function". Migrate the whole file:
- git mv test/lib-workspace-containment.test.js
-> checks/lib-workspace-containment.check.mjs
- only content change: _setup import path "./_setup.js" ->
"../test/_setup.js" (same reference form as every existing
checks/*.check.mjs); logic, assertions, and header untouched.
Verification (cwd = plugins/Wzdhehe/mcode-webui, bare commands):
- npm test: tests 1059 / pass 1057 / skipped 2 / fail 0, exit 0 —
total identical to pre-migration (count-neutral move; the file's 15
containment cases all still run, now via checks/*.check.mjs).
- Flagless face: node --test test/*.test.js test/integration/*.test.js
-> tests 568 / pass 568 / fail 0, exit 0. test/ no longer contains
any mock-using file.
lib-sessions-persist.test.js stays in test/ — verified zero-mock (its
only mock API is t.mock.method on console, which is stable and works
without the experimental flag).
…+ HOME isolation
Two integration-gate failures, both test-side; zero product-code
changes.
1. test/integration/default-bind.test.js — port race
Evidence (siinfer):
Error: no listening line within 4s. stdout: [webui] workspace:
homedir fallback=/home/moc
stderr: [uncaughtException] listen EADDRINUSE: address already
in use 0.0.0.0:19700
Cause: the three cases drew random ports from one 19700..19799 pool
and bootOnce resolved at the listening line right after SIGTERM —
on Linux the next case could bind while the dying listener still
held the socket (close is asynchronous; macOS timing hid it).
Fix: each case gets its own deterministic port (19701/19702/19703),
and bootOnce now tears the child down COMPLETELY before resolving:
SIGTERM, escalate to SIGKILL after 1.5s if close stalls, await the
exit event, then rm the tmp dir. Assertions unchanged. Five
consecutive solo runs: 3/3 pass, exit 0 each.
2. test/lib-settings.test.js — real-HOME isolation violation
Evidence (siinfer):
Error: ENOENT: no such file or directory, rename
'/home/moc/.mcode-webui/events.ndjson.tmp'
-> '/home/moc/.mcode-webui/events.ndjson'
Cause: settings.js setters append B01 write-ahead audit events via
lib/events.js, whose _eventsPath() lazily resolves the env knob
MCODE_WEBUI_EVENTS_PATH — this suite never set it, so appends went
to the real ~/.mcode-webui/events.ndjson (silent pollution where
the dir exists, ENOENT where it doesn't). Note the audit appends on
setReadOnly/rotateToken predate this branch (v2.0.0 rigor batch,
54af814); the gap was test isolation, fixed as such.
The isolation proof also caught a second leak in the same file:
persisting setters called outside the persistence describe
(rotateToken / setTokenAcknowledged) wrote the operator's REAL
settings.json (231 -> 276 bytes — the delta being this branch's
new lanBind/trustedOrigins fields).
Fix: module-scope env isolation for BOTH knobs —
MCODE_WEBUI_EVENTS_PATH and MCODE_WEBUI_SETTINGS_PATH point at a
per-suite mkdtemp'd file, restored + cleaned in a file-level after().
The persistence describe's own beforeEach/afterEach still
override-and-restore on top, so its fresh-file assertions are
unchanged. Env knob used: MCODE_WEBUI_EVENTS_PATH (events.js
_eventsPath lazy read — same knob checks/routes-settings.check.mjs
already uses).
Verification (cwd=plugin dir):
- npm test: exit 0, tests 1084 / pass 1082 / fail 0 / skipped 2
(the 2 skips are the pre-existing platform-gated ones).
- Isolation proof: `ls -la ~/.mcode-webui/` + shasum of every file
before vs after `node --test test/lib-settings.test.js` — byte
identical (HOME_FACE_UNCHANGED), suite 33/33 pass.
|
All five blocking points are addressed at the updated head ( 1. Wildcard CORS × local bypass. 2. Default exposure. Default bind is now 3. Uploads. Multipart parsing is a bounded streaming state machine (a 4. Session deletion. Per-table errors are classified instead of swallowed: 5. Workspace and persistence boundaries. Workspace selection now requires the candidate to resolve and Docs and manifest. Verification at Two smaller pre-existing drift items we found but did not touch (out of scope, flagging for awareness): the reverse-proxy doc suggests |
hetaoBackend
left a comment
There was a problem hiding this comment.
Request changes for exact current head 5f375b3074498f07b0ed3923eb355ab793f6dacd.
The previous CORS/LAN/upload/DB/workspace/session findings are substantially improved, but a new High authentication blocker remains in the documented reverse-proxy deployment:
docs/HTTPS-REVERSE-PROXY.md:26,111-205recommends a same-host proxy forwarding to127.0.0.1:8080. The backend sees the proxy upstream socket as local (server/lib/lan.js:19-27), andserver/lib/auth.js:127-135accepts local requests without a token.server/router.js:421-481then uses that local flag to bypass token, LAN, rate-limit and read-only gates. Any client reaching the public proxy can therefore invoke session, upload, settings, workspace and agent APIs without the WebUI token. Origin checks are not network authentication and programmatic clients can omit Origin. Define and enforce an explicit trusted-proxy contract with per-request authentication; do not infer original-client trust from the loopback upstream. Add an end-to-end negative test for the proxy topology.- The same reverse-proxy guide repeatedly instructs users to set
MCODE_WEBUI_TOKEN, but the implementation readsTOKEN(server/lib/config.js:85-89,server/lib/auth.js:58-73). Align the documented and implemented token contract. references/SECURITY-NOTES.md:329-334,391-401makes canonical claims that conflict with the implementation: runtime SQLite/session/settings/cwd persistence and destructive deletion do write user data, and the upload naming description does not matchserver/lib/upload.js:413-419. Correct the security disclosure before merge.
Root Ubuntu/CodeQL checks are green, but the plugin-specific checks are not clearly all executed by that root command. [code]smith is skipped and is not evidence.
PR 描述 — Mcode-webui 插件
本 PR 新增内容
plugins/Wzdhehe/mcode-webui/,符合 Agent Plugins 1.0 规范plugin.json(版本2.0.0)含 10 个白名单顶层字段skills/mcode-webui/SKILL.md含{name, description}frontmatterLICENSE(MIT)README.md(用户向快速上手 +docs/screenshots/5 张真实截图)references/SECURITY-NOTES.md(权威安全披露)docs/(ARCHITECTURE、API、CAPABILITIES、DEVELOPMENT、TROUBLESHOOTING、BORROW-harness-v2、MATH-skeleton-webui-v2、ANTI-PATTERNS-FIX-PLAN、
PROJECT-CHARTER-webui-v2、VERIFICATION-REPORT、HTTPS-REVERSE-PROXY、CI)
server/、public/、test/、scripts/(真实目录,与项目根保持同步;打包时按原样进入
dist/作为发布产物)package.json(与项目根一致,含setup:plugin、package:plugin、check、sbom脚本)v2.0.0 相对 v1.x 的变更(工业化)
本 PR supersede PR #16(v1.0.0 marketplace 提交,OPEN 28 天,@hetaoBackend 给了
4 条
CHANGES_REQUESTEDreview)。v2.0.0 用结构性改写代替 patch 方式逐条回应:
server/auth.js缺 v1.0.1 setter 导出setExpectedToken/setTokenAuthEnabled/markFirstRunNotified;isFirstRun读持久化状态server/lib/auth.js(B03 + §6.2 reconcile)server/lib/db.js:24-34硬编码better-sqlite3解析器MCODE_BETTER_SQLITE3环境变量 →MCODE_CMD反向回溯 →~/.mcode-webui/db-resolver.json→ 内置 fallback)server/lib/db.js(C01)SECURITY-NOTES.md的环境变量没在config.js导出;?token=与Authorization头不一致MCODE_WEBUI_UPLOAD_DIR/MCODE_WEBUI_SETTINGS_PATH/MCODE_BETTER_SQLITE3/DEBUG_INJECT);scripts/check-docs-alignment.mjs升级为 CI 闸门,断言 README + plugin + SECURITY-NOTES ↔ router.js + config.js 三向一致server/lib/config.js(§6.2)+scripts/check-docs-alignment.mjs(B05)plugins/Wzdhehe/mcode-webui/下每个文件都是新写或改动);前 3 条 finding 由结构性变更关掉;含Wzdhehe/Mcode-webui的 round-8 CSRF 修复在关上旧 review 之外,v2.0.0 还加了 9 项工业级属性,由 19 个实施 lease 支撑
(详见
docs/VERIFICATION-REPORT.md的头条摘要 +docs/PROJECT-CHARTER-webui-v2.md章程):server/lib/events.js(B01)+ 18 hook 点server/lib/alerts.js+server/routes/alerts.js(B02)authorize(action, ctx)Promise,默认 5 分钟 fail-closed,16 个 hook 点server/lib/authorize.js(B03)package-lock.json+ CycloneDX 1.5 SBOM + npm-audit 集成.github/workflows/ci.yml+scripts/gen-sbom.mjs(C02)node --test矩阵(Node 22 / Node 24 × macOS / Linux / Windows).github/workflows/ci.yml(C02)plugin.jsoncapability 都带description(204-286 字符);CONTRIBUTING.md 含 "Common npm test failures" 小节plugin.json+README.md+CONTRIBUTING.md(B05)sih-math定理引用(PROB-018 / ORD-022 / TOP-008 / ALG-001 等)docs/MATH-skeleton-webui-v2-2026-09-20.md(A02)scripts/check-docs-alignment.mjs在 v2 reconcile 后于 CI 退出 0scripts/check-docs-alignment.mjs(B05)+ §6 reconcile在 v1.x 之上新增的能力:
/api/sessions/search?q=…(B05 + C05)/api/sessions/:id/export(C06)/api/usage/forecast— 最小二乘线性拟合 + R² 置信度(C07)MCODE_WEBUI_TOKEN_STDOUT=1环境变量门控(C08)MCODE_WEBUI_RATE_LIMIT/_BURST(C03)为什么做这个插件
Kimi-Code 风格的 web 前端对接
mcodeagent 运行时。让用户在浏览器而不是终端里打开
mcode会话,实时流式查看工具事件,切换 workspace,使用?token=入站modal——全不占用 Mcode TUI 的终端。
示例 prompt(含预期结果)
Prompt 1 — 用户:"打开 Mcode webui"
预期:
node server.js(前台或后台任选)open日志行Prompt 2 — 用户:"Mcode webui 状态"
预期:
.server.err看最近错误Prompt 3 — 用户:"显示 Mcode webui url"
预期:
http://<lan-ip>:8080/TOKEN)也输出带?token=…的完整 URL完整触发列表见
SKILL.md。依赖
mcodeCLI 0.1.4+(用于mcode acp传输)sqlite3二进制(用于 usage 面板)— 由server/lib/config.js#detectSqlite3Bin自动检测mavis0.1.0+(用于真实 token 使用量;缺失时降级为估算)网络与数据行为
0.0.0.0:8080— 通过HOST=127.0.0.1切到 loopback 唯一?token=查询字符串(浏览器友好);也接受Authorization: Bearer头mcode、mmx quota)~/.minimax/v2/sqlite/runtime-state.sqlite(只读)~/.minimax/v2/sqlite/runtime-state.sqlite— 仅在DELETE /api/sessions/:id时(带
?dryRun=true可选预览)MCODE_WEBUI_UPLOAD_DIR(默认.webui-uploads/)用于文件上传~/.minimax-code/webui/.webui-sessions.json用于会话存储完整披露:
references/SECURITY-NOTES.md。自动测试证据
覆盖率(用
c8对server/lib/**/*.js+scripts/**/*.mjs):测试分布(节选):
lib-events.test.js— 27 tests(NDJSON 原子写、单调 seq、hash 链)lib-events-hash.test.js— 8 tests(篡改检测、链恢复)lib-alerts.test.js— 20 tests(3 个等级、60s dedup、ring buffer、dedup 在 ring 翻转后仍命中 + audit payload 完整 — 在 V01 review 后 commit 8f2e86b 加的 regression 覆盖)routes-alerts.test.js— 6 tests(SSE replay、heartbeat、close)lib-authorize.test.js— 20 tests(白名单、超时、per-cid 清理)lib-interaction.test.js— 37 tests(commands 解析器、permission presets、ask-user modal)lib-feedback.test.js— 12 tests(命令反馈、消息点赞/点踩)check-docs-alignment.test.js— 15 tests(live integration、drift round-trip)CI:GitHub Actions 上 Node 22 / Node 24 × macOS / Linux / Windows。
完整 PR 套件跑
npm run check:ci && npm test && npm run sbom && npm audit。手动测试证据
mavis plugin install安装插件(路径模式)TOKEN=$(openssl rand -hex 16)http://127.0.0.1:8080/?token=…— SSE 流连接成功,模型流式渲染lanBroadcast: false— 手机端返回 403 带友好页对生产
runtime-state.sqlite的副本(713 MB)用MCODE_RUNTIME_DB=<copy>;一个有 11,176 行跨 12 表的会话减到 7 行(只剩
questionnaire_requests,按设计跳过 — 它不是
local_runtime_*前缀的)。表清单覆盖 Mcode schema33 个 session-keyed 表中的 32 个。
?dryRun=true重跑删除 — 预览显示行数,无修改红线合规(mcode-plugin-guide)
DELETE /api/sessions/:id有?dryRun=true可选预览。真删走 SQLite
transaction(),每表容错。detectSqlite3Bin()自动检测 — 不写死主机路径。references/SECURITY-NOTES.md是单一权威源;SKILL.md(TL;DR + 链接)、
plugin.json(extensions.securityNotes)、本 PR 描述、插件README.md都引用它。extensions.securityNotes、PR 模板。Checklist
plugin.json通过https://agent-plugins.org/schemas/1.0.0/plugin.schema.json校验npm test— 828 pass, 4 fail(pre-existing better-sqlite3 ABI),2 skippednpm run check— exit 0(6 个 alignment 组全绿)npm run sbom— CycloneDX 1.5 输出,115 componentsnpm audit— 0 vulnerabilitiesreferences/SECURITY-NOTES.md覆盖所有红线 7 主题 + 4 个环境变量导出docs/screenshots/5 张真实截图hooks/ 不支持的 capability 字段plugins/Wzdhehe/mcode-webui/)Closes #16(v1.0.0 marketplace 提交)— 本 PR merge 时自动关闭 Add plugin: mcode-webui (Wzdhehe) #16Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.