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
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
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"]
19 changes: 19 additions & 0 deletions bridge/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "@gatepost-sim/bridge",
"version": "0.1.0-dev",
"private": true,
"type": "module",
"scripts": {
"build": "tsc",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"ws": "8.18.3"
},
"devDependencies": {
"@types/node": "26.6.6",
"@types/ws": "8.18.1",
"vitest": "5.0.5"
}
}
105 changes: 105 additions & 0 deletions bridge/src/docker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import http from 'node:http';
const project = process.env.COMPOSE_PROJECT_NAME || 'gatepost-sim-devices';
const services = (process.env.GATE_SERVICES || 'gate1,gate2,gate3,gate4').split(',');
const venueNetwork = process.env.VENUE_NETWORK || `${project}_venue`;
const socketPath = process.env.DOCKER_SOCKET || '/var/run/docker.sock';
export function allowed(labels: Record<string, string>, id: string) {
return (
labels['com.docker.compose.project'] === project &&
services.includes(labels['com.docker.compose.service']) &&
labels['com.docker.compose.service'] === id
);
}
export function request(
method: string,
path: string,
body?: unknown,
): Promise<{ status: number; data: unknown }> {
return new Promise((resolve, reject) => {
const payload = body === undefined ? undefined : JSON.stringify(body);
const req = http.request(
{
socketPath,
path,
method,
headers: payload
? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) }
: {},
},
(res) => {
let raw = '';
res.on('data', (chunk) => (raw += chunk));
res.on('end', () => {
let data: unknown = raw;
try {
data = JSON.parse(raw);
} catch {}
resolve({ status: res.statusCode || 0, data });
});
},
);
req.on('error', reject);
req.end(payload);
});
}
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)}`);
return result.data;
}
type Container = {
Id: string;
Config: { Labels: Record<string, string> };
NetworkSettings: {
Networks: Record<
string,
{
IPAMConfig?: { IPv4Address?: string; IPv6Address?: string } | null;
IPAddress?: string;
GlobalIPv6Address?: string;
MacAddress?: string;
Aliases?: string[];
}
>;
};
};
export async function action(id: string, kind: 'power' | 'network', on: boolean) {
if (!services.includes(id)) throw new Error('Service not allowed');
const list = (await checked(
'GET',
`/containers/json?all=1&filters=${encodeURIComponent(JSON.stringify({ label: [`com.docker.compose.project=${project}`, `com.docker.compose.service=${id}`] }))}`,
)) as { Id: string }[];
if (list.length !== 1) throw new Error(`Expected one container for ${id}, found ${list.length}`);
const container = (await checked('GET', `/containers/${list[0].Id}/json`)) as Container;
if (!allowed(container.Config.Labels || {}, id)) throw new Error('Container labels refused');
const cid = container.Id;
if (kind === 'power') await checked('POST', `/containers/${cid}/${on ? 'start' : 'kill'}`);
else {
const network = container.NetworkSettings.Networks[venueNetwork];
if (on) {
if (network) return;
const saved = networkSettings.get(cid);
if (!saved) throw new Error('Original network settings unavailable');
await checked('POST', `/networks/${encodeURIComponent(venueNetwork)}/connect`, {
Container: cid,
EndpointConfig: saved,
});
} else {
if (!network) return;
networkSettings.set(cid, {
IPAMConfig: network.IPAMConfig ?? {
IPv4Address: network.IPAddress,
IPv6Address: network.GlobalIPv6Address,
},
MacAddress: network.MacAddress,
Aliases: network.Aliases,
});
await checked('POST', `/networks/${encodeURIComponent(venueNetwork)}/disconnect`, {
Container: cid,
Force: false,
});
}
}
}
const networkSettings = new Map<string, unknown>();
48 changes: 48 additions & 0 deletions bridge/src/protocol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export type Role = 'scanner' | 'outputs';
export type Output =
| { kind: 'light'; value: 'GREEN' | 'RED' | 'OFF' }
| { kind: 'relay'; ms: number }
| { kind: 'net'; value: 'ON' | 'OFF' };
export function hello(line: string): { gate: string; role: Role } | null {
const match = /^HELLO ([!-~]{1,63}) (scanner|outputs) 1$/.exec(line);
return match && !/\s/.test(match[1]) ? { gate: match[1], role: match[2] as Role } : null;
}
export function output(line: string): Output | null {
if (line === 'LIGHT GREEN' || line === 'LIGHT RED' || line === 'LIGHT OFF')
return { kind: 'light', value: line.slice(6) as 'GREEN' | 'RED' | 'OFF' };
if (line === 'LED NET ON' || line === 'LED NET OFF')
return { kind: 'net', value: line.slice(8) as 'ON' | 'OFF' };
const relay = /^RELAY OPEN (0|[1-9][0-9]*)$/.exec(line);
if (relay && Number.isSafeInteger(Number(relay[1])) && Number(relay[1]) > 0)
return { kind: 'relay', ms: Number(relay[1]) };
return null;
}
export class Lines {
private pending = '';
private dropping = false;
feed(chunk: Buffer, onLine: (line: string) => void, onInvalid: (reason: string) => void) {
for (const byte of chunk) {
if (byte === 10) {
if (this.dropping) onInvalid('overlong line');
else if (/^[\x20-\x7e]*$/.test(this.pending)) onLine(this.pending);
else onInvalid('non-ASCII or malformed line');
this.pending = '';
this.dropping = false;
} else if (!this.dropping) {
if (byte < 32 || byte > 126) {
this.dropping = true;
continue;
}
if (this.pending.length >= 255) {
this.dropping = true;
continue;
}
this.pending += String.fromCharCode(byte);
}
}
}
}
export function scanLine(barcode: string) {
if (!/^[!-~]{1,63}$/.test(barcode) || /\s/.test(barcode)) throw new Error('Invalid barcode');
return `SCAN ${barcode}\n`;
}
133 changes: 133 additions & 0 deletions bridge/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import net from 'node:net';
import http from 'node:http';
import fs from 'node:fs';
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';
const port = Number(process.env.PORT || 8080),
devicePort = Number(process.env.DEVICE_PORT || 7600);
const webRoot = process.env.WEB_ROOT || path.resolve('web/dist');
const tickets = (
process.env.TICKET_FILE && fs.existsSync(process.env.TICKET_FILE)
? fs.readFileSync(process.env.TICKET_FILE, 'utf8')
: ''
)
.split(/\r?\n/)
.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),
);
for (const id of gateIds) model.gate(id);
net
.createServer((socket) => {
const lines = new Lines();
let identity: ReturnType<typeof hello> = null;
socket.on('data', (chunk) =>
lines.feed(
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk),
(line) => {
if (!identity) {
const parsed = hello(line);
if (!parsed || !gateIds.includes(parsed.gate)) {
model.log('?', 'ignored', line);
socket.destroy();
return;
}
identity = parsed;
model.attach(parsed.gate, parsed.role, socket);
model.log(parsed.gate, 'received', line);
return;
}
if (identity.role === 'outputs') model.receive(identity.gate, line);
else model.log(identity.gate, 'ignored', line);
},
(reason) => model.log(identity?.gate || '?', 'ignored', reason),
),
);
socket.on('close', () => {
if (identity) model.detach(identity.gate, identity.role, socket);
});
})
.listen(devicePort, '0.0.0.0');
const types: Record<string, string> = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.svg': 'image/svg+xml',
};
const server = http.createServer((req, res) => {
if (req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ ok: true }));
return;
}
const name = req.url === '/' ? '/index.html' : decodeURIComponent((req.url || '').split('?')[0]);
const file = path.resolve(webRoot, '.' + name);
if (!file.startsWith(path.resolve(webRoot) + path.sep)) {
res.writeHead(403).end();
return;
}
fs.readFile(file, (error, data) => {
if (error) {
res.writeHead(404).end();
return;
}
res
.writeHead(200, { 'Content-Type': types[path.extname(file)] || 'application/octet-stream' })
.end(data);
});
});
const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('connection', (ws) => {
clients.add(ws);
ws.send(JSON.stringify({ type: 'snapshot', ...model.snapshot(), tickets }));
ws.on('close', () => clients.delete(ws));
ws.on('message', async (raw) => {
try {
const msg = JSON.parse(raw.toString());
if (msg.type === 'scan' && typeof msg.gate === 'string' && typeof msg.barcode === 'string')
model.scan(msg.gate, msg.barcode);
else if (
msg.type === 'simultaneous' &&
Array.isArray(msg.gates) &&
typeof msg.barcode === 'string'
) {
for (const id of msg.gates) model.scan(id, msg.barcode);
} else if (
msg.type === 'burst' &&
Number.isInteger(msg.count) &&
msg.count > 0 &&
msg.count <= 200 &&
Number.isInteger(msg.intervalMs) &&
msg.intervalMs >= 0 &&
msg.intervalMs <= 5000
) {
for (let i = 0; i < msg.count; i++)
setTimeout(() => {
try {
model.scan(gateIds[i % gateIds.length], tickets[i % tickets.length]);
} catch {}
}, i * msg.intervalMs);
} else if (msg.type === 'pass' && typeof msg.gate === 'string') model.pass(msg.gate);
else if (
(msg.type === 'power' || msg.type === 'network') &&
typeof msg.gate === 'string' &&
typeof msg.on === 'boolean'
) {
await action(msg.gate, msg.type, msg.on);
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) {
ws.send(JSON.stringify({ type: 'error', message: String(error) }));
}
});
});
server.listen(port, '0.0.0.0');
Loading
Loading