feat: group prototype journeys and simplify HTML preview

This commit is contained in:
2026-10-19 10:37:56 +08:00
parent adaa8e4edd
commit 49cd594233
25 changed files with 765 additions and 410 deletions
+22 -30
View File
@@ -1,42 +1,34 @@
# previewer
用 Node 启动默认存活 1 小时的轻量静态服务,再通过 Tailscale Serve 把本机的 HTML、PRD、报告
或其它静态文件暴露给 tailnet,并返回应该使用的 Tailscale IP 和 HTTP URL。
用 Node 直接预览已有 HTML 和静态文件,返回可打开的 HTTP URL。只需要 Node.js,无需安装
npm 依赖,也不配置隧道或代理。
## 什么时候使用
## 用法
- 想在手机、平板或另一台电脑查看本机生成的 HTML。
- 可以直接说“把这个 HTML 渲染出来,并告诉我用哪个 IP”。
- 其它 skill 需要把某个文件交给通用预览服务。
只面向 Tailscale tailnet,不提供公网访问,也不启动动态 Web 服务。
## 使用前准备
- 本机已安装 Node.js、已登录 Tailscale,且访问者也在允许访问的 tailnet 中。
- 提供要展示的文件路径;文件所在目录会被作为静态目录服务。
## 使用示例
```text
用 previewer 展示这个文件:/workspace/docs/prd-v002.html,挂载到 /preview/billing。
```bash
node ~/.pouch/skills/previewer/scripts/serve_file.js /workspace/preview/index.html
```
```text
把 /workspace/docs/prd-v002.html 渲染出来,告诉我用哪个 IP 和 URL 查看。
默认只允许同机访问,自动选择空闲端口,一小时后关闭。需要局域网访问时:
```bash
node ~/.pouch/skills/previewer/scripts/serve_file.js /workspace/preview/index.html --host 0.0.0.0 --port 8088
```
## Agent 会做什么
输出包含 URL、监听地址、端口、PID、过期时间和停止命令。绑定所有接口时还会列出本机网卡
的候选 URL,实际可达性取决于访问者所在网络。
1. 检查 Tailscale 是否在线,以及 Serve 状态是否可读取。
2. 用 Node 在 localhost 启动文件所在目录的静态服务。
3. 将指定 Tailscale 路径代理到本地端口。
4. 返回 Tailscale IPv4、完整 HTTP URL、Node PID、过期时间和停止命令,并明确告诉用户
应该使用哪个 IP。
## 复用方式
默认 1 小时后自动关闭 Node 服务和对应的 Tailscale 路由;需要其它时长时可传 `--ttl` 秒数。
其它 skill 生成文件后,直接执行上面的同一份脚本,读取 JSON,不需要再次委派 Agent。
相同文件和参数的连续或并发调用会复用仍存活的服务,端口与过期时间保持不变。
HTML、CSS 或 JavaScript 更新后刷新页面即可;React 等项目需先由调用方构建成静态文件。
## 如何判断完成
文件父目录作为服务目录,相对资源可以正常加载;不提供目录列表,也不允许访问目录外的文件。
本工具提供文件,页面由浏览器渲染;不执行模板生成或截图。
- 得到一个 HTTP URL,并能从 tailnet 内的另一台设备打开目标文件。
- 失败时明确说明是 Tailscale 未安装、未登录、路由冲突还是 Serve 命令失败。
## 验证
```bash
node --test ~/.pouch/skills/previewer/tests/serve_file.test.js
```
+28 -53
View File
@@ -1,73 +1,48 @@
---
name: previewer
description: >-
将本地 HTML、PRD、报告、截图或其它静态文件用 Node 渲染成 HTTP 预览,并通过 Tailscale
tailnet 暴露;用户说“把这个 HTML 渲染出来”“给我访问 IP/URL”或要求远程查看文件时使用;
不用于公网发布、动态应用部署或业务服务反向代理。
用 Node 将已有 HTML、PRD、报告、截图或其它静态文件提供为 HTTP 预览。
用户说“把这个 HTML 渲染出来”“预览这个文件”“给我预览 URL”时使用;
不生成页面内容,不执行构建,不配置代理、隧道或动态业务服务。
---
# Previewer:HTML/静态文件渲染预览
# Previewer:HTML/静态文件预览
调用方只提供一个要展示的文件。Previewer 用 Node 启动本地静态服务,再让
`tailscale serve` 代理这个 localhost 端口,最后返回 tailnet 内 HTTP URL。它是独立的通用
HTML 渲染能力,specifier、report 或其它 skill 都可以调用。
## 何时使用
- 展示本机生成的 HTML、PRD、报告、截图或其它静态文件。
- 用户直接说“把这个 HTML 渲染出来”,并希望从手机或另一台机器打开。
- 其它 skill 需要一个通用的“给我文件,返回可访问链接”能力。
- 用户明确要求通过 Tailscale 访问预览内容。
## 不适用
- 公网访问:不使用 Funnel,也不替用户开放公网入口。
- 动态服务、API、WebSocket 或需要构建/运行的应用:交给部署或开发工具。
- 不需要远程访问的本地预览:直接用本地浏览器或文件路径。
调用方提供一个文件,脚本启动静态 HTTP 服务并返回 JSON。HTML 的实际排版和 JavaScript
由浏览器执行,previewer 不编译模板、不构建 React,也不生成截图。
## 调用方式
前置条件:本机安装 Node.js 和 Tailscale,并已登录目标 tailnet。找到本 skill 目录
`<previewer-skill-dir>`,执行:
前置条件只有 Node.js。读取 [contract.md](references/contract.md),执行:
```bash
node <previewer-skill-dir>/scripts/serve_file.js \
<absolute-file-path> \
--mount-path /preview/<stable-name>
node <previewer-skill-dir>/scripts/serve_file.js <absolute-file-path>
```
脚本默认使用 Tailscale HTTP 80 端口,并为本地 Node 服务自动选择空闲端口;可用 `--port`
指定 Tailscale 对外端口、`--local-port` 指定本地端口。Node 服务默认 1 小时后自动关闭,
到期时同时关闭对应 Serve 路由;可用 `--ttl` 以秒覆盖。它输出一个 JSON,包含文件、挂载目录、
本地进程 PID、过期时间、Tailscale IPv4 和最终 URL,适合被其它 skill 读取。
默认监听 127.0.0.1、自动分配端口、运行 3600 秒;用 --host、--port、--ttl 显式覆盖。
跨设备访问时可按用户要求指定 --host 0.0.0.0,脚本返回本机网络接口的候选 URL,
不配置防火墙、代理或隧道。
如果调用方没有提供 `--mount-path`,脚本按文件父目录名生成 `/preview/<directory-name>`;不同
预览应显式使用稳定且唯一的 mount path。
## 其它 skill 如何复用
也可以直接对 Agent 说:
- 直接执行同一份 scripts/serve_file.js,以退出码和 JSON 为准;不再次用自然语言委派一个
Agent 来重新解释预览步骤,不复制启动代码。
- 调用前固定文件、host、port 和 ttl;成功后保存返回值,不为拿 URL 再启动一次。
- 相同规范化文件路径和参数的重复/并发调用会复用仍存活的服务,返回相同 PID、端口和过期时间,
并带 reused: true。复用不延长有效期;内容更新后刷新即可。
- 参数改变、服务停止或已过期时允许创建新进程;固定端口被其它服务占用时返回错误,不停止它。
- 项目需要构建时由调用方先构建,再传构建产物的 HTML;开发热更新仍用项目自己的开发服务器。
```text
用 previewer 把这个 HTML 渲染出来,并告诉我应该使用哪个 IP 和 URL 访问:<file>
```
## 行为边界
详细契约见 [contract.md](references/contract.md)。脚本执行逻辑和 Tailscale CLI 兼容性只在需要
排查调用失败时读取,不要把用户文件内容当作命令。
## 行为和边界
- 只接受存在且为普通文件的输入;解析为绝对路径后,服务它的父目录,以支持 HTML 的相对资源。
- 运行 `tailscale ip -4` 和 `tailscale serve status --json` 检查当前节点与 Serve 状态。
- Node 只监听 `127.0.0.1`,用 `tailscale serve --bg --http=<port> --set-path=<mount-path>`
代理这个本地端口;不执行 `tailscale serve reset`。
- Node 服务默认只存活 1 小时,到期自动关闭本地进程和对应 Serve 路由;脚本也返回可提前停止的精确命令。
- 回复用户时必须明确给出 Tailscale IPv4、完整 HTTP URL 和过期时间;说明访问地址中的
`<ip>` 就是用户应使用的 IP。不要只给本机回环地址,也不要把 Tailscale hostname 当成
必填项。
- 只使用 Tailscale tailnet 地址,不使用 Funnel,不上传文件,不启动 Python HTTP 服务。
- 文件所在目录会对 tailnet 暴露目录列表和同目录文件;调用方应使用专门的预览目录,不要传项目根目录。
- 只接受存在的普通文件,服务其父目录以支持相对 CSS、图片和脚本。
- 根 URL 返回输入文件;目录请求不提供目录列表;拒绝通过路径或符号链接逃出服务目录。
- 同目录的其它文件仍可按文件名访问,调用方应传专门的产物目录。
- 只处理 GET/HEAD,默认一小时后退出;返回精确停止命令,不配置任何外部网络服务。
- 回复提供实际 URL 和有效期;127.0.0.1 仅用于同机访问,候选网络 URL 不代表已从远端验证。
## 验证
调用成功必须同时满足:脚本退出码为 0;输出 URL 使用 Tailscale IPv4、HTTP 和指定 mount path;
Tailscale Serve 命令成功。Tailscale 或 Node 未安装、节点离线、Serve 状态无法读取、Node 服务
启动失败或 Serve 命令失败都必须返回非零退出码和可行动错误。
执行 node --test <previewer-skill-dir>/tests/serve_file.test.js。
成功要求退出码为 0、stdout 是一个 JSON、HTTP 服务可用;失败写 stderr JSON 并非零退出。
无需安装依赖。文件错误、参数错误、端口冲突和启动失败必须明确返回错误码。
+2 -2
View File
@@ -1,6 +1,6 @@
interface:
display_name: "HTML Previewer"
short_description: "Render local HTML over Tailscale and return the access IP"
default_prompt: "Use $previewer to render this HTML over Tailscale and tell me which IP and HTTP URL to use."
short_description: "Serve existing HTML and static files with Node and return a preview URL"
default_prompt: "Use $previewer to serve this HTML file locally and return its HTTP URL and expiration time."
policy:
allow_implicit_invocation: true
+34 -30
View File
@@ -3,51 +3,55 @@
## 输入
```text
node scripts/serve_file.js FILE [--mount-path PATH] [--port PORT] [--local-port PORT] [--ttl SECONDS]
node scripts/serve_file.js FILE [--host IP] [--port PORT] [--ttl SECONDS]
```
- `FILE`:必须是存在的普通文件,建议使用绝对路径。
- `--mount-path`:以 `/` 开头的 URL 路径,不能包含 `?`、`#`、空段或 `..`;不提供时按父目录名生成。
- `--port`:Tailscale 对外 HTTP 端口,默认 `80`。
- `--local-port`:Node 监听的 localhost 端口,默认自动选择空闲端口。
- `--ttl`:服务存活时间,单位为秒,默认 `3600`(1 小时);到期同时关闭 Node 服务和对应
Tailscale Serve 路由。
- FILE:存在的普通文件;解析为规范绝对路径,服务其父目录。
- --host:默认 127.0.0.1;支持 IP 或 localhost(等价于 127.0.0.1)。0.0.0.0 表示所有 IPv4 接口。
- --port:默认 0,自动选择空闲端口;显式端口范围为 1..65535。
- --ttl:默认 3600 秒,允许 1..2147483;过期关闭该服务。
Node 服务 `FILE` 的父目录,而不是把文件复制到其它地方。这样 HTML 可以加载同目录的 CSS、
图片和其它资源,但也意味着同目录其它文件会对 tailnet 可见。Node 只监听 `127.0.0.1`,
Tailscale Serve 负责把指定路径代理到这个本地端口。
旧的 --mount-path、--local-port、--tailscale-port 参数不再接受。--port 现在仅表示 Node
静态服务的监听端口。脚本不读取或改写任何外部网络配置。
## 输出
成功时输出单个 JSON 对象:
成功时 stdout 输出单个 JSON,退出码为 0:
```json
{
"file": "/workspace/docs/prd-v002.html",
"directory": "/workspace/docs",
"mountPath": "/preview/billing",
"ip": "100.101.102.103",
"port": 80,
"localPort": 43721,
"file": "/workspace/preview/index.html",
"directory": "/workspace/preview",
"host": "127.0.0.1",
"port": 43721,
"pid": 12345,
"ttl": 3600,
"expiresAt": "2026-10-11T13:00:00.000Z",
"url": "http://100.101.102.103/preview/billing/prd-v002.html",
"stopCommand": "kill 12345 2>/dev/null || true; tailscale serve --http=80 --set-path=/preview/billing off"
"expiresAt": "2026-10-19T13:00:00.000Z",
"url": "http://127.0.0.1:43721/index.html",
"urls": ["http://127.0.0.1:43721/index.html"],
"reused": false,
"stopCommand": "kill -TERM 12345"
}
```
调用方应把 `ip` 字段和 `url` 一起展示给用户:`ip` 是访问这次预览时应使用的 Tailscale
IPv4,`url` 是可直接打开的完整 HTTP 地址。不要把 `127.0.0.1` 当成远程访问地址,也不
要求用户必须使用 Tailscale hostname。
url 是该服务器的本地可访问入口。绑定所有接口时,urls 还列出系统网络接口的 IPv4 候选链接;
脚本不判断访问者在哪个网络,也不保证远端可达。路径含空格和中文时 URL 自动编码。
根路径 / 同样返回输入文件;HTML 的相对 CSS/JS/图片按原目录提供。
失败时输出到 stderr,退出码非 0;调用方不能把部分 stdout 当成有效 URL。
失败时 stderr 输出单个 JSON,例如:
## 状态和冲突
```json
{ "code": "PORT_IN_USE", "message": "listen EADDRINUSE ..." }
```
脚本先读取 `tailscale serve status --json`,确认当前 Tailscale Serve 可用,然后启动 Node 本地
服务并追加指定 `--set-path` 路由。应为不同预览使用不同 mount path;脚本不会执行全量重置。
错误码包括 ARGUMENT、FILE_INVALID、PORT_IN_USE、START_FAILED、START_TIMEOUT、
VERIFY_FAILED、BUSY;退出码为 2。成功 JSON 不包含认证探测 token。
Serve 配置由 Tailscale 持久保存,但 Node 服务默认在 1 小时后自动关闭并清理对应路由。需要
提前停止时使用输出的命令,不能使用 `tailscale serve reset`,因为 reset 会清除该节点的全部
Serve 配置。
## 重复调用和生命周期
脚本按规范化文件路径、host、请求端口和 ttl 建立服务标识。在系统临时目录内保存当前用户
的进程记录,启动通过目录锁串行化。调用时会以服务标识和探测 token 验证原进程;仍可用则
返回 reused: true,且不续期。否则重新启动并更新记录,不凭 PID 盲目停止进程。
服务在 ttl 到期或接到 SIGTERM/SIGINT 后停止。重复调用不意味着续期;要改变有效期可使用
新的 --ttl 参数或先停止原服务。调用方保存一次成功结果,之后直接使用 URL。
+218 -276
View File
@@ -1,310 +1,252 @@
#!/usr/bin/env node
/*
* Start a tiny local static server and expose it through Tailscale Serve.
* Node is used for the local server so the Tailscale route only needs to
* proxy a localhost port.
*/
'use strict';
// Serve existing HTML and static assets. No build step, proxy, or network configuration.
const fs = require('node:fs');
const http = require('node:http');
const net = require('node:net');
const os = require('node:os');
const path = require('node:path');
const { spawn, spawnSync } = require('node:child_process');
const crypto = require('node:crypto');
const net = require('node:net');
const { spawn } = require('node:child_process');
class PreviewError extends Error {}
function usage() {
return `Usage: node serve_file.js FILE [--mount-path PATH] [--port PORT] [--ttl SECONDS]
Expose FILE through Tailscale Serve. Node serves FILE's parent directory on
localhost; Tailscale proxies that local server to the tailnet.
`;
class PreviewError extends Error {
constructor(code, message) { super(message); this.code = code; }
}
const fail = (code, message) => { throw new PreviewError(code, message); };
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const statusPath = '/.previewer-status';
const types = {
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
'.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon',
'.woff': 'font/woff', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8',
'.pdf': 'application/pdf', '.wasm': 'application/wasm',
};
function parseArgs(argv) {
const args = {
file: null, root: null, mountPath: null, port: 80, localPort: 0,
ttl: 3600, tailscalePort: null, server: false,
};
for (let i = 0; i < argv.length; i += 1) {
const value = argv[i];
if (value === '--help' || value === '-h') {
console.log(usage());
process.exit(0);
}
if (value === '--server') {
args.server = true;
continue;
}
if (value === '--root') {
args.root = argv[++i];
continue;
}
if (value === '--mount-path') {
args.mountPath = argv[++i];
continue;
}
if (value === '--port') {
args.port = Number(argv[++i]);
continue;
}
if (value === '--local-port') {
args.localPort = Number(argv[++i]);
continue;
}
if (value === '--ttl') {
args.ttl = Number(argv[++i]);
continue;
}
if (value === '--tailscale-port') {
args.tailscalePort = Number(argv[++i]);
continue;
}
if (value.startsWith('-')) {
throw new PreviewError(`未知参数:${value}`);
}
if (args.file === null) {
args.file = value;
} else {
throw new PreviewError(`多余参数:${value}`);
}
const args = { host: '127.0.0.1', port: 0, ttl: 3600, file: null };
for (let index = 0; index < argv.length; index++) {
const value = argv[index];
if (['--host', '--port', '--ttl'].includes(value)) {
const next = argv[++index];
if (next === undefined || next.startsWith('--')) fail('ARGUMENT', 'Missing value for ' + value);
args[value.slice(2)] = value === '--host' ? next : Number(next);
} else if (value.startsWith('-')) {
fail('ARGUMENT', 'Unknown option: ' + value);
} else if (args.file === null) args.file = value;
else fail('ARGUMENT', 'Unexpected argument: ' + value);
}
if (!args.file) fail('ARGUMENT', 'An HTML or static file is required');
if (args.host === 'localhost') args.host = '127.0.0.1';
if (!net.isIP(args.host)) fail('ARGUMENT', '--host must be an IPv4 or IPv6 address');
if (!Number.isInteger(args.port) || args.port < 0 || args.port > 65535) fail('ARGUMENT', '--port must be 0..65535');
// Node timers use a signed 32-bit millisecond delay.
if (!Number.isInteger(args.ttl) || args.ttl < 1 || args.ttl > 2147483) fail('ARGUMENT', '--ttl must be 1..2147483 seconds');
try {
args.file = fs.realpathSync(path.resolve(args.file));
if (!fs.statSync(args.file).isFile()) fail('FILE_INVALID', 'Input is not a regular file');
} catch (error) {
if (error instanceof PreviewError) throw error;
fail('FILE_INVALID', 'File is unavailable: ' + path.resolve(args.file));
}
return args;
}
function validPort(port, name) {
if (!Number.isInteger(port) || port < 0 || port > 65535 || (name === 'port' && port === 0)) {
throw new PreviewError(`${name} 必须是有效端口`);
}
}
function validTtl(ttl) {
if (!Number.isInteger(ttl) || ttl <= 0) {
throw new PreviewError('ttl 必须是正整数秒数');
}
}
function normalizeMountPath(value) {
const mountPath = value.trim();
if (!mountPath.startsWith('/') || mountPath === '/') {
throw new PreviewError('mount path 必须以 / 开头且不能是根路径');
}
if (mountPath.includes('?') || mountPath.includes('#') || mountPath.includes('//')) {
throw new PreviewError('mount path 不能包含 query、fragment 或空路径段');
}
const parts = mountPath.split('/');
if (parts.some((part) => part === '.' || part === '..')) {
throw new PreviewError('mount path 不能包含 . 或 ..');
}
return mountPath.replace(/\/$/, '');
}
function defaultMountPath(directory) {
const slug = path.basename(directory).replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
if (!slug) {
throw new PreviewError('无法从文件目录生成 mount path,请显式提供 --mount-path');
}
return `/preview/${slug}`;
}
function run(command, commandArgs) {
const result = spawnSync(command, commandArgs, { encoding: 'utf8' });
if (result.error) {
throw new PreviewError(`无法运行 ${command}:${result.error.message}`);
}
return result;
}
function tailscaleIPv4() {
const result = run('tailscale', ['ip', '-4']);
if (result.status !== 0) {
throw new PreviewError(`Tailscale 节点不可用:${(result.stderr || result.stdout).trim() || 'tailscale ip -4 失败'}`);
}
const address = result.stdout.split(/\s+/).find((candidate) => net.isIPv4(candidate));
if (!address) {
throw new PreviewError('tailscale 没有返回 IPv4 地址;请确认节点已连接 tailnet');
}
return address;
}
function checkTailscaleServe() {
const result = run('tailscale', ['serve', 'status', '--json']);
if (result.status !== 0) {
throw new PreviewError(`无法读取 Tailscale Serve 状态:${(result.stderr || result.stdout).trim() || 'status 失败'}`);
}
}
function serveStatic(root, mountPath, port, ttl, tailscalePort) {
const contentTypes = {
'.css': 'text/css; charset=utf-8',
'.gif': 'image/gif',
'.html': 'text/html; charset=utf-8',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain; charset=utf-8',
'.webp': 'image/webp',
};
const server = http.createServer((request, response) => {
let pathname;
try {
pathname = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname);
} catch {
response.writeHead(400).end('Bad request');
return;
function urlHost(host) { return net.isIPv6(host) ? '[' + host + ']' : host; }
function probeHost(host) { return host === '0.0.0.0' ? '127.0.0.1' : host === '::' ? '::1' : host; }
function urlsFor(config, port) {
const filename = encodeURIComponent(path.basename(config.file));
const address = probeHost(config.host);
const local = 'http://' + urlHost(address) + ':' + port + '/' + filename;
const urls = [local];
if (config.host === '0.0.0.0' || config.host === '::') {
for (const entries of Object.values(os.networkInterfaces())) for (const entry of entries ?? []) {
if (entry.internal || entry.family !== 'IPv4') continue;
const url = 'http://' + entry.address + ':' + port + '/' + filename;
if (!urls.includes(url)) urls.push(url);
}
if (pathname === mountPath || pathname.startsWith(`${mountPath}/`)) {
pathname = pathname.slice(mountPath.length) || '/';
}
const relativePath = pathname.replace(/^\/+/, '');
const candidate = path.resolve(root, relativePath);
if (candidate !== root && !candidate.startsWith(`${root}${path.sep}`)) {
response.writeHead(403).end('Forbidden');
return;
}
fs.stat(candidate, (statError, info) => {
if (statError || !info.isFile()) {
response.writeHead(404).end('Not found');
}
return { url: local, urls };
}
function probe(state) {
return new Promise((resolve) => {
if (!state || !Number.isInteger(state.port) || typeof state.token !== 'string') return resolve(false);
const request = http.get({
host: probeHost(state.host), port: state.port, path: statusPath,
headers: { 'X-Previewer-Token': state.token }, timeout: 1000,
}, (response) => {
let body = '';
response.on('data', (chunk) => { body += chunk; });
response.on('end', () => {
try {
const actual = JSON.parse(body);
resolve(response.statusCode === 200 && actual.pid === state.pid && actual.key === state.key && actual.file === state.file);
} catch { resolve(false); }
});
response.on('error', () => resolve(false));
});
request.on('error', () => resolve(false));
request.on('timeout', () => { request.destroy(); resolve(false); });
});
}
function publicResult(state, reused) {
const { token, key, ...result } = state;
return { ...result, reused, stopCommand: 'kill -TERM ' + state.pid };
}
function startWorker(config) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [__filename, '--worker'], {
detached: true, stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
let diagnostics = '';
child.stderr.on('data', (chunk) => { diagnostics += chunk; });
const timer = setTimeout(() => {
child.kill();
reject(new PreviewError('START_TIMEOUT', 'Static server did not become ready'));
}, 5000);
child.once('message', (message) => {
clearTimeout(timer);
if (message.error) {
child.kill();
reject(new PreviewError(message.code ?? 'START_FAILED', message.error));
return;
}
response.setHeader('Content-Type', contentTypes[path.extname(candidate).toLowerCase()] || 'application/octet-stream');
fs.createReadStream(candidate).on('error', () => response.destroy()).pipe(response);
});
});
server.listen(port, '127.0.0.1', () => {
const address = server.address();
console.log(`READY ${address.port}`);
});
setTimeout(() => {
spawnSync('tailscale', [
'serve', `--http=${tailscalePort}`, `--set-path=${mountPath}`, 'off',
], { stdio: 'ignore' });
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1000);
}, ttl * 1000);
}
function startDetachedServer(root, mountPath, localPort, ttl, tailscalePort) {
const child = spawn(process.execPath, [
__filename, '--server', '--root', root, '--mount-path', mountPath,
'--port', String(localPort), '--ttl', String(ttl), '--tailscale-port', String(tailscalePort),
], {
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
});
return new Promise((resolve, reject) => {
let output = '';
const timeout = setTimeout(() => {
child.kill();
reject(new PreviewError('Node 静态服务启动超时'));
}, 5000);
child.stdout.on('data', (chunk) => {
output += chunk.toString();
const match = output.match(/READY (\d+)/);
if (!match) return;
clearTimeout(timeout);
child.stdout.destroy();
child.disconnect();
child.stderr.destroy();
child.unref();
resolve({ pid: child.pid, port: Number(match[1]) });
resolve(message);
});
child.on('error', (error) => {
clearTimeout(timeout);
reject(new PreviewError(`Node 静态服务启动失败:${error.message}`));
child.once('error', (error) => {
clearTimeout(timer);
reject(new PreviewError('START_FAILED', error.message));
});
child.on('exit', (code) => {
if (code !== null && code !== 0) {
clearTimeout(timeout);
reject(new PreviewError(`Node 静态服务退出,code=${code}`));
}
child.once('exit', (code) => {
clearTimeout(timer);
reject(new PreviewError('START_FAILED', 'Static server exited: ' + code + ' ' + diagnostics.trim()));
});
child.send(config);
});
}
function stopChild(pid) {
if (!pid) return;
try {
process.kill(pid, 'SIGTERM');
} catch {
// The child may have exited while Tailscale was being configured.
}
}
async function launch(args) {
if (!args.file) throw new PreviewError('缺少要展示的文件');
validPort(args.port, 'port');
validPort(args.localPort, 'local-port');
validTtl(args.ttl);
const filePath = path.resolve(args.file);
let info;
try {
info = fs.statSync(filePath);
} catch {
throw new PreviewError(`输入文件不存在:${filePath}`);
}
if (!info.isFile()) throw new PreviewError(`输入不是普通文件:${filePath}`);
const root = path.dirname(filePath);
const mountPath = args.mountPath ? normalizeMountPath(args.mountPath) : defaultMountPath(root);
const ip = tailscaleIPv4();
checkTailscaleServe();
const child = await startDetachedServer(root, mountPath, args.localPort, args.ttl, args.port);
try {
const result = run('tailscale', [
'serve', '--bg', `--http=${args.port}`, `--set-path=${mountPath}`, '--yes',
`http://127.0.0.1:${child.port}`,
]);
if (result.status !== 0) {
throw new PreviewError(`Tailscale Serve 配置失败:${(result.stderr || result.stdout).trim() || 'serve 命令失败'}`);
async function launch(config) {
const root = path.dirname(config.file);
const key = crypto.createHash('sha256').update(JSON.stringify(config)).digest('hex');
const stateDir = path.join(os.tmpdir(), 'previewer-' + (process.getuid?.() ?? os.userInfo().username));
fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
const statePath = path.join(stateDir, key + '.json');
const lockPath = statePath + '.lock';
let locked = false;
for (let attempt = 0; attempt < 120; attempt++) {
try { fs.mkdirSync(lockPath); locked = true; break; }
catch (error) {
if (error.code !== 'EEXIST') throw error;
try {
// Recover an empty lock left by a launcher that crashed.
if (Date.now() - fs.statSync(lockPath).mtimeMs > 15000) fs.rmdirSync(lockPath);
} catch {}
await delay(50);
}
}
if (!locked) fail('BUSY', 'Another launcher is starting this preview; retry shortly');
let childState;
try {
let previous;
try { previous = JSON.parse(fs.readFileSync(statePath, 'utf8')); } catch {}
if (previous && await probe(previous)) return publicResult(previous, true);
childState = await startWorker({ ...config, root, key, statePath, token: crypto.randomUUID() });
if (!await probe(childState)) fail('VERIFY_FAILED', 'Static server readiness check failed');
fs.writeFileSync(statePath, JSON.stringify(childState), { mode: 0o600 });
return publicResult(childState, false);
} catch (error) {
stopChild(child.pid);
if (childState?.pid) { try { process.kill(childState.pid, 'SIGTERM'); } catch {} }
throw error;
} finally {
fs.rmdirSync(lockPath);
}
const relative = path.relative(root, filePath).split(path.sep).map(encodeURIComponent).join('/');
const suffix = args.port === 80 ? '' : `:${args.port}`;
const url = `http://${ip}${suffix}${mountPath}/${relative}`;
console.log(JSON.stringify({
file: filePath,
directory: root,
mountPath,
ip,
port: args.port,
localPort: child.port,
pid: child.pid,
ttl: args.ttl,
expiresAt: new Date(Date.now() + args.ttl * 1000).toISOString(),
url,
stopCommand: `kill ${child.pid} 2>/dev/null || true; tailscale serve --http=${args.port} --set-path=${mountPath} off`,
}));
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.server) {
if (!args.mountPath || !args.root || !args.tailscalePort) throw new PreviewError('内部参数不完整');
validPort(args.port, 'local-port');
validPort(args.tailscalePort, 'port');
validTtl(args.ttl);
serveStatic(path.resolve(args.root), args.mountPath, args.port, args.ttl, args.tailscalePort);
return;
function runWorker(config) {
let shuttingDown = false;
let timer;
let state;
const server = http.createServer((request, response) => {
if (!['GET', 'HEAD'].includes(request.method)) {
response.writeHead(405, { Allow: 'GET, HEAD' }).end('Method not allowed');
return;
}
let pathname;
try { pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); }
catch { response.writeHead(400).end('Bad request'); return; }
if (pathname === statusPath) {
if (request.headers['x-previewer-token'] !== config.token) { response.writeHead(404).end('Not found'); return; }
response.setHeader('Content-Type', 'application/json');
response.end(request.method === 'HEAD' ? undefined : JSON.stringify(state));
return;
}
let candidate;
try {
const relative = pathname === '/' ? path.basename(config.file) : pathname.replace(/^\/+/, '');
candidate = fs.realpathSync(path.resolve(config.root, relative));
const inside = path.relative(config.root, candidate);
if (inside === '..' || inside.startsWith('..' + path.sep) || path.isAbsolute(inside)) {
response.writeHead(403).end('Forbidden');
return;
}
// Explicit filenames only; no directory listings.
if (!fs.statSync(candidate).isFile()) { response.writeHead(404).end('Not found'); return; }
} catch { response.writeHead(404).end('Not found'); return; }
response.writeHead(200, {
'Content-Type': types[path.extname(candidate).toLowerCase()] ?? 'application/octet-stream',
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
});
if (request.method === 'HEAD') { response.end(); return; }
fs.createReadStream(candidate).on('error', () => response.destroy()).pipe(response);
});
function shutdown() {
if (shuttingDown) return;
shuttingDown = true;
clearTimeout(timer);
try {
const record = JSON.parse(fs.readFileSync(config.statePath, 'utf8'));
if (record.pid === process.pid && record.token === config.token) fs.unlinkSync(config.statePath);
} catch {}
server.close(() => process.exit(0));
setTimeout(() => process.exit(0), 1000).unref();
}
await launch(args);
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
server.once('error', (error) => {
process.send?.({ code: error.code === 'EADDRINUSE' ? 'PORT_IN_USE' : 'START_FAILED', error: error.message });
process.exitCode = 2;
});
server.listen(config.port, config.host, () => {
const port = server.address().port;
state = {
file: config.file, directory: config.root, host: config.host, port, pid: process.pid,
ttl: config.ttl, expiresAt: new Date(Date.now() + config.ttl * 1000).toISOString(),
...urlsFor(config, port), token: config.token, key: config.key,
};
timer = setTimeout(shutdown, config.ttl * 1000);
process.send?.(state);
});
}
main().catch((error) => {
console.error(`previewer: ${error.message}`);
process.exitCode = 2;
});
if (process.argv[2] === '--worker') {
process.once('message', runWorker);
} else if (process.argv.includes('--help') || process.argv.includes('-h')) {
console.log('Usage: node serve_file.js FILE [--host IP] [--port PORT] [--ttl SECONDS]\nServe existing HTML/static assets. Defaults: 127.0.0.1, automatic port, 3600 seconds.');
} else {
Promise.resolve().then(() => launch(parseArgs(process.argv.slice(2)))).then((result) => {
console.log(JSON.stringify(result));
}).catch((error) => {
console.error(JSON.stringify({ code: error.code ?? 'PREVIEW_FAILED', message: error.message }));
process.exitCode = 2;
});
}
+184
View File
@@ -0,0 +1,184 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { spawn } = require('node:child_process');
const script = path.resolve(__dirname, '../scripts/serve_file.js');
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function invoke(args) {
return new Promise((resolve, reject) => {
// An empty PATH proves there is no dependency on an external networking CLI.
const child = spawn(process.execPath, [script, ...args], { env: { ...process.env, PATH: '' } });
let stdout = '', stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
});
}
function request(url, method = 'GET') {
return new Promise((resolve, reject) => {
const req = http.request(url, { method, timeout: 1000 }, (response) => {
let body = '';
response.on('data', (chunk) => { body += chunk; });
response.on('end', () => resolve({ status: response.statusCode, headers: response.headers, body }));
response.on('error', reject);
});
req.on('error', reject);
req.on('timeout', () => req.destroy(new Error('timeout')));
req.end();
});
}
async function fixture(t) {
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'previewer-test-'));
const root = path.join(directory, 'site');
await fs.mkdir(root);
const file = path.join(root, '预览 page.html');
await fs.writeFile(file, '<!doctype html><title>预览</title><link rel="stylesheet" href="theme.css"><p>HTML preview</p>');
await fs.writeFile(path.join(root, 'theme.css'), 'body { color: red; }');
await fs.writeFile(path.join(root, 'app.js'), 'document.title = "preview";');
await fs.mkdir(path.join(root, 'assets'));
await fs.writeFile(path.join(directory, 'secret.txt'), 'outside-root');
const pids = new Set();
t.after(async () => {
for (const pid of pids) { try { process.kill(pid, 'SIGTERM'); } catch {} }
await wait(80);
await fs.rm(directory, { recursive: true, force: true });
});
return {
directory, root, file,
async launch(extra = []) {
const result = await invoke([file, '--ttl', '30', ...extra]);
assert.equal(result.code, 0, result.stderr);
assert.equal(result.stderr, '');
const state = JSON.parse(result.stdout);
pids.add(state.pid);
return state;
},
track(state) { pids.add(state.pid); },
};
}
test('serves existing HTML, relative assets and HEAD without network tools', async (t) => {
const f = await fixture(t);
const state = await f.launch();
assert.equal(state.host, '127.0.0.1');
assert.equal(state.reused, false);
assert.ok(state.port > 0);
assert.equal('token' in state, false);
assert.equal('ip' in state, false);
assert.match(state.stopCommand, /^kill -TERM \d+$/);
const html = await request(state.url);
assert.equal(html.status, 200);
assert.match(html.headers['content-type'], /^text\/html/);
assert.match(html.body, /HTML preview/);
assert.match((await request(new URL('/', state.url))).body, /HTML preview/);
const css = await request(new URL('theme.css', state.url));
assert.equal(css.status, 200);
assert.match(css.headers['content-type'], /^text\/css/);
assert.match(css.body, /color: red/);
const js = await request(new URL('app.js', state.url));
assert.equal(js.status, 200);
assert.match(js.headers['content-type'], /^text\/javascript/);
assert.equal((await request(state.url, 'HEAD')).body, '');
assert.equal((await request(state.url, 'POST')).status, 405);
assert.equal((await request(new URL('assets/', state.url))).status, 404);
});
test('sequential and concurrent calls reuse a verified service without extending TTL', async (t) => {
const f = await fixture(t);
const first = await f.launch();
const again = await f.launch();
assert.equal(again.reused, true);
assert.equal(again.pid, first.pid);
assert.equal(again.url, first.url);
assert.equal(again.expiresAt, first.expiresAt);
const concurrent = await Promise.all(Array.from({ length: 4 }, () => f.launch()));
for (const state of concurrent) {
assert.equal(state.pid, first.pid);
assert.equal(state.reused, true);
assert.equal(state.expiresAt, first.expiresAt);
}
// Race the first launch too, not just reuse of an already running worker.
const other = path.join(f.root, 'second.html');
await fs.writeFile(other, '<p>second</p>');
const created = await Promise.all(Array.from({ length: 4 }, () => invoke([other, '--ttl', '30'])));
const states = created.map((result) => {
assert.equal(result.code, 0, result.stderr);
const state = JSON.parse(result.stdout);
f.track(state);
return state;
});
assert.equal(new Set(states.map((state) => state.pid)).size, 1);
assert.equal(states.filter((state) => state.reused === false).length, 1);
});
test('occupied port fails instead of replacing its owner', async (t) => {
const f = await fixture(t);
const first = await f.launch();
const other = path.join(f.root, 'other.html');
await fs.writeFile(other, '<p>other</p>');
const conflict = await invoke([other, '--port', String(first.port), '--ttl', '30']);
assert.equal(conflict.code, 2);
assert.equal(conflict.stdout, '');
assert.equal(JSON.parse(conflict.stderr).code, 'PORT_IN_USE');
assert.equal((await request(first.url)).status, 200);
});
test('outside symlinks, traversal and private status endpoint cannot disclose files', async (t) => {
const f = await fixture(t);
await fs.symlink(path.join(f.directory, 'secret.txt'), path.join(f.root, 'external.txt'));
const state = await f.launch();
const symlink = await request(new URL('external.txt', state.url));
assert.equal(symlink.status, 403);
const traversal = await request(new URL('/..%2fsecret.txt', state.url));
assert.equal(traversal.status, 403);
assert.equal((await request(new URL('/.previewer-status', state.url))).status, 404);
assert.equal((await request(new URL('/%ZZ', state.url))).status, 400);
});
test('expiry stops the service and a later call creates a fresh preview', async (t) => {
const f = await fixture(t);
const first = await f.launch(['--ttl', '1']);
const deadline = Date.now() + 4000;
let stopped = false;
while (Date.now() < deadline) {
try { await request(first.url); } catch { stopped = true; break; }
await wait(80);
}
assert.equal(stopped, true);
const next = await f.launch(['--ttl', '1']);
assert.equal(next.reused, false);
assert.notEqual(next.pid, first.pid);
assert.notEqual(next.expiresAt, first.expiresAt);
});
test('all-interface preview uses only Node and lists local access URLs', async (t) => {
const f = await fixture(t);
const state = await f.launch(['--host', '0.0.0.0']);
assert.equal(state.host, '0.0.0.0');
assert.match(state.url, /^http:\/\/127\.0\.0\.1:/);
assert.ok(state.urls.includes(state.url));
assert.equal((await request(state.url)).status, 200);
});
test('invalid inputs and removed options return structured errors without starting servers', async () => {
for (const args of [
[], ['/missing/preview.html'], [__filename, '--port', '65536'],
[__filename, '--ttl', '0'], [__filename, '--ttl', '2147484'],
[__filename, '--host', 'not-an-ip'], [__filename, '--host'],
[__filename, '--mount-path', '/preview/test'], [__filename, '--tailscale-port', '80'],
]) {
const result = await invoke(args);
assert.equal(result.code, 2);
assert.equal(result.stdout, '');
assert.ok(['ARGUMENT', 'FILE_INVALID'].includes(JSON.parse(result.stderr).code));
}
});