Repository navigation
feat: add opt-in file output mode for snapshot and get_elements (#178) - #184
hoanle0126 wants to merge 5 commits into
Conversation
[Medium impact] The PR changes how two page-inspection tools return results and manage local output files. The PR should not merge until the two outstanding cleanup findings are fixed. FindingsSummaryAdds optional file output for
Reviews (7) · Last reviewed commit: "feat: prune stale output files on startu..." · Reviewed by Greptile |
| const dir = outputDir?.trim() || process.env.WDIO_MCP_OUTPUT_DIR?.trim() || join(tmpdir(), DEFAULT_OUTPUT_SUBDIR); | ||
| mkdirSync(dir, { recursive: true }); | ||
|
|
||
| fileCounter = (fileCounter + 1) % 1_000_000; | ||
| const prefix = sessionFilePrefix(sessionId); | ||
| const safeKind = sanitizeSegment(kind); | ||
| const fileName = `${prefix}-${safeKind}-${Date.now()}-${fileCounter}.${ext}`; | ||
| const filePath = join(dir, fileName); | ||
|
|
||
| writeFileSync(filePath, content, 'utf8'); |
There was a problem hiding this comment.
Other users can read snapshots
If the server runs on a shared Linux host with the usual 022 umask, file mode saves page contents in /tmp/wdio-mcp-outputs with readable-by-everyone files. Neither mkdirSync nor writeFileSync sets private permissions, so another local user can list and read snapshots from logged-in pages. Use a private directory owned by the current user and create files with owner-only access.
How this was verified: Both tools pass page contents to writeSessionOutputFile, which writes them under the shared temporary directory without restricting access.
| }); | ||
| state.browsers.delete(oldSessionId); | ||
| state.sessionMetadata.delete(oldSessionId); | ||
| cleanupSessionOutputFiles(oldSessionId); |
There was a problem hiding this comment.
A snapshot already running when start_session replaces its session can write a file after this cleanup finishes. Replacement runs outside the old session’s queue, and the running call keeps its old sessionId. When its browser request returns, writeSessionOutputFile recreates the deleted tracking entry. Nothing cleans that entry again, so the file remains after replacement. Reject writes for removed sessions, or arrange cleanup after running writers finish.
| if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) { | ||
| throw new Error(`Invalid output directory "${configuredDir}": not owned by current user.`); | ||
| } | ||
| chmodSync(configuredDir, 0o700); |
There was a problem hiding this comment.
Shared directories lose access
If a user points outputDir or WDIO_MCP_OUTPUT_DIR at an existing shared project directory, chmodSync(configuredDir, 0o700) removes everyone else’s access to that directory and its unrelated files. Closing the session does not restore those permissions.
Create a private subdirectory for outputs, or reject directories with unsuitable permissions without changing them.
| let subdir = privateSubdirs.get(configuredDir); | ||
| if (!subdir || !existsSync(subdir)) { | ||
| subdir = mkdtempSync(join(configuredDir, DEFAULT_OUTPUT_PREFIX)); | ||
| chmodSync(subdir, 0o700); | ||
| privateSubdirs.set(configuredDir, subdir); | ||
| } | ||
| return subdir; |
There was a problem hiding this comment.
Shared paths can expose snapshots
If another local user can change entries in a shared outputDir without the sticky bit, they can rename the private subdirectory and replace its path with a symlink. existsSync accepts that replacement, so later writes use the attacker’s directory.
The attacker can precreate writable files for upcoming timestamp-and-counter names. writeFileSync overwrites those attacker-owned files before chmodSync runs, exposing page contents even if the permission change fails. Reject unsafe shared parents or use directory and file creation that cannot follow substituted paths.
How this was verified: Both tools pass page contents to this writer, which reuses cached directory paths after only existsSync and writes predictable filenames without exclusive creation.
anthonypdawson
left a comment
There was a problem hiding this comment.
Thanks for picking this up, this is pretty much exactly what I described in #178. The opt-in outputMode: "file", the WDIO_MCP_OUTPUT_MODE / WDIO_MCP_OUTPUT_DIR env defaults, and skipping the truncation in file mode are all the right calls. The compact summary with path, refs, lines, and bytes is what I wanted for keeping large snapshots and element lists out of context.
A few things worth noting before merge:
- There is no way to list or prune the files after they are written. You get the path once in the result, and cleanup only runs on close or replace. If the server crashes or you reconnect, those files are orphans in a temp dir with no way to discover them. A list tool, or at least a prune / cleanup on startup, would close that gap.
- If you point outputDir at an existing shared directory, the code creates a private subdir inside it and writes there instead. That is the safe choice, but it is surprising. The returned path is correct, so the agent will find it, but a person looking in the directory they asked for will not. Worth calling out in the docs, or in the result message.
- Docs need an update. The PR touches the server, lifecycle, both tools, file-output.ts, and tests, but I did not see a docs update for the new outputMode / outputDir params or the env vars. The tool descriptions cover the basics, but the docs page for snapshot and get_elements should list the file mode, the env vars, the default temp location, the 0600 / 0700 permissions, and the cleanup behavior on close / replace.
Happy to test this once it lands. Thanks again for building it.
|
Thanks for the thorough review @anthonypdawson! Addressed all three points in
|
| for (const childName of readdirSync(entryPath)) { | ||
| const childPath = join(entryPath, childName); | ||
| if (isTrackedOutputFile(childPath)) continue; | ||
| try { | ||
| const childStat = lstatSync(childPath); | ||
| if ( | ||
| childStat.isFile() && | ||
| !childStat.isSymbolicLink() && | ||
| (typeof process.getuid !== 'function' || childStat.uid === process.getuid()) | ||
| ) { | ||
| unlinkSync(childPath); |
There was a problem hiding this comment.
Cleanup deletes unrelated files
pruneDirectory deletes every same-user regular file inside a private directory whose name merely starts with wdio-mcp-outputs-. If an outputDir contains a private wdio-mcp-outputs-backup directory, its unrelated files are deleted. Names without a PID bypass the live-process check, and startup runs this cleanup even in inline mode.
Require proof that the directory and files belong to this feature before deleting them.
| } else if (baseIsPrivate && !isTrackedOutputFile(entryPath)) { | ||
| const fileMatch = entryName.match(OUTPUT_FILE_PATTERN); | ||
| if (!fileMatch) continue; | ||
| const ownerPid = fileMatch[1] ? Number(fileMatch[1]) : undefined; | ||
| if (ownerPid !== undefined && ownerPid !== process.pid && isProcessAlive(ownerPid)) { | ||
| continue; |
There was a problem hiding this comment.
If two calls use a relative outputDir and its absolute equivalent, the second call scans the same directory again. Tracking compares path strings, so the scan does not recognize the first call's files. The PID guard explicitly excludes process.pid, allowing cleanup to delete those live snapshot or element files.
Use one absolute, canonical path for tracking and cleanup, or skip all files owned by a running process, including this one.
|
Hey @anthonypdawson @hoanle0126, thanks for the work and the patience here, and sorry for the late direction change. I would not merge this in its current shape, for two reasons:
What I'd like instead:
That replaces most of |
|
Thanks for the direction, this makes sense to me. The session-side fix is the better home for it. One file store, CLI and MCP behaving the same, and a lot less surface in this repo. What I asked for in #178 is just the behavior: path plus compact summary instead of the full tree in context. As long as that survives the move, I'm good with reworking this however you and @hoanle0126 want to split it. My approval was on the old shape, so consider it superseded. |
|
Thanks @Winify, that split makes a lot of sense and keeps CLI and MCP behavior consistent. I opened webdriverio/webdriverio#16461 for the Once that lands and |
|
@hoanle0126 #195 is merged to
|
|
Sounds good, thanks @Winify! I'll rebase onto |
Closes #178
Summary
Adds an opt-in
outputMode("inline" | "file") parameter andoutputDiroption (plusWDIO_MCP_OUTPUT_MODEandWDIO_MCP_OUTPUT_DIRenvironment defaults) tosnapshotandget_elementsso agents can write large accessibility trees and element lists to disk instead of returning the full payload inline in context.Changes
src/utils/file-output.tsto write session-scoped output files with owner-only 0600 file and 0700 directory permissions, creating a private subdirectory when a configured output directory is shared.snapshotandget_elementsto support file output mode, skip inline truncation when writing to disk, and note in the summary when a shared output directory required a private subdirectory.README.md, with unit tests intests/tools/snapshot-file-output.test.ts.