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
13 changes: 13 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## Why

## What changed

## How to verify

---

## 背景

## 改动

## 怎么验证
43 changes: 43 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: CI
on: [pull_request]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- run: npm install -g pnpm@10.20.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version-file: .nvmrc
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm lint
- run: pnpm typecheck
- run: pnpm test
- run: pnpm build
- run: pnpm exec playwright install --with-deps chromium
- name: Browser test with fake gates
run: |
PORT=28080 DEVICE_PORT=7600 node bridge/dist/server.js &
bridge_pid=$!
node scripts/fake-gates.mjs &
gates_pid=$!
trap 'kill $bridge_pid $gates_pid || true' EXIT
pnpm exec playwright test e2e/entrance.spec.ts
- run: docker build -t gatepost-sim:ci .
- uses: anchore/sbom-action@f8bdd1d8ac5e901a77a92f111440fdb1b593736b # v0.20.6
with:
image: gatepost-sim:ci
artifact-name: gatepost-sim.spdx.json
- uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: gatepost-sim:ci
format: table
exit-code: '1'
severity: CRITICAL,HIGH
18 changes: 18 additions & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
* @mateo-rossi @fatima-zahra
/bridge/ @mateo-rossi @fatima-zahra
/web/ @mateo-rossi @fatima-zahra
/scripts/ @mateo-rossi @fatima-zahra
/data/ @mateo-rossi @fatima-zahra
/compose.*.yaml @mateo-rossi @fatima-zahra
/compose.lab.yaml @yuki-tanaka @noah-williams
/bridge/test/ @noah-williams
/web/test/ @noah-williams
/e2e/ @noah-williams
/playwright.config.ts @noah-williams
/scripts/e2e-gatepost.sh @noah-williams
/scripts/real-controls.mjs @noah-williams
/scripts/screenshots.sh @noah-williams
/docs/screenshots/ @noah-williams
/.github/ @ingrid-larsen
/renovate.json @ingrid-larsen
/CODEOWNERS @ingrid-larsen
54 changes: 54 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
English | [简体中文](CONTRIBUTING.zh-CN.md)

# Contributing

Keep each pull request focused on one change. Include its tests and documentation, and update English and Chinese guides together.

## Branches and commits

Name branches `<type>/<topic>`, using a short, hyphenated topic, for example `fix/gate-controls`.

Use commit subjects of the form `type(scope): summary`. Use `feat`, `fix`, `test`, `docs`, `style`, `chore`, `ci`, `perf`, `refactor` or `revert` for the type. Name the affected area in the scope, such as `bridge`, `web`, `sim` or `repo`. Write the summary in the imperative, for example `fix(bridge): report failed power actions`.

## Before opening a pull request

Use the Node version in `.nvmrc` and pnpm 10.20.0, as specified by `package.json`. Run these commands from the repository root:

```sh
pnpm install --frozen-lockfile
pnpm lint
pnpm typecheck
pnpm test
pnpm build
pnpm exec playwright install --with-deps chromium
```

Run the browser checks with a bridge and four fake gates. Keep ports 28080 and 7600 free, and stop any existing simulator first. Run this block in Bash after the build:

```sh
(
set -e
PORT=28080 DEVICE_PORT=7600 node bridge/dist/server.js &
bridge_pid=$!
node scripts/fake-gates.mjs &
gates_pid=$!
trap 'kill "$bridge_pid" "$gates_pid" 2>/dev/null || true' EXIT
pnpm test:e2e
)
```

`pnpm test:e2e` runs `e2e/entrance.spec.ts`. The fake gates reconnect while the bridge starts. These checks cover the browser and simulated device connections. Changes to Docker controls, Compose files or Gatepost integration also need checks against a running entrance with Docker and a compatible Gatepost checkout. Include the exact revisions, commands and results in the pull request.

With Docker installed, check the image build:

```sh
docker build -t gatepost-sim:local .
```

Fix any failures and rerun the affected checks. Explain the reason for the change, what changed and how it was verified.

## Review and merge

Follow `CODEOWNERS` when requesting reviews. Mateo Rossi and Fatima Zahra own the simulator and device behaviour; Noah Williams owns tests and browser checks; Yuki Tanaka reviews routed lab changes; Ingrid Larsen owns CI. Obtain at least one approval from an owner of each touched area. Include the relevant security, network or operations owner when the change affects those responsibilities.

All required CI checks must be green before merge. CI runs on pull requests. Local checks are required before opening the pull request. CI also builds the container image, generates its SBOM and scans for high and critical vulnerabilities.
54 changes: 54 additions & 0 deletions CONTRIBUTING.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
[English](CONTRIBUTING.md) | 简体中文

# 贡献指南

每个拉取请求只处理一项改动,并附上相应的测试和文档。中英文指南应同步更新。

## 分支和提交

分支名采用 `<type>/<topic>`,主题要简短,单词之间用连字符连接,例如 `fix/gate-controls`。

提交标题采用 `type(scope): summary`。类型使用 `feat`、`fix`、`test`、`docs`、`style`、`chore`、`ci`、`perf`、`refactor` 或 `revert`。括号内写受影响的范围,例如 `bridge`、`web`、`sim` 或 `repo`。摘要使用祈使句,以动词原形说明要做的事,例如 `fix(bridge): report failed power actions`。

## 发起拉取请求前

使用 `.nvmrc` 指定的 Node 版本,以及 `package.json` 指定的 pnpm 10.20.0。在仓库根目录运行:

```sh
pnpm install --frozen-lockfile
pnpm lint
pnpm typecheck
pnpm test
pnpm build
pnpm exec playwright install --with-deps chromium
```

浏览器检查需要一个 bridge 和四台假设备。确保端口 28080 和 7600 空闲,并先停止已有的模拟器。构建完成后,在 Bash 中运行以下代码块:

```sh
(
set -e
PORT=28080 DEVICE_PORT=7600 node bridge/dist/server.js &
bridge_pid=$!
node scripts/fake-gates.mjs &
gates_pid=$!
trap 'kill "$bridge_pid" "$gates_pid" 2>/dev/null || true' EXIT
pnpm test:e2e
)
```

`pnpm test:e2e` 执行 `e2e/entrance.spec.ts`。bridge 启动期间,假设备会自动重连。这些检查覆盖浏览器和模拟设备连接。修改 Docker 控制、Compose 文件或 Gatepost 集成时,还须安装 Docker,准备兼容的 Gatepost 检出目录,并对运行中的入口进行检查。在拉取请求中写明准确的版本引用、命令和结果。

安装 Docker 后,检查镜像能否构建:

```sh
docker build -t gatepost-sim:local .
```

如有检查失败,修复后重新运行相关检查。在拉取请求中说明改动原因、具体改动和验证方式。

## 评审与合并

按照 `CODEOWNERS` 邀请评审。Mateo Rossi 和 Fatima Zahra 负责模拟器与设备行为;Noah Williams 负责测试和浏览器检查;Yuki Tanaka 评审路由实验环境的改动;Ingrid Larsen 负责 CI。每个受影响的领域都须至少有一名负责人批准。涉及安全、网络或运营职责时,也应邀请对应负责人参与。

合并前,所有必需的 CI 检查都必须通过。CI 在拉取请求上运行,发起拉取请求前须完成本地检查。CI 还会构建容器镜像、生成 SBOM,并扫描高危和严重漏洞。
23 changes: 23 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
FROM node:26.12.1-bookworm-slim@sha256:88e480776c6149ff1d098cd304f44bf18057fb5d284a3329b78162d29821e28c AS build
WORKDIR /app
RUN npm install -g pnpm@10.20.0
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY bridge/package.json bridge/package.json
COPY web/package.json web/package.json
RUN pnpm install --frozen-lockfile
COPY bridge bridge
COPY web web
RUN pnpm build
FROM node:26.12.1-bookworm-slim@sha256:88e480776c6149ff1d098cd304f44bf18057fb5d284a3329b78162d29821e28c
LABEL org.opencontainers.image.title="Gatepost entrance simulator" org.opencontainers.image.licenses="MIT"
ENV NODE_ENV=production PORT=8080 DEVICE_PORT=7600 WEB_ROOT=/app/web/dist
WORKDIR /app
COPY --from=build /app/bridge/dist /app/bridge/dist
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
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))"
CMD ["node","bridge/dist/server.js"]
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
English | [简体中文](README.zh-CN.md)

# Gatepost simulator

This local entrance simulator gives device developers and venue staff a browser view of four synthetic gates. It models barcode scans, turnstile motion, lights, device connections, power and the venue network. It implements Gatepost's [device simulator protocol](../gatepost/docs/device/simulator-protocol.md).

## Run

Install Docker, then run from this repository:

```sh
scripts/venue.sh up --gatepost ../gatepost --ref 2b4843b --mode devices
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.

`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.

## 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.

## 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.

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.
29 changes: 29 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[English](README.md) | 简体中文

# Gatepost 模拟器

本地入口模拟器在浏览器中展示四个使用合成票据的闸机,供设备开发与场馆演示使用。它模拟扫码、转闸、指示灯、设备连接、电源和场馆网络,并实现 Gatepost 的[设备模拟协议](../gatepost/docs/device/simulator-protocol.zh-CN.md)。

## 运行

安装 Docker,在本仓库执行:

```sh
scripts/venue.sh up --gatepost ../gatepost --ref 2b4843b --mode devices
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` 检查正在运行的入口。票据文件只含合成条码。

`SIM_PORT` 控制本地页面端口;`DOCKER_GID` 默认取 Docker socket 的组 ID。容器内页面端口为 8080,仅发布到主机回环地址;设备 TCP 只在私有 `devices` 网络监听。`AUTO_PASS_MS` 可配置转闸打开后的自动通行。bridge 以 `node` 用户运行,需要通过 socket 的组权限访问 Docker。

## 浏览器消息

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` 决定。

## 开发与限制

使用 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 并扫描漏洞。

bridge 挂载了 Docker Engine socket。能够使用该 socket 的进程可以管理主机上的所有容器。因此本工具仅用于本地开发,页面只发布到 127.0.0.1;电源和网络操作会检查 Compose 项目与服务白名单。网络操作只断开并重新连接场馆网络,同时保存地址、MAC 与别名;私有设备网络保持连接。模拟器不模拟无线电、电源供电细节或扫码器光学特性。
4 changes: 2 additions & 2 deletions bridge/package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"name": "@gatepost-sim/bridge",
"version": "0.1.0-dev",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc",
"test": "vitest run --passWithNoTests",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
Expand Down
66 changes: 66 additions & 0 deletions bridge/test/docker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { afterEach, expect, it, vi } from 'vitest';
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { allowed } from '../src/docker.js';

const servers: http.Server[] = [];
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
servers.splice(0).map((server) => new Promise<void>((done) => server.close(() => done()))),
);
for (const directory of directories.splice(0))
fs.rmSync(directory, { recursive: true, force: true });
delete process.env.DOCKER_SOCKET;
vi.resetModules();
});

it('guards project, service and requested gate', () => {
const labels = {
'com.docker.compose.project': 'gatepost-sim-devices',
'com.docker.compose.service': 'gate1',
};
expect(allowed(labels, 'gate1')).toBe(true);
expect(allowed(labels, 'gate2')).toBe(false);
expect(allowed({ ...labels, 'com.docker.compose.project': 'foreign' }, 'gate1')).toBe(false);
});

it('checks inspected labels before a Docker action on a Unix 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 calls: string[] = [];
let projectLabel = 'foreign';
const server = http.createServer((req, res) => {
calls.push(`${req.method} ${req.url}`);
res.setHeader('Content-Type', 'application/json');
if (req.url?.startsWith('/containers/json')) res.end(JSON.stringify([{ Id: 'container-1' }]));
else if (req.url === '/containers/container-1/json')
res.end(
JSON.stringify({
Id: 'container-1',
Config: {
Labels: {
'com.docker.compose.project': projectLabel,
'com.docker.compose.service': 'gate1',
},
},
NetworkSettings: { Networks: {} },
}),
);
else res.writeHead(204).end();
});
servers.push(server);
await new Promise<void>((done) => server.listen(socket, done));
vi.resetModules();
const { action } = await import('../src/docker.js');
await expect(action('gate1', 'power', false)).rejects.toThrow('Container labels refused');
await expect(action('foreign-gate', 'power', false)).rejects.toThrow('Service not allowed');
expect(calls.some((call) => call.includes('/kill'))).toBe(false);
projectLabel = 'gatepost-sim-devices';
await action('gate1', 'power', false);
expect(calls.some((call) => call === 'POST /containers/container-1/kill')).toBe(true);
});
43 changes: 43 additions & 0 deletions bridge/test/protocol.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, it, expect } from 'vitest';
import { hello, output, Lines, scanLine } from '../src/protocol.js';
describe('wire protocol', () => {
it('recognizes both HELLO roles and rejects malformed lines', () => {
expect(hello('HELLO gate1 scanner 1')).toEqual({ gate: 'gate1', role: 'scanner' });
expect(hello('HELLO gate1 outputs 1')).toEqual({ gate: 'gate1', role: 'outputs' });
expect(hello('HELLO gate1 scanner 2')).toBeNull();
expect(hello('HELLO bad gate scanner 1')).toBeNull();
});
it('parses output commands and rejects unknown lines', () => {
expect(output('LIGHT GREEN')).toEqual({ kind: 'light', value: 'GREEN' });
expect(output('RELAY OPEN 2000')).toEqual({ kind: 'relay', ms: 2000 });
expect(output('LED NET OFF')).toEqual({ kind: 'net', value: 'OFF' });
expect(output('RELAY OPEN -2')).toBeNull();
expect(output('BOGUS')).toBeNull();
});
it('discards overlong and non-ASCII lines through LF', () => {
const lines: string[] = [],
bad: string[] = [];
const parser = new Lines();
parser.feed(
Buffer.from('A'.repeat(256)),
(l) => lines.push(l),
(r) => bad.push(r),
);
parser.feed(
Buffer.from('\nLIGHT GREEN\n'),
(l) => lines.push(l),
(r) => bad.push(r),
);
parser.feed(
Buffer.from([0xff, 10]),
(l) => lines.push(l),
(r) => bad.push(r),
);
expect(lines).toEqual(['LIGHT GREEN']);
expect(bad).toHaveLength(2);
});
it('bounds outgoing scans', () => {
expect(scanLine('GP-1')).toBe('SCAN GP-1\n');
expect(() => scanLine('a'.repeat(64))).toThrow();
});
});
Loading
Loading