Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ COPY --from=build /app/web/dist /app/web/dist
COPY --from=build /app/node_modules /app/node_modules
COPY --from=build /app/bridge/node_modules /app/bridge/node_modules
COPY --from=build /app/bridge/package.json /app/bridge/package.json
USER node
COPY scripts/bridge-entrypoint.sh /usr/local/bin/bridge-entrypoint
EXPOSE 8080 7600
HEALTHCHECK --interval=15s --timeout=3s CMD node -e "fetch('http://127.0.0.1:8080/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
ENTRYPOINT ["/usr/local/bin/bridge-entrypoint"]
CMD ["node","bridge/dist/server.js"]
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,30 @@ scripts/venue.sh status
scripts/venue.sh down
```

The script builds `gated` in a detached temporary worktree, starts the standalone entrance at http://127.0.0.1:28080, and removes the worktree with `down`. For the Gate 3 crash scenario, build the revision before the fix in a separate detached worktree and pass `--gate3-crash DIR`; `down` includes `compose.gate3-crash.yaml` in cleanup. `scripts/e2e-gatepost.sh` runs the Playwright checks against an active entrance. The ticket file contains only synthetic barcodes.
The script builds `gated` in a detached temporary worktree, starts the standalone entrance at http://127.0.0.1:28080, and removes the worktree with `down`. For a revision with the hub, use `--ref main`. For the Gate 3 crash scenario, build the revision before the fix in a separate detached worktree and pass `--gate3-crash DIR`; `down` includes `compose.gate3-crash.yaml` in cleanup. `GATEPOST_REF=main scripts/e2e-gatepost.sh controls` starts a standalone entrance, checks real Docker network and power actions through the bridge WebSocket, and cleans up. Its other modes run the historical Playwright checks against an active entrance. The ticket file contains only synthetic barcodes.

`SIM_PORT` changes the local page port. `DOCKER_GID` defaults to the socket group. The bridge listens for the page on port 8080 inside its container, publishes only to host loopback, and accepts device TCP on the private `devices` network. `AUTO_PASS_MS` enables automatic passage after a relay opens. The bridge runs as the `node` user; it needs access to the Docker socket, usually via the socket's group ID.
`SIM_PORT` changes the local page port. The bridge listens for the page on port 8080 inside its container, publishes only to host loopback, and accepts device TCP on the private `devices` network. `AUTO_PASS_MS` enables automatic passage after a relay opens. At startup the bridge reads the mounted Docker socket's group inside the container, then runs as `node` with that supplementary group. The health endpoint and page report socket access.

## Browser messages

The browser WebSocket is `/ws`. The bridge sends `{ "type": "snapshot", "gates": [], "events": [], "tickets": [] }` and `{ "type": "error", "message": "..." }`. The browser sends `scan` (`gate`, `barcode`), `simultaneous` (`gates`, `barcode`), `burst` (`count`, `intervalMs`), `pass` (`gate`), `power` (`gate`, `on`), or `network` (`gate`, `on`). Gate IDs must be configured services. The event log records the wire lines and directions. The bridge does not decide ticket validity; `gated` does.
The browser WebSocket is `/ws`. The bridge sends `{ "type": "snapshot", "gates": [], "events": [], "tickets": [], "docker": { "ok": true, "message": "Docker socket accessible" } }` and `{ "type": "error", "message": "..." }`. The browser sends `scan` (`gate`, `barcode`), `simultaneous` (`gates`, `barcode`), `burst` (`count`, `intervalMs`), `pass` (`gate`), `power` (`gate`, `on`), or `network` (`gate`, `on`). Gate IDs must be configured services. The event log records the wire lines and directions. The bridge does not decide ticket validity; `gated` does.

## Development

Use Node 26.12.1 and pnpm 10.20.0. Run `pnpm install --frozen-lockfile`, then `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build`. `pnpm test:e2e` runs browser checks against a running bridge and fake gates. CI also builds the image, produces an SBOM, and scans it.

## Screenshots

Install headless Chromium with `pnpm exec playwright install chromium`, then capture light and dark pairs for Gate 3 stopping after an unknown barcode, two gates admitting one ticket before the race fix, exactly one gate admitting it after the fix, and offline admission at two gates. In the offline scene, Gate 2 admits a ticket with its cable unplugged and network LED off. Online Gate 1 then admits the same ticket through the hub, which has not heard of Gate 2's local admission. The event log labels each decision from the network LED reported by the gate.

```sh
GATEPOST_DIR=../gatepost \
GATE3_WORKING_REF="$gate3_fix" GATE3_CRASH_REF="$gate3_crash" \
DOUBLE_ADMISSION_BEFORE_REF="$race_before" DOUBLE_ADMISSION_FIXED_REF="$race_after" \
OFFLINE_ADMISSION_REF=69c5ea6 \
scripts/screenshots.sh
```

Choose each ref from your Gatepost checkout before running: `gate3_fix` is the revision after the Gate 3 crash fix; `gate3_crash` is a revision that still exhibits the crash; `race_after` is the revision with the hub race fix; `race_before` is a revision that still exhibits double admission. `OFFLINE_ADMISSION_REF` needs the hub client and network LED; `69c5ea6` has both. Use `git -C ../gatepost log --oneline --all` to find them, then set those five shell variables. The script builds detached temporary worktrees, checks the historical behavior, writes 1440 × 900 screenshots at 2× device scale under `docs/screenshots/`, and runs Compose `down -v` for every entrance. See [screenshot notes](docs/screenshots/README.md).

The bridge has the Docker Engine socket mounted. Anyone who can use that socket can manage every container on the host. This local development service publishes its page only on 127.0.0.1 and checks the configured Compose project and service allow-list before power or network actions. The network control disconnects and reconnects only the venue network, saving its address, MAC and aliases; the private device network stays connected. The simulator models hardware commands, not radio, power-supply behavior, or scanner optics.
20 changes: 17 additions & 3 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,30 @@ scripts/venue.sh status
scripts/venue.sh down
```

脚本在独立的临时 worktree 中构建 `gated`,在 http://127.0.0.1:28080 启动入口;`down` 清理 Compose 项目和 worktree。要运行重现 Gate 3 崩溃的场景,在另一个独立 worktree 中构建崩溃修复前的提交,并以 `--gate3-crash DIR` 传入;`down` 会同时纳入 `compose.gate3-crash.yaml`。`scripts/e2e-gatepost.sh` 检查正在运行的入口。票据文件只含合成条码。
脚本在独立的临时 worktree 中构建 `gated`,在 http://127.0.0.1:28080 启动入口;`down` 清理 Compose 项目和 worktree。带 hub 的版本使用 `--ref main`。要运行重现 Gate 3 崩溃的场景,在另一个独立 worktree 中构建崩溃修复前的提交,并以 `--gate3-crash DIR` 传入;`down` 会同时纳入 `compose.gate3-crash.yaml`。`GATEPOST_REF=main scripts/e2e-gatepost.sh controls` 会启动独立入口,通过 bridge WebSocket 检查实际 Docker 网络与电源操作,然后清理;其他模式对运行中的入口执行历史 Playwright 检查。票据文件只含合成条码。

`SIM_PORT` 控制本地页面端口;`DOCKER_GID` 默认取 Docker socket 的组 ID。容器内页面端口为 8080,仅发布到主机回环地址;设备 TCP 只在私有 `devices` 网络监听。`AUTO_PASS_MS` 可配置转闸打开后的自动通行。bridge 以 `node` 用户运行,需要通过 socket 的组权限访问 Docker。
`SIM_PORT` 控制本地页面端口;容器内页面端口为 8080,仅发布到主机回环地址;设备 TCP 只在私有 `devices` 网络监听。`AUTO_PASS_MS` 可配置转闸打开后的自动通行。bridge 启动时读取容器内 Docker socket 的组 ID,再以带该附加组的 `node` 用户运行。健康检查和页面都会显示 socket 的访问状态。

## 浏览器消息

WebSocket 路径是 `/ws`。bridge 发送 `snapshot`(含 `gates`、`events`、`tickets`)或 `error`(含 `message`)。浏览器发送 `scan`(`gate`、`barcode`)、`simultaneous`(`gates`、`barcode`)、`burst`(`count`、`intervalMs`)、`pass`(`gate`)、`power` 或 `network`(`gate`、`on`)。闸机 ID 必须属于配置的服务。事件日志记录协议行与方向。票据是否有效由 `gated` 决定。
WebSocket 路径是 `/ws`。bridge 发送 `snapshot`(含 `gates`、`events`、`tickets` 和 Docker socket 的 `docker` 状态)或 `error`(含 `message`)。浏览器发送 `scan`(`gate`、`barcode`)、`simultaneous`(`gates`、`barcode`)、`burst`(`count`、`intervalMs`)、`pass`(`gate`)、`power` 或 `network`(`gate`、`on`)。闸机 ID 必须属于配置的服务。事件日志记录协议行与方向。票据是否有效由 `gated` 决定。

## 开发与限制

使用 Node 26.12.1 与 pnpm 10.20.0。运行 `pnpm install --frozen-lockfile`,再运行 `pnpm lint`、`pnpm typecheck`、`pnpm test`、`pnpm build`。`pnpm test:e2e` 在 bridge 与假闸机运行时检查页面。CI 还构建镜像、生成 SBOM 并扫描漏洞。

## 截图

先运行 `pnpm exec playwright install chromium` 安装无界面 Chromium,再为四个场景生成浅色和深色截图:Gate 3 遇到未知条码停止、修复前两台闸机同时放行同一票据、修复后仅一台闸机放行,以及两台闸机的离线放行。在离线场景中,Gate 2 的网线已拔出、网络灯熄灭,它独立放行一张票据;仍然在线的 Gate 1 随后通过 hub 放行同一票据,因为 hub 没有收到 Gate 2 的记录。事件日志依据闸机报告的网络灯状态标出决策来源。

```sh
GATEPOST_DIR=../gatepost \
GATE3_WORKING_REF="$gate3_fix" GATE3_CRASH_REF="$gate3_crash" \
DOUBLE_ADMISSION_BEFORE_REF="$race_before" DOUBLE_ADMISSION_FIXED_REF="$race_after" \
OFFLINE_ADMISSION_REF=69c5ea6 \
scripts/screenshots.sh
```

先用 `git -C ../gatepost log --oneline --all` 选择引用并设置 shell 变量:`gate3_fix` 是 Gate 3 崩溃修复后的版本,`gate3_crash` 是仍会发生该崩溃的版本;`race_after` 是 hub 竞态修复后的版本,`race_before` 是仍会重复放行的版本。`OFFLINE_ADMISSION_REF` 须包含 hub 客户端与网络灯,`69c5ea6` 符合要求。脚本在临时独立 worktree 中构建、验证历史行为,将 1440 × 900、设备缩放比例 2 的截图写入 `docs/screenshots/`,并对每次入口运行执行 Compose `down -v`。详见[截图说明](docs/screenshots/README.zh-CN.md)。

bridge 挂载了 Docker Engine socket。能够使用该 socket 的进程可以管理主机上的所有容器。因此本工具仅用于本地开发,页面只发布到 127.0.0.1;电源和网络操作会检查 Compose 项目与服务白名单。网络操作只断开并重新连接场馆网络,同时保存地址、MAC 与别名;私有设备网络保持连接。模拟器不模拟无线电、电源供电细节或扫码器光学特性。
17 changes: 15 additions & 2 deletions bridge/src/docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,23 @@ export function request(
}
async function checked(method: string, path: string, body?: unknown) {
const result = await request(method, path, body);
if (result.status >= 300)
throw new Error(`Docker ${method} ${path}: ${result.status} ${JSON.stringify(result.data)}`);
if (result.status >= 300) {
const message =
result.data && typeof result.data === 'object' && 'message' in result.data
? String(result.data.message)
: JSON.stringify(result.data);
throw new Error(`Docker API ${result.status}: ${message}`);
}
return result.data;
}
export async function socketHealth(): Promise<{ ok: boolean; message: string }> {
try {
await checked('GET', '/_ping');
return { ok: true, message: 'Docker socket accessible' };
} catch (error) {
return { ok: false, message: String(error) };
}
}
type Container = {
Id: string;
Config: { Labels: Record<string, string> };
Expand Down
29 changes: 19 additions & 10 deletions bridge/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import path from 'node:path';
import { WebSocketServer, WebSocket } from 'ws';
import { hello, Lines } from './protocol.js';
import { Model } from './state.js';
import { action } from './docker.js';
import { action, socketHealth } from './docker.js';
const port = Number(process.env.PORT || 8080),
devicePort = Number(process.env.DEVICE_PORT || 7600);
const webRoot = process.env.WEB_ROOT || path.resolve('web/dist');
Expand All @@ -18,13 +18,17 @@ const tickets = (
.filter(Boolean);
const gateIds = (process.env.GATE_SERVICES || 'gate1,gate2,gate3,gate4').split(',');
const clients = new Set<WebSocket>();
const model = new Model(
() => {
const data = JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets });
for (const ws of clients) if (ws.readyState === WebSocket.OPEN) ws.send(data);
},
Number(process.env.AUTO_PASS_MS || 0),
);
let docker = { ok: false, message: 'Checking Docker socket' };
void socketHealth().then((result) => {
docker = result;
if (!result.ok) console.error(`Docker socket unavailable: ${result.message}`);
publish();
});
function publish() {
const data = JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets, docker });
for (const ws of clients) if (ws.readyState === WebSocket.OPEN) ws.send(data);
}
const model = new Model(publish, Number(process.env.AUTO_PASS_MS || 0));
for (const id of gateIds) model.gate(id);
net
.createServer((socket) => {
Expand Down Expand Up @@ -65,7 +69,9 @@ const types: Record<string, string> = {
};
const server = http.createServer((req, res) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ ok: true }));
res
.writeHead(docker.ok ? 200 : 503, { 'Content-Type': 'application/json' })
.end(JSON.stringify({ ok: docker.ok, docker }));
return;
}
const name = req.url === '/' ? '/index.html' : decodeURIComponent((req.url || '').split('?')[0]);
Expand All @@ -87,7 +93,7 @@ const server = http.createServer((req, res) => {
const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('connection', (ws) => {
clients.add(ws);
ws.send(JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets }));
ws.send(JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets, docker }));
ws.on('close', () => clients.delete(ws));
ws.on('message', async (raw) => {
try {
Expand Down Expand Up @@ -122,10 +128,13 @@ wss.on('connection', (ws) => {
typeof msg.on === 'boolean'
) {
await action(msg.gate, msg.type, msg.on);
model.log(msg.gate, 'action', `${msg.type} ${msg.on ? 'on' : 'off'}`);
if (msg.type === 'power') model.setPower(msg.gate, msg.on);
else model.setNetwork(msg.gate, msg.on);
} else throw new Error('Invalid message');
} catch (error) {
console.error('Bridge action failed:', error);
model.log('?', 'error', String(error));
ws.send(JSON.stringify({ type: 'error', message: String(error) }));
}
});
Expand Down
11 changes: 9 additions & 2 deletions bridge/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,15 @@ export class Model {
this.log(id, 'ignored', line);
return;
}
if (parsed.kind === 'light') g.light = parsed.value;
else if (parsed.kind === 'net') g.netLed = parsed.value;
if (parsed.kind === 'light') {
g.light = parsed.value;
if (parsed.value !== 'OFF')
this.log(
id,
'decision',
`${g.netLed === 'ON' ? 'HUB' : 'LOCAL'} ${parsed.value === 'GREEN' ? 'ACCEPT' : 'REJECT'}`,
);
} else if (parsed.kind === 'net') g.netLed = parsed.value;
else {
g.relayUntil = Date.now() + parsed.ms;
setTimeout(() => {
Expand Down
23 changes: 23 additions & 0 deletions bridge/test/docker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,26 @@ it('checks inspected labels before a Docker action on a Unix socket', async () =
await action('gate1', 'power', false);
expect(calls.some((call) => call === 'POST /containers/container-1/kill')).toBe(true);
});

it('reports Docker API status and message from an inaccessible socket', async () => {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'gatepost-docker-test-'));
directories.push(directory);
const socket = path.join(directory, 'docker.sock');
process.env.DOCKER_SOCKET = socket;
const server = http.createServer((_req, res) => {
res
.writeHead(403, { 'Content-Type': 'application/json' })
.end(JSON.stringify({ message: 'permission denied' }));
});
servers.push(server);
await new Promise<void>((done) => server.listen(socket, done));
vi.resetModules();
const { action, socketHealth } = await import('../src/docker.js');
await expect(action('gate1', 'power', false)).rejects.toThrow(
'Docker API 403: permission denied',
);
await expect(socketHealth()).resolves.toEqual({
ok: false,
message: 'Error: Docker API 403: permission denied',
});
});
11 changes: 11 additions & 0 deletions bridge/test/state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,14 @@ it('separates streams, resets outputs on disconnect and does not resend scans af
next.destroy();
first.destroy();
});
it('labels admissions by the network LED reported with the decision', () => {
const model = new Model(() => {});
model.receive('gate2', 'LED NET OFF');
model.receive('gate2', 'LIGHT GREEN');
model.receive('gate1', 'LED NET ON');
model.receive('gate1', 'LIGHT GREEN');
expect(model.events.filter((event) => event.direction === 'decision')).toMatchObject([
{ gate: 'gate2', line: 'LOCAL ACCEPT' },
{ gate: 'gate1', line: 'HUB ACCEPT' },
]);
});
1 change: 0 additions & 1 deletion compose.devices.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ services:
bridge:
build: .
image: gatepost-sim:local
group_add: ['${DOCKER_GID:-0}']
ports: ['127.0.0.1:${SIM_PORT:-28080}:8080']
volumes:
- /var/run/docker.sock:/var/run/docker.sock
Expand Down
23 changes: 19 additions & 4 deletions docs/screenshots/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,23 @@ English | [简体中文](README.zh-CN.md)

# Demonstration screenshots

All screenshots use a 1440 × 900 light-theme Playwright viewport.
Every scenario has `<name>.png` (light) and `<name>.dark.png` (dark), captured in headless Chromium at a 1440 × 900 viewport and device scale 2.

| File | State and code ref | Command |
| ------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `gate3-stopped.png` | Gate 3 crash scenario, `2b4843b` plus Gate 3 crash revision `a058409` adapter | `pnpm exec playwright test e2e/real-gate3-stopped.spec.ts` |
Run from the repository root:

```sh
GATEPOST_DIR=../gatepost \
GATE3_WORKING_REF=2b4843b GATE3_CRASH_REF=a058409 \
DOUBLE_ADMISSION_BEFORE_REF=ed6ea9c DOUBLE_ADMISSION_FIXED_REF=69b11cd \
OFFLINE_ADMISSION_REF=69c5ea6 \
scripts/screenshots.sh
```

| Pair name | Scenario | Gatepost refs |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| `gate3-stopped` | Four accepted scans, a rejection, then Gate 3 stops on `UNKNOWN` while Gate 4 keeps working | `2b4843b` and crash revision `a058409` |
| `offline-double-admission` | Gate 2 admits locally with its cable unplugged and network LED off; online Gate 1 then admits the same ticket through the hub | `69c5ea6` |
| `double-admission-before-fix` | Both gates admit the same ticket | `ed6ea9c`, immediately before race fix `6b7659e` |
| `double-admission-fixed` | Exactly one gate admits on each of 30 tries | `69b11cd` |

Set the five ref variables to other commits when retaking the pairs. `OFFLINE_ADMISSION_REF` needs a hub client and network LED. The event log labels decisions using the LED reported by each gate. The filenames describe the documented scenarios and remain stable.
Loading
Loading