Add Edge Agent implementation for gateway connection lifecycle, agent commands, Shelly device discovery, relay control, and WebSocket communication with broker. Include unit tests for critical flows.

This commit is contained in:
Jeppe Bundgaard
2026-04-08 19:01:42 +02:00
parent 653680376a
commit 45b7250480
101 changed files with 21583 additions and 16 deletions
+192 -1
View File
@@ -10888,6 +10888,34 @@ paths:
application/json:
schema: {}
/departments/daily-reports/overview:
get:
tags:
- Departments
summary: Get daily report overview
operationId: getDailyReportOverview
parameters:
- name: date
in: query
required: true
schema: {type: string}
- name: date_to
in: query
required: false
schema: {type: string}
- name: department_ids
in: query
required: true
schema:
type: string
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/DepartmentDailyReportOverviewResponse'
/departments/daily-reports/get:
get:
tags:
@@ -10964,7 +10992,36 @@ paths:
description: Success
content:
application/json:
schema: {}
schema:
$ref: '#/components/schemas/DepartmentDailyReportTransactionCountResponse'
/departments/daily-reports/outside-hours-trend:
get:
tags:
- Departments
summary: Get outside-hours trend for daily reports
operationId: getDailyReportOutsideHoursTrend
parameters:
- name: date
in: query
required: true
schema: {type: string}
- name: date_to
in: query
required: true
schema: {type: string}
- name: department_ids
in: query
required: true
schema:
type: string
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursTrendResponse'
/departments/daily-reports/bookings-count:
get:
@@ -16516,4 +16573,138 @@ components:
additionalProperties: true
example: []
DepartmentDailyReportOutsideHoursBreakdown:
type: object
properties:
orders: { type: integer }
xlvask: { type: integer }
selfserve: { type: integer }
DepartmentDailyReportOutsideHoursSummary:
type: object
properties:
department_ids:
type: array
items: { type: integer }
date: { type: string }
date_to: { type: string }
total: { type: integer }
by_source:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursBreakdown'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportMetric:
type: object
properties:
state: { type: string }
value:
type: number
nullable: true
out_of:
type: number
nullable: true
message:
type: string
nullable: true
by_source:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursBreakdown'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportProductTile:
type: object
properties:
product_id: { type: integer }
slug: { type: string }
title: { type: string }
state: { type: string }
value: { type: integer }
out_of: { type: integer }
DepartmentDailyReportOverviewPayload:
type: object
properties:
department_ids:
type: array
items: { type: integer }
date: { type: string }
date_to: { type: string }
metrics:
type: object
additionalProperties:
$ref: '#/components/schemas/DepartmentDailyReportMetric'
products:
type: array
items:
$ref: '#/components/schemas/DepartmentDailyReportProductTile'
DepartmentDailyReportOverviewResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportOverviewPayload'
DepartmentDailyReportTransactionCountPayload:
type: object
properties:
quantity: { type: integer }
products: { type: integer }
earnings: { type: integer }
washes: { type: integer }
water_usage: { type: integer }
date: { type: string }
date_to: { type: string }
department_id: { type: integer }
outside_hours:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursSummary'
DepartmentDailyReportTransactionCountResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportTransactionCountPayload'
DepartmentDailyReportOutsideHoursTrendPoint:
type: object
properties:
date: { type: string }
total: { type: integer }
by_source:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursBreakdown'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportOutsideHoursTrendPayload:
type: object
properties:
department_ids:
type: array
items: { type: integer }
date: { type: string }
date_to: { type: string }
points:
type: array
items:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursTrendPoint'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportOutsideHoursTrendResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursTrendPayload'
+378
View File
@@ -0,0 +1,378 @@
import { createHash } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
import { spawn } from "node:child_process";
import process from "node:process";
import WebSocket from "ws";
const DEFAULT_VERSION = "0.1.0";
export async function loadConfig(configPath) {
const raw = await fs.readFile(configPath, "utf8");
return JSON.parse(raw);
}
export async function saveConfig(configPath, config) {
await fs.writeFile(configPath, JSON.stringify(config, null, 2));
}
export function normalizeBrokerWsUrl(brokerUrl) {
if (!brokerUrl) {
throw new Error("Missing broker URL");
}
if (brokerUrl.startsWith("ws://") || brokerUrl.startsWith("wss://")) {
return brokerUrl;
}
return brokerUrl.replace(/^http:/i, "ws:").replace(/^https:/i, "wss:");
}
export async function apiRequest(baseUrl, path, method = "POST", body = {}, fetchImpl = fetch) {
const response = await fetchImpl(`${String(baseUrl).replace(/\/$/, "")}${path}`, {
method,
headers: {
"content-type": "application/json",
},
body: method === "GET" ? undefined : JSON.stringify(body),
});
const json = await response.json();
if (!response.ok) {
throw new Error(json?.data?.message || json?.message || `HTTP ${response.status}`);
}
return json.data ?? json;
}
export async function claimIfNeeded(config, configPath, fetchImpl = fetch) {
if (config.gatewayId && config.agentToken) {
return config;
}
const claimed = await apiRequest(config.apiUrl, "/edge-agent/claim", "POST", {
token: config.installToken,
hostname: config.hostname || os.hostname(),
installed_version: config.installedVersion || DEFAULT_VERSION,
metadata: {
platform: process.platform,
arch: process.arch,
},
}, fetchImpl);
const nextConfig = {
...config,
gatewayId: claimed.gateway.id,
agentToken: claimed.agent_token,
brokerUrl: claimed.broker_url || config.brokerUrl,
releaseChannel: claimed.release_channel || config.releaseChannel || "stable",
};
await saveConfig(configPath, nextConfig);
return nextConfig;
}
async function fetchJson(url, fetchImpl = fetch) {
const response = await fetchImpl(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
function expandCandidateIps(options = {}) {
if (Array.isArray(options.candidateIps) && options.candidateIps.length > 0) {
return options.candidateIps;
}
if (typeof options.subnetPrefix === "string") {
const start = Number.isInteger(options.startHost) ? options.startHost : 1;
const end = Number.isInteger(options.endHost) ? options.endHost : 20;
const ips = [];
for (let host = start; host <= end; host += 1) {
ips.push(`${options.subnetPrefix}.${host}`);
}
return ips;
}
return [];
}
export async function discoverShellyDevices(options = {}, fetchImpl = fetch) {
const candidateIps = expandCandidateIps(options);
const discovered = [];
await Promise.all(candidateIps.map(async (ip) => {
try {
const identity = await fetchJson(`http://${ip}/shelly`, fetchImpl);
discovered.push({
id: identity.mac || identity.id || ip,
device_id: identity.mac || identity.id || ip,
local_ip: ip,
model: identity.model || identity.type || "Shelly",
channel_count: Number(identity.num_outputs || identity.num_switches || 1),
online: true,
capabilities: {
generation: identity.gen || null,
},
metadata: identity,
});
} catch {
// Ignore non-responsive candidates during opportunistic discovery.
}
}));
return discovered;
}
export async function getRelayStatus(payload, fetchImpl = fetch) {
const ip = payload.localIp || payload.local_ip || payload.ip;
const channel = Number.isInteger(payload.channel) ? payload.channel : 0;
if (!ip) {
throw new Error("Missing relay local IP");
}
try {
const rpc = await fetchJson(`http://${ip}/rpc/Switch.GetStatus?id=${channel}`, fetchImpl);
return {
online: true,
on: Boolean(rpc.output),
raw: rpc,
};
} catch {
const legacy = await fetchJson(`http://${ip}/relay/${channel}`, fetchImpl);
return {
online: true,
on: Boolean(legacy.ison ?? legacy.output),
raw: legacy,
};
}
}
export async function setRelayState(payload, fetchImpl = fetch) {
const ip = payload.localIp || payload.local_ip || payload.ip;
const channel = Number.isInteger(payload.channel) ? payload.channel : 0;
const on = Boolean(payload.on);
if (!ip) {
throw new Error("Missing relay local IP");
}
try {
const rpc = await fetchJson(`http://${ip}/rpc/Switch.Set?id=${channel}&on=${on ? "true" : "false"}`, fetchImpl);
return {
online: true,
on: Boolean(rpc.output ?? on),
raw: rpc,
};
} catch {
const legacy = await fetchJson(`http://${ip}/relay/${channel}?turn=${on ? "on" : "off"}`, fetchImpl);
return {
online: true,
on: Boolean(legacy.ison ?? legacy.output ?? on),
raw: legacy,
};
}
}
export async function runUpdate(payload, fetchImpl = fetch) {
if (!payload.artifactUrl) {
return {
updated: false,
skipped: true,
reason: "No artifact URL provided",
};
}
const response = await fetchImpl(payload.artifactUrl);
if (!response.ok) {
throw new Error(`Artifact download failed: HTTP ${response.status}`);
}
const buffer = Buffer.from(await response.arrayBuffer());
const sha256 = createHash("sha256").update(buffer).digest("hex");
if (payload.sha256 && String(payload.sha256).toLowerCase() !== sha256.toLowerCase()) {
throw new Error("Artifact checksum mismatch");
}
return {
updated: true,
sha256,
bytes: buffer.length,
};
}
function defaultShellCommand() {
if (process.platform === "win32") {
return { command: process.env.ComSpec || "cmd.exe", args: [] };
}
return { command: process.env.SHELL || "/bin/sh", args: [] };
}
export function createShellBridge(sendMessage) {
const sessions = new Map();
const open = (payload = {}) => {
const sessionId = String(payload.sessionId);
const shell = payload.shellCommand ? { command: payload.shellCommand, args: payload.shellArgs || [] } : defaultShellCommand();
const proc = spawn(shell.command, shell.args, {
cwd: payload.cwd || process.cwd(),
env: process.env,
stdio: "pipe",
});
proc.stdout.on("data", (chunk) => {
sendMessage({ type: "SHELL_OUTPUT", sessionId, data: chunk.toString("utf8") });
});
proc.stderr.on("data", (chunk) => {
sendMessage({ type: "SHELL_OUTPUT", sessionId, data: chunk.toString("utf8") });
});
proc.on("close", (code) => {
sessions.delete(sessionId);
sendMessage({ type: "SHELL_EXIT", sessionId, code });
});
sessions.set(sessionId, proc);
sendMessage({ type: "SHELL_OPENED", sessionId });
};
const input = (payload = {}) => {
const proc = sessions.get(String(payload.sessionId));
if (!proc) {
return;
}
proc.stdin.write(String(payload.data || ""));
};
const close = (payload = {}) => {
const sessionId = String(payload.sessionId);
const proc = sessions.get(sessionId);
if (!proc) {
return;
}
proc.kill();
sessions.delete(sessionId);
};
return { open, input, close };
}
export async function handleAgentCommand(command, deps = {}) {
const fetchImpl = deps.fetchImpl || fetch;
switch (command.commandType) {
case "DISCOVER_SHELLY":
return { inventory: await discoverShellyDevices(command.payload || {}, fetchImpl) };
case "GET_RELAY_STATUS":
return await getRelayStatus(command.payload || {}, fetchImpl);
case "SET_RELAY_STATE":
return await setRelayState(command.payload || {}, fetchImpl);
case "RUN_UPDATE":
return await runUpdate(command.payload || {}, fetchImpl);
case "RESTART_AGENT":
return { restarted: true };
case "REBOOT_HOST":
return { rebooted: true };
default:
throw new Error(`Unsupported agent command: ${command.commandType}`);
}
}
export function buildHeartbeatPayload(config, extra = {}) {
return {
hostname: os.hostname(),
installed_version: config.installedVersion || DEFAULT_VERSION,
target_version: config.targetVersion || config.installedVersion || DEFAULT_VERSION,
status: extra.status || "ONLINE",
discovery_status: extra.discovery_status || "READY",
inventory: extra.inventory || [],
metadata: {
release_channel: config.releaseChannel || "stable",
...extra.metadata,
},
};
}
export async function sendHeartbeat(config, fetchImpl = fetch, extra = {}) {
if (!config.gatewayId || !config.agentToken) {
throw new Error("Gateway claim must complete before heartbeat");
}
return apiRequest(
config.apiUrl,
`/edge-agent/gateways/${config.gatewayId}/heartbeat`,
"POST",
{
agent_token: config.agentToken,
...buildHeartbeatPayload(config, extra),
},
fetchImpl
);
}
export function connectBroker(config, { fetchImpl = fetch, wsFactory = (url) => new WebSocket(url) } = {}) {
const shell = createShellBridge((message) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message));
}
});
const wsUrl = `${normalizeBrokerWsUrl(config.brokerUrl)}/ws/agent?gatewayId=${encodeURIComponent(config.gatewayId)}&token=${encodeURIComponent(config.agentToken)}`;
const socket = wsFactory(wsUrl);
socket.on("message", async (raw) => {
const message = JSON.parse(raw.toString());
try {
if (message.type === "COMMAND") {
const payload = await handleAgentCommand({
commandType: message.commandType,
payload: message.payload || {},
}, { fetchImpl });
socket.send(JSON.stringify({
type: "COMMAND_RESULT",
commandId: message.commandId,
ok: true,
payload,
}));
return;
}
if (message.type === "OPEN_ROOT_SHELL") {
shell.open(message.payload || {});
} else if (message.type === "SHELL_INPUT") {
shell.input(message.payload || {});
} else if (message.type === "CLOSE_ROOT_SHELL") {
shell.close(message.payload || {});
}
} catch (error) {
socket.send(JSON.stringify({
type: "COMMAND_RESULT",
commandId: message.commandId,
ok: false,
error: error instanceof Error ? error.message : String(error),
}));
}
});
return socket;
}
export async function startAgent({ configPath, fetchImpl = fetch, wsFactory } = {}) {
if (!configPath) {
throw new Error("Missing --config path");
}
let config = await loadConfig(configPath);
config = await claimIfNeeded(config, configPath, fetchImpl);
await sendHeartbeat(config, fetchImpl);
const socket = connectBroker(config, { fetchImpl, wsFactory });
const intervalMs = Number(config.heartbeatIntervalSeconds || 15) * 1000;
const timer = setInterval(() => {
sendHeartbeat(config, fetchImpl).catch(() => {});
}, intervalMs);
socket.on("close", () => clearInterval(timer));
return { socket, timer, config };
}
if (import.meta.url === `file://${process.argv[1]}`) {
const configFlagIndex = process.argv.indexOf("--config");
const configPath = configFlagIndex >= 0 ? process.argv[configFlagIndex + 1] : null;
startAgent({ configPath }).catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
+8
View File
@@ -0,0 +1,8 @@
{
"name": "truckwash-edge-agent",
"private": true,
"type": "module",
"dependencies": {
"ws": "^8.18.0"
}
}
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
Copyright (c) 2013 Arnout Kazemier and contributors
Copyright (c) 2016 Luigi Pinca and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+548
View File
@@ -0,0 +1,548 @@
# ws: a Node.js WebSocket library
[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws)
[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster)
[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws)
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation.
Passes the quite extensive Autobahn test suite: [server][server-report],
[client][client-report].
**Note**: This module does not work in the browser. The client in the docs is a
reference to a backend with the role of a client in the WebSocket communication.
Browser clients must use the native
[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
object. To make the same code work seamlessly on Node.js and the browser, you
can use one of the many wrappers available on npm, like
[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws).
## Table of Contents
- [Protocol support](#protocol-support)
- [Installing](#installing)
- [Opt-in for performance](#opt-in-for-performance)
- [Legacy opt-in for performance](#legacy-opt-in-for-performance)
- [API docs](#api-docs)
- [WebSocket compression](#websocket-compression)
- [Usage examples](#usage-examples)
- [Sending and receiving text data](#sending-and-receiving-text-data)
- [Sending binary data](#sending-binary-data)
- [Simple server](#simple-server)
- [External HTTP/S server](#external-https-server)
- [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server)
- [Client authentication](#client-authentication)
- [Server broadcast](#server-broadcast)
- [Round-trip time](#round-trip-time)
- [Use the Node.js streams API](#use-the-nodejs-streams-api)
- [Other examples](#other-examples)
- [FAQ](#faq)
- [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client)
- [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections)
- [How to connect via a proxy?](#how-to-connect-via-a-proxy)
- [Changelog](#changelog)
- [License](#license)
## Protocol support
- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`)
- **HyBi drafts 13-17** (Current default, alternatively option
`protocolVersion: 13`)
## Installing
```
npm install ws
```
### Opt-in for performance
[bufferutil][] is an optional module that can be installed alongside the ws
module:
```
npm install --save-optional bufferutil
```
This is a binary addon that improves the performance of certain operations such
as masking and unmasking the data payload of the WebSocket frames. Prebuilt
binaries are available for the most popular platforms, so you don't necessarily
need to have a C++ compiler installed on your machine.
To force ws to not use bufferutil, use the
[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) environment variable. This
can be useful to enhance security in systems where a user can put a package in
the package search path of an application of another user, due to how the
Node.js resolver algorithm works.
#### Legacy opt-in for performance
If you are running on an old version of Node.js (prior to v18.14.0), ws also
supports the [utf-8-validate][] module:
```
npm install --save-optional utf-8-validate
```
This contains a binary polyfill for [`buffer.isUtf8()`][].
To force ws not to use utf-8-validate, use the
[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment variable.
## API docs
See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and
utility functions.
## WebSocket compression
ws supports the [permessage-deflate extension][permessage-deflate] which enables
the client and server to negotiate a compression algorithm and its parameters,
and then selectively apply it to the data payloads of each WebSocket message.
The extension is disabled by default on the server and enabled by default on the
client. It adds a significant overhead in terms of performance and memory
consumption so we suggest to enable it only if it is really needed.
Note that Node.js has a variety of issues with high-performance compression,
where increased concurrency, especially on Linux, can lead to [catastrophic
memory fragmentation][node-zlib-bug] and slow performance. If you intend to use
permessage-deflate in production, it is worthwhile to set up a test
representative of your workload and ensure Node.js/zlib will handle it with
acceptable performance and memory usage.
Tuning of permessage-deflate can be done via the options defined below. You can
also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly
into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
See [the docs][ws-server-options] for more options.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({
port: 8080,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled.
}
});
```
The client will only use the extension if it is supported and enabled on the
server. To always disable the extension on the client, set the
`perMessageDeflate` option to `false`.
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path', {
perMessageDeflate: false
});
```
## Usage examples
### Sending and receiving text data
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});
```
### Sending binary data
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
const array = new Float32Array(5);
for (var i = 0; i < array.length; ++i) {
array[i] = i / 2;
}
ws.send(array);
});
```
### Simple server
```js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
```
### External HTTP/S server
```js
import { createServer } from 'https';
import { readFileSync } from 'fs';
import { WebSocketServer } from 'ws';
const server = createServer({
cert: readFileSync('/path/to/cert.pem'),
key: readFileSync('/path/to/key.pem')
});
const wss = new WebSocketServer({ server });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
server.listen(8080);
```
### Multiple servers sharing a single HTTP/S server
```js
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });
wss1.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
wss2.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
server.on('upgrade', function upgrade(request, socket, head) {
const { pathname } = new URL(request.url, 'wss://base.url');
if (pathname === '/foo') {
wss1.handleUpgrade(request, socket, head, function done(ws) {
wss1.emit('connection', ws, request);
});
} else if (pathname === '/bar') {
wss2.handleUpgrade(request, socket, head, function done(ws) {
wss2.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
server.listen(8080);
```
### Client authentication
```js
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
function onSocketError(err) {
console.error(err);
}
const server = createServer();
const wss = new WebSocketServer({ noServer: true });
wss.on('connection', function connection(ws, request, client) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log(`Received message ${data} from user ${client}`);
});
});
server.on('upgrade', function upgrade(request, socket, head) {
socket.on('error', onSocketError);
// This function is not defined on purpose. Implement it with your own logic.
authenticate(request, function next(err, client) {
if (err || !client) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
socket.removeListener('error', onSocketError);
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request, client);
});
});
});
server.listen(8080);
```
Also see the provided [example][session-parse-example] using `express-session`.
### Server broadcast
A client WebSocket broadcasting to all connected WebSocket clients, including
itself.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});
```
A client WebSocket broadcasting to every other connected WebSocket clients,
excluding itself.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});
```
### Round-trip time
```js
import WebSocket from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
ws.on('error', console.error);
ws.on('open', function open() {
console.log('connected');
ws.send(Date.now());
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function message(data) {
console.log(`Round-trip time: ${Date.now() - data} ms`);
setTimeout(function timeout() {
ws.send(Date.now());
}, 500);
});
```
### Use the Node.js streams API
```js
import WebSocket, { createWebSocketStream } from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
const duplex = createWebSocketStream(ws, { encoding: 'utf8' });
duplex.on('error', console.error);
duplex.pipe(process.stdout);
process.stdin.pipe(duplex);
```
### Other examples
For a full example with a browser client communicating with a ws server, see the
examples folder.
Otherwise, see the test cases.
## FAQ
### How to get the IP address of the client?
The remote IP address can be obtained from the raw socket.
```js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws, req) {
const ip = req.socket.remoteAddress;
ws.on('error', console.error);
});
```
When the server runs behind a proxy like NGINX, the de-facto standard is to use
the `X-Forwarded-For` header.
```js
wss.on('connection', function connection(ws, req) {
const ip = req.headers['x-forwarded-for'].split(',')[0].trim();
ws.on('error', console.error);
});
```
### How to detect and close broken connections?
Sometimes, the link between the server and the client can be interrupted in a
way that keeps both the server and the client unaware of the broken state of the
connection (e.g. when pulling the cord).
In these cases, ping messages can be used as a means to verify that the remote
endpoint is still responsive.
```js
import { WebSocketServer } from 'ws';
function heartbeat() {
this.isAlive = true;
}
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.isAlive = true;
ws.on('error', console.error);
ws.on('pong', heartbeat);
});
const interval = setInterval(function ping() {
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
wss.on('close', function close() {
clearInterval(interval);
});
```
Pong messages are automatically sent in response to ping messages as required by
the spec.
Just like the server example above, your clients might as well lose connection
without knowing it. You might want to add a ping listener on your clients to
prevent that. A simple implementation would be:
```js
import WebSocket from 'ws';
function heartbeat() {
clearTimeout(this.pingTimeout);
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
this.pingTimeout = setTimeout(() => {
this.terminate();
}, 30000 + 1000);
}
const client = new WebSocket('wss://websocket-echo.com/');
client.on('error', console.error);
client.on('open', heartbeat);
client.on('ping', heartbeat);
client.on('close', function clear() {
clearTimeout(this.pingTimeout);
});
```
### How to connect via a proxy?
Use a custom `http.Agent` implementation like [https-proxy-agent][] or
[socks-proxy-agent][].
## Changelog
We're using the GitHub [releases][changelog] for changelog entries.
## License
[MIT](LICENSE)
[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input
[bufferutil]: https://github.com/websockets/bufferutil
[changelog]: https://github.com/websockets/ws/releases
[client-report]: http://websockets.github.io/ws/autobahn/clients/
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[node-zlib-bug]: https://github.com/nodejs/node/issues/8871
[node-zlib-deflaterawdocs]:
https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
[permessage-deflate]: https://tools.ietf.org/html/rfc7692
[server-report]: http://websockets.github.io/ws/autobahn/servers/
[session-parse-example]: ./examples/express-session-parse
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[utf-8-validate]: https://github.com/websockets/utf-8-validate
[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback
+8
View File
@@ -0,0 +1,8 @@
'use strict';
module.exports = function () {
throw new Error(
'ws does not work in the browser. Browser clients must use the native ' +
'WebSocket object'
);
};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const createWebSocketStream = require('./lib/stream');
const extension = require('./lib/extension');
const PerMessageDeflate = require('./lib/permessage-deflate');
const Receiver = require('./lib/receiver');
const Sender = require('./lib/sender');
const subprotocol = require('./lib/subprotocol');
const WebSocket = require('./lib/websocket');
const WebSocketServer = require('./lib/websocket-server');
WebSocket.createWebSocketStream = createWebSocketStream;
WebSocket.extension = extension;
WebSocket.PerMessageDeflate = PerMessageDeflate;
WebSocket.Receiver = Receiver;
WebSocket.Sender = Sender;
WebSocket.Server = WebSocketServer;
WebSocket.subprotocol = subprotocol;
WebSocket.WebSocket = WebSocket;
WebSocket.WebSocketServer = WebSocketServer;
module.exports = WebSocket;
+131
View File
@@ -0,0 +1,131 @@
'use strict';
const { EMPTY_BUFFER } = require('./constants');
const FastBuffer = Buffer[Symbol.species];
/**
* Merges an array of buffers into a new buffer.
*
* @param {Buffer[]} list The array of buffers to concat
* @param {Number} totalLength The total length of buffers in the list
* @return {Buffer} The resulting buffer
* @public
*/
function concat(list, totalLength) {
if (list.length === 0) return EMPTY_BUFFER;
if (list.length === 1) return list[0];
const target = Buffer.allocUnsafe(totalLength);
let offset = 0;
for (let i = 0; i < list.length; i++) {
const buf = list[i];
target.set(buf, offset);
offset += buf.length;
}
if (offset < totalLength) {
return new FastBuffer(target.buffer, target.byteOffset, offset);
}
return target;
}
/**
* Masks a buffer using the given mask.
*
* @param {Buffer} source The buffer to mask
* @param {Buffer} mask The mask to use
* @param {Buffer} output The buffer where to store the result
* @param {Number} offset The offset at which to start writing
* @param {Number} length The number of bytes to mask.
* @public
*/
function _mask(source, mask, output, offset, length) {
for (let i = 0; i < length; i++) {
output[offset + i] = source[i] ^ mask[i & 3];
}
}
/**
* Unmasks a buffer using the given mask.
*
* @param {Buffer} buffer The buffer to unmask
* @param {Buffer} mask The mask to use
* @public
*/
function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask[i & 3];
}
}
/**
* Converts a buffer to an `ArrayBuffer`.
*
* @param {Buffer} buf The buffer to convert
* @return {ArrayBuffer} Converted buffer
* @public
*/
function toArrayBuffer(buf) {
if (buf.length === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
/**
* Converts `data` to a `Buffer`.
*
* @param {*} data The data to convert
* @return {Buffer} The buffer
* @throws {TypeError}
* @public
*/
function toBuffer(data) {
toBuffer.readOnly = true;
if (Buffer.isBuffer(data)) return data;
let buf;
if (data instanceof ArrayBuffer) {
buf = new FastBuffer(data);
} else if (ArrayBuffer.isView(data)) {
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
} else {
buf = Buffer.from(data);
toBuffer.readOnly = false;
}
return buf;
}
module.exports = {
concat,
mask: _mask,
toArrayBuffer,
toBuffer,
unmask: _unmask
};
/* istanbul ignore else */
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil = require('bufferutil');
module.exports.mask = function (source, mask, output, offset, length) {
if (length < 48) _mask(source, mask, output, offset, length);
else bufferUtil.mask(source, mask, output, offset, length);
};
module.exports.unmask = function (buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil.unmask(buffer, mask);
};
} catch (e) {
// Continue regardless of the error.
}
}
+19
View File
@@ -0,0 +1,19 @@
'use strict';
const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];
const hasBlob = typeof Blob !== 'undefined';
if (hasBlob) BINARY_TYPES.push('blob');
module.exports = {
BINARY_TYPES,
CLOSE_TIMEOUT: 30000,
EMPTY_BUFFER: Buffer.alloc(0),
GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
hasBlob,
kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
kListener: Symbol('kListener'),
kStatusCode: Symbol('status-code'),
kWebSocket: Symbol('websocket'),
NOOP: () => {}
};
+292
View File
@@ -0,0 +1,292 @@
'use strict';
const { kForOnEventAttribute, kListener } = require('./constants');
const kCode = Symbol('kCode');
const kData = Symbol('kData');
const kError = Symbol('kError');
const kMessage = Symbol('kMessage');
const kReason = Symbol('kReason');
const kTarget = Symbol('kTarget');
const kType = Symbol('kType');
const kWasClean = Symbol('kWasClean');
/**
* Class representing an event.
*/
class Event {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}
/**
* @type {*}
*/
get target() {
return this[kTarget];
}
/**
* @type {String}
*/
get type() {
return this[kType];
}
}
Object.defineProperty(Event.prototype, 'target', { enumerable: true });
Object.defineProperty(Event.prototype, 'type', { enumerable: true });
/**
* Class representing a close event.
*
* @extends Event
*/
class CloseEvent extends Event {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === undefined ? 0 : options.code;
this[kReason] = options.reason === undefined ? '' : options.reason;
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
}
Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
/**
* Class representing an error event.
*
* @extends Event
*/
class ErrorEvent extends Event {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === undefined ? null : options.error;
this[kMessage] = options.message === undefined ? '' : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
}
Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
/**
* Class representing a message event.
*
* @extends Event
*/
class MessageEvent extends Event {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);
this[kData] = options.data === undefined ? null : options.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
}
Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
/**
* This provides methods for emulating the `EventTarget` interface. It's not
* meant to be used directly.
*
* @mixin
*/
const EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options = {}) {
for (const listener of this.listeners(type)) {
if (
!options[kForOnEventAttribute] &&
listener[kListener] === handler &&
!listener[kForOnEventAttribute]
) {
return;
}
}
let wrapper;
if (type === 'message') {
wrapper = function onMessage(data, isBinary) {
const event = new MessageEvent('message', {
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'close') {
wrapper = function onClose(code, message) {
const event = new CloseEvent('close', {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'error') {
wrapper = function onError(error) {
const event = new ErrorEvent('error', {
error,
message: error.message
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'open') {
wrapper = function onOpen() {
const event = new Event('open');
event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
wrapper[kListener] = handler;
if (options.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},
/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener);
break;
}
}
}
};
module.exports = {
CloseEvent,
ErrorEvent,
Event,
EventTarget,
MessageEvent
};
/**
* Call an event listener
*
* @param {(Function|Object)} listener The listener to call
* @param {*} thisArg The value to use as `this`` when calling the listener
* @param {Event} event The event to pass to the listener
* @private
*/
function callListener(listener, thisArg, event) {
if (typeof listener === 'object' && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}
+203
View File
@@ -0,0 +1,203 @@
'use strict';
const { tokenChars } = require('./validation');
/**
* Adds an offer to the map of extension offers or a parameter to the map of
* parameters.
*
* @param {Object} dest The map of extension offers or parameters
* @param {String} name The extension or parameter name
* @param {(Object|Boolean|String)} elem The extension parameters or the
* parameter value
* @private
*/
function push(dest, name, elem) {
if (dest[name] === undefined) dest[name] = [elem];
else dest[name].push(elem);
}
/**
* Parses the `Sec-WebSocket-Extensions` header into an object.
*
* @param {String} header The field value of the header
* @return {Object} The parsed object
* @public
*/
function parse(header) {
const offers = Object.create(null);
let params = Object.create(null);
let mustUnescape = false;
let isEscaping = false;
let inQuotes = false;
let extensionName;
let paramName;
let start = -1;
let code = -1;
let end = -1;
let i = 0;
for (; i < header.length; i++) {
code = header.charCodeAt(i);
if (extensionName === undefined) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const name = header.slice(start, end);
if (code === 0x2c) {
push(offers, name, params);
params = Object.create(null);
} else {
extensionName = name;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (paramName === undefined) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 0x20 || code === 0x09) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b || code === 0x2c) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
push(params, header.slice(start, end), true);
if (code === 0x2c) {
push(offers, extensionName, params);
params = Object.create(null);
extensionName = undefined;
}
start = end = -1;
} else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
paramName = header.slice(start, i);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else {
//
// The value of a quoted-string after unescaping must conform to the
// token ABNF, so only token characters are valid.
// Ref: https://tools.ietf.org/html/rfc6455#section-9.1
//
if (isEscaping) {
if (tokenChars[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (start === -1) start = i;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 0x22 /* '"' */ && start !== -1) {
inQuotes = false;
end = i;
} else if (code === 0x5c /* '\' */) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
inQuotes = true;
} else if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (start !== -1 && (code === 0x20 || code === 0x09)) {
if (end === -1) end = i;
} else if (code === 0x3b || code === 0x2c) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
let value = header.slice(start, end);
if (mustUnescape) {
value = value.replace(/\\/g, '');
mustUnescape = false;
}
push(params, paramName, value);
if (code === 0x2c) {
push(offers, extensionName, params);
params = Object.create(null);
extensionName = undefined;
}
paramName = undefined;
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
}
if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
throw new SyntaxError('Unexpected end of input');
}
if (end === -1) end = i;
const token = header.slice(start, end);
if (extensionName === undefined) {
push(offers, token, params);
} else {
if (paramName === undefined) {
push(params, token, true);
} else if (mustUnescape) {
push(params, paramName, token.replace(/\\/g, ''));
} else {
push(params, paramName, token);
}
push(offers, extensionName, params);
}
return offers;
}
/**
* Builds the `Sec-WebSocket-Extensions` header field value.
*
* @param {Object} extensions The map of extensions and parameters to format
* @return {String} A string representing the given object
* @public
*/
function format(extensions) {
return Object.keys(extensions)
.map((extension) => {
let configurations = extensions[extension];
if (!Array.isArray(configurations)) configurations = [configurations];
return configurations
.map((params) => {
return [extension]
.concat(
Object.keys(params).map((k) => {
let values = params[k];
if (!Array.isArray(values)) values = [values];
return values
.map((v) => (v === true ? k : `${k}=${v}`))
.join('; ');
})
)
.join('; ');
})
.join(', ');
})
.join(', ');
}
module.exports = { format, parse };
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const kDone = Symbol('kDone');
const kRun = Symbol('kRun');
/**
* A very simple job queue with adjustable concurrency. Adapted from
* https://github.com/STRML/async-limiter
*/
class Limiter {
/**
* Creates a new `Limiter`.
*
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
* to run concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @param {Function} job The job to run
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
}
module.exports = Limiter;
+528
View File
@@ -0,0 +1,528 @@
'use strict';
const zlib = require('zlib');
const bufferUtil = require('./buffer-util');
const Limiter = require('./limiter');
const { kStatusCode } = require('./constants');
const FastBuffer = Buffer[Symbol.species];
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const kPerMessageDeflate = Symbol('permessage-deflate');
const kTotalLength = Symbol('total-length');
const kCallback = Symbol('callback');
const kBuffers = Symbol('buffers');
const kError = Symbol('error');
//
// We limit zlib concurrency, which prevents severe memory fragmentation
// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
// and https://github.com/websockets/ws/issues/1202
//
// Intentionally global; it's the global thread pool that's an issue.
//
let zlibLimiter;
/**
* permessage-deflate implementation.
*/
class PerMessageDeflate {
/**
* Creates a PerMessageDeflate instance.
*
* @param {Object} [options] Configuration options
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
* for, or request, a custom client window size
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
* acknowledge disabling of client context takeover
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
* calls to zlib
* @param {Boolean} [options.isServer=false] Create the instance in either
* server or client mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
* use of a custom server window size
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
* disabling of server context takeover
* @param {Number} [options.threshold=1024] Size (in bytes) below which
* messages should not be compressed if context takeover is disabled
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
* deflate
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
* inflate
*/
constructor(options) {
this._options = options || {};
this._threshold =
this._options.threshold !== undefined ? this._options.threshold : 1024;
this._maxPayload = this._options.maxPayload | 0;
this._isServer = !!this._options.isServer;
this._deflate = null;
this._inflate = null;
this.params = null;
if (!zlibLimiter) {
const concurrency =
this._options.concurrencyLimit !== undefined
? this._options.concurrencyLimit
: 10;
zlibLimiter = new Limiter(concurrency);
}
}
/**
* @type {String}
*/
static get extensionName() {
return 'permessage-deflate';
}
/**
* Create an extension negotiation offer.
*
* @return {Object} Extension parameters
* @public
*/
offer() {
const params = {};
if (this._options.serverNoContextTakeover) {
params.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
params.client_no_context_takeover = true;
}
if (this._options.serverMaxWindowBits) {
params.server_max_window_bits = this._options.serverMaxWindowBits;
}
if (this._options.clientMaxWindowBits) {
params.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (this._options.clientMaxWindowBits == null) {
params.client_max_window_bits = true;
}
return params;
}
/**
* Accept an extension negotiation offer/response.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Object} Accepted configuration
* @public
*/
accept(configurations) {
configurations = this.normalizeParams(configurations);
this.params = this._isServer
? this.acceptAsServer(configurations)
: this.acceptAsClient(configurations);
return this.params;
}
/**
* Releases all resources used by the extension.
*
* @public
*/
cleanup() {
if (this._inflate) {
this._inflate.close();
this._inflate = null;
}
if (this._deflate) {
const callback = this._deflate[kCallback];
this._deflate.close();
this._deflate = null;
if (callback) {
callback(
new Error(
'The deflate stream was closed while data was being processed'
)
);
}
}
}
/**
* Accept an extension negotiation offer.
*
* @param {Array} offers The extension negotiation offers
* @return {Object} Accepted configuration
* @private
*/
acceptAsServer(offers) {
const opts = this._options;
const accepted = offers.find((params) => {
if (
(opts.serverNoContextTakeover === false &&
params.server_no_context_takeover) ||
(params.server_max_window_bits &&
(opts.serverMaxWindowBits === false ||
(typeof opts.serverMaxWindowBits === 'number' &&
opts.serverMaxWindowBits > params.server_max_window_bits))) ||
(typeof opts.clientMaxWindowBits === 'number' &&
!params.client_max_window_bits)
) {
return false;
}
return true;
});
if (!accepted) {
throw new Error('None of the extension offers can be accepted');
}
if (opts.serverNoContextTakeover) {
accepted.server_no_context_takeover = true;
}
if (opts.clientNoContextTakeover) {
accepted.client_no_context_takeover = true;
}
if (typeof opts.serverMaxWindowBits === 'number') {
accepted.server_max_window_bits = opts.serverMaxWindowBits;
}
if (typeof opts.clientMaxWindowBits === 'number') {
accepted.client_max_window_bits = opts.clientMaxWindowBits;
} else if (
accepted.client_max_window_bits === true ||
opts.clientMaxWindowBits === false
) {
delete accepted.client_max_window_bits;
}
return accepted;
}
/**
* Accept the extension negotiation response.
*
* @param {Array} response The extension negotiation response
* @return {Object} Accepted configuration
* @private
*/
acceptAsClient(response) {
const params = response[0];
if (
this._options.clientNoContextTakeover === false &&
params.client_no_context_takeover
) {
throw new Error('Unexpected parameter "client_no_context_takeover"');
}
if (!params.client_max_window_bits) {
if (typeof this._options.clientMaxWindowBits === 'number') {
params.client_max_window_bits = this._options.clientMaxWindowBits;
}
} else if (
this._options.clientMaxWindowBits === false ||
(typeof this._options.clientMaxWindowBits === 'number' &&
params.client_max_window_bits > this._options.clientMaxWindowBits)
) {
throw new Error(
'Unexpected or invalid parameter "client_max_window_bits"'
);
}
return params;
}
/**
* Normalize parameters.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Array} The offers/response with normalized parameters
* @private
*/
normalizeParams(configurations) {
configurations.forEach((params) => {
Object.keys(params).forEach((key) => {
let value = params[key];
if (value.length > 1) {
throw new Error(`Parameter "${key}" must have only a single value`);
}
value = value[0];
if (key === 'client_max_window_bits') {
if (value !== true) {
const num = +value;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
value = num;
} else if (!this._isServer) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
} else if (key === 'server_max_window_bits') {
const num = +value;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
value = num;
} else if (
key === 'client_no_context_takeover' ||
key === 'server_no_context_takeover'
) {
if (value !== true) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
} else {
throw new Error(`Unknown parameter "${key}"`);
}
params[key] = value;
});
});
return configurations;
}
/**
* Decompress data. Concurrency limited.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
decompress(data, fin, callback) {
zlibLimiter.add((done) => {
this._decompress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Compress data. Concurrency limited.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
compress(data, fin, callback) {
zlibLimiter.add((done) => {
this._compress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Decompress data.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_decompress(data, fin, callback) {
const endpoint = this._isServer ? 'client' : 'server';
if (!this._inflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits =
typeof this.params[key] !== 'number'
? zlib.Z_DEFAULT_WINDOWBITS
: this.params[key];
this._inflate = zlib.createInflateRaw({
...this._options.zlibInflateOptions,
windowBits
});
this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
this._inflate.on('error', inflateOnError);
this._inflate.on('data', inflateOnData);
}
this._inflate[kCallback] = callback;
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
const err = this._inflate[kError];
if (err) {
this._inflate.close();
this._inflate = null;
callback(err);
return;
}
const data = bufferUtil.concat(
this._inflate[kBuffers],
this._inflate[kTotalLength]
);
if (this._inflate._readableState.endEmitted) {
this._inflate.close();
this._inflate = null;
} else {
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.reset();
}
}
callback(null, data);
});
}
/**
* Compress data.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_compress(data, fin, callback) {
const endpoint = this._isServer ? 'server' : 'client';
if (!this._deflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits =
typeof this.params[key] !== 'number'
? zlib.Z_DEFAULT_WINDOWBITS
: this.params[key];
this._deflate = zlib.createDeflateRaw({
...this._options.zlibDeflateOptions,
windowBits
});
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
this._deflate.on('data', deflateOnData);
}
this._deflate[kCallback] = callback;
this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
//
// The deflate stream was closed while data was being processed.
//
return;
}
let data = bufferUtil.concat(
this._deflate[kBuffers],
this._deflate[kTotalLength]
);
if (fin) {
data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
}
//
// Ensure that the callback will not be called again in
// `PerMessageDeflate#cleanup()`.
//
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
}
callback(null, data);
});
}
}
module.exports = PerMessageDeflate;
/**
* The listener of the `zlib.DeflateRaw` stream `'data'` event.
*
* @param {Buffer} chunk A chunk of data
* @private
*/
function deflateOnData(chunk) {
this[kBuffers].push(chunk);
this[kTotalLength] += chunk.length;
}
/**
* The listener of the `zlib.InflateRaw` stream `'data'` event.
*
* @param {Buffer} chunk A chunk of data
* @private
*/
function inflateOnData(chunk) {
this[kTotalLength] += chunk.length;
if (
this[kPerMessageDeflate]._maxPayload < 1 ||
this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
) {
this[kBuffers].push(chunk);
return;
}
this[kError] = new RangeError('Max payload size exceeded');
this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
this[kError][kStatusCode] = 1009;
this.removeListener('data', inflateOnData);
//
// The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the
// fact that in Node.js versions prior to 13.10.0, the callback for
// `zlib.flush()` is not called if `zlib.close()` is used. Utilizing
// `zlib.reset()` ensures that either the callback is invoked or an error is
// emitted.
//
this.reset();
}
/**
* The listener of the `zlib.InflateRaw` stream `'error'` event.
*
* @param {Error} err The emitted error
* @private
*/
function inflateOnError(err) {
//
// There is no need to call `Zlib#close()` as the handle is automatically
// closed when an error is emitted.
//
this[kPerMessageDeflate]._inflate = null;
if (this[kError]) {
this[kCallback](this[kError]);
return;
}
err[kStatusCode] = 1007;
this[kCallback](err);
}
+706
View File
@@ -0,0 +1,706 @@
'use strict';
const { Writable } = require('stream');
const PerMessageDeflate = require('./permessage-deflate');
const {
BINARY_TYPES,
EMPTY_BUFFER,
kStatusCode,
kWebSocket
} = require('./constants');
const { concat, toArrayBuffer, unmask } = require('./buffer-util');
const { isValidStatusCode, isValidUTF8 } = require('./validation');
const FastBuffer = Buffer[Symbol.species];
const GET_INFO = 0;
const GET_PAYLOAD_LENGTH_16 = 1;
const GET_PAYLOAD_LENGTH_64 = 2;
const GET_MASK = 3;
const GET_DATA = 4;
const INFLATING = 5;
const DEFER_EVENT = 6;
/**
* HyBi Receiver implementation.
*
* @extends Writable
*/
class Receiver extends Writable {
/**
* Creates a Receiver instance.
*
* @param {Object} [options] Options object
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {String} [options.binaryType=nodebuffer] The type for binary data
* @param {Object} [options.extensions] An object containing the negotiated
* extensions
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
* client or server mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
*/
constructor(options = {}) {
super();
this._allowSynchronousEvents =
options.allowSynchronousEvents !== undefined
? options.allowSynchronousEvents
: true;
this._binaryType = options.binaryType || BINARY_TYPES[0];
this._extensions = options.extensions || {};
this._isServer = !!options.isServer;
this._maxPayload = options.maxPayload | 0;
this._skipUTF8Validation = !!options.skipUTF8Validation;
this[kWebSocket] = undefined;
this._bufferedBytes = 0;
this._buffers = [];
this._compressed = false;
this._payloadLength = 0;
this._mask = undefined;
this._fragmented = 0;
this._masked = false;
this._fin = false;
this._opcode = 0;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragments = [];
this._errored = false;
this._loop = false;
this._state = GET_INFO;
}
/**
* Implements `Writable.prototype._write()`.
*
* @param {Buffer} chunk The chunk of data to write
* @param {String} encoding The character encoding of `chunk`
* @param {Function} cb Callback
* @private
*/
_write(chunk, encoding, cb) {
if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
this._bufferedBytes += chunk.length;
this._buffers.push(chunk);
this.startLoop(cb);
}
/**
* Consumes `n` bytes from the buffered data.
*
* @param {Number} n The number of bytes to consume
* @return {Buffer} The consumed bytes
* @private
*/
consume(n) {
this._bufferedBytes -= n;
if (n === this._buffers[0].length) return this._buffers.shift();
if (n < this._buffers[0].length) {
const buf = this._buffers[0];
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
return new FastBuffer(buf.buffer, buf.byteOffset, n);
}
const dst = Buffer.allocUnsafe(n);
do {
const buf = this._buffers[0];
const offset = dst.length - n;
if (n >= buf.length) {
dst.set(this._buffers.shift(), offset);
} else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
}
n -= buf.length;
} while (n > 0);
return dst;
}
/**
* Starts the parsing loop.
*
* @param {Function} cb Callback
* @private
*/
startLoop(cb) {
this._loop = true;
do {
switch (this._state) {
case GET_INFO:
this.getInfo(cb);
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16(cb);
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64(cb);
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData(cb);
break;
case INFLATING:
case DEFER_EVENT:
this._loop = false;
return;
}
} while (this._loop);
if (!this._errored) cb();
}
/**
* Reads the first two bytes of a frame.
*
* @param {Function} cb Callback
* @private
*/
getInfo(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
const buf = this.consume(2);
if ((buf[0] & 0x30) !== 0x00) {
const error = this.createError(
RangeError,
'RSV2 and RSV3 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_2_3'
);
cb(error);
return;
}
const compressed = (buf[0] & 0x40) === 0x40;
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
const error = this.createError(
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
cb(error);
return;
}
this._fin = (buf[0] & 0x80) === 0x80;
this._opcode = buf[0] & 0x0f;
this._payloadLength = buf[1] & 0x7f;
if (this._opcode === 0x00) {
if (compressed) {
const error = this.createError(
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
cb(error);
return;
}
if (!this._fragmented) {
const error = this.createError(
RangeError,
'invalid opcode 0',
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
cb(error);
return;
}
this._opcode = this._fragmented;
} else if (this._opcode === 0x01 || this._opcode === 0x02) {
if (this._fragmented) {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
cb(error);
return;
}
this._compressed = compressed;
} else if (this._opcode > 0x07 && this._opcode < 0x0b) {
if (!this._fin) {
const error = this.createError(
RangeError,
'FIN must be set',
true,
1002,
'WS_ERR_EXPECTED_FIN'
);
cb(error);
return;
}
if (compressed) {
const error = this.createError(
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
cb(error);
return;
}
if (
this._payloadLength > 0x7d ||
(this._opcode === 0x08 && this._payloadLength === 1)
) {
const error = this.createError(
RangeError,
`invalid payload length ${this._payloadLength}`,
true,
1002,
'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
);
cb(error);
return;
}
} else {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
cb(error);
return;
}
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 0x80) === 0x80;
if (this._isServer) {
if (!this._masked) {
const error = this.createError(
RangeError,
'MASK must be set',
true,
1002,
'WS_ERR_EXPECTED_MASK'
);
cb(error);
return;
}
} else if (this._masked) {
const error = this.createError(
RangeError,
'MASK must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_MASK'
);
cb(error);
return;
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else this.haveLength(cb);
}
/**
* Gets extended payload length (7+16).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength16(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
this._payloadLength = this.consume(2).readUInt16BE(0);
this.haveLength(cb);
}
/**
* Gets extended payload length (7+64).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength64(cb) {
if (this._bufferedBytes < 8) {
this._loop = false;
return;
}
const buf = this.consume(8);
const num = buf.readUInt32BE(0);
//
// The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
// if payload length is greater than this number.
//
if (num > Math.pow(2, 53 - 32) - 1) {
const error = this.createError(
RangeError,
'Unsupported WebSocket frame: payload length > 2^53 - 1',
false,
1009,
'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
);
cb(error);
return;
}
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
this.haveLength(cb);
}
/**
* Payload length has been read.
*
* @param {Function} cb Callback
* @private
*/
haveLength(cb) {
if (this._payloadLength && this._opcode < 0x08) {
this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
'Max payload size exceeded',
false,
1009,
'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
);
cb(error);
return;
}
}
if (this._masked) this._state = GET_MASK;
else this._state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask() {
if (this._bufferedBytes < 4) {
this._loop = false;
return;
}
this._mask = this.consume(4);
this._state = GET_DATA;
}
/**
* Reads data bytes.
*
* @param {Function} cb Callback
* @private
*/
getData(cb) {
let data = EMPTY_BUFFER;
if (this._payloadLength) {
if (this._bufferedBytes < this._payloadLength) {
this._loop = false;
return;
}
data = this.consume(this._payloadLength);
if (
this._masked &&
(this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
) {
unmask(data, this._mask);
}
}
if (this._opcode > 0x07) {
this.controlMessage(data, cb);
return;
}
if (this._compressed) {
this._state = INFLATING;
this.decompress(data, cb);
return;
}
if (data.length) {
//
// This message is not compressed so its length is the sum of the payload
// length of all fragments.
//
this._messageLength = this._totalPayloadLength;
this._fragments.push(data);
}
this.dataMessage(cb);
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @param {Function} cb Callback
* @private
*/
decompress(data, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
if (err) return cb(err);
if (buf.length) {
this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
'Max payload size exceeded',
false,
1009,
'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
);
cb(error);
return;
}
this._fragments.push(buf);
}
this.dataMessage(cb);
if (this._state === GET_INFO) this.startLoop(cb);
});
}
/**
* Handles a data message.
*
* @param {Function} cb Callback
* @private
*/
dataMessage(cb) {
if (!this._fin) {
this._state = GET_INFO;
return;
}
const messageLength = this._messageLength;
const fragments = this._fragments;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragmented = 0;
this._fragments = [];
if (this._opcode === 2) {
let data;
if (this._binaryType === 'nodebuffer') {
data = concat(fragments, messageLength);
} else if (this._binaryType === 'arraybuffer') {
data = toArrayBuffer(concat(fragments, messageLength));
} else if (this._binaryType === 'blob') {
data = new Blob(fragments);
} else {
data = fragments;
}
if (this._allowSynchronousEvents) {
this.emit('message', data, true);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit('message', data, true);
this._state = GET_INFO;
this.startLoop(cb);
});
}
} else {
const buf = concat(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
'invalid UTF-8 sequence',
true,
1007,
'WS_ERR_INVALID_UTF8'
);
cb(error);
return;
}
if (this._state === INFLATING || this._allowSynchronousEvents) {
this.emit('message', buf, false);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit('message', buf, false);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @return {(Error|RangeError|undefined)} A possible error
* @private
*/
controlMessage(data, cb) {
if (this._opcode === 0x08) {
if (data.length === 0) {
this._loop = false;
this.emit('conclude', 1005, EMPTY_BUFFER);
this.end();
} else {
const code = data.readUInt16BE(0);
if (!isValidStatusCode(code)) {
const error = this.createError(
RangeError,
`invalid status code ${code}`,
true,
1002,
'WS_ERR_INVALID_CLOSE_CODE'
);
cb(error);
return;
}
const buf = new FastBuffer(
data.buffer,
data.byteOffset + 2,
data.length - 2
);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
'invalid UTF-8 sequence',
true,
1007,
'WS_ERR_INVALID_UTF8'
);
cb(error);
return;
}
this._loop = false;
this.emit('conclude', code, buf);
this.end();
}
this._state = GET_INFO;
return;
}
if (this._allowSynchronousEvents) {
this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
/**
* Builds an error object.
*
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
* @param {String} message The error message
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
* `message`
* @param {Number} statusCode The status code
* @param {String} errorCode The exposed error code
* @return {(Error|RangeError)} The error
* @private
*/
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
this._loop = false;
this._errored = true;
const err = new ErrorCtor(
prefix ? `Invalid WebSocket frame: ${message}` : message
);
Error.captureStackTrace(err, this.createError);
err.code = errorCode;
err[kStatusCode] = statusCode;
return err;
}
}
module.exports = Receiver;
+602
View File
@@ -0,0 +1,602 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
'use strict';
const { Duplex } = require('stream');
const { randomFillSync } = require('crypto');
const PerMessageDeflate = require('./permessage-deflate');
const { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');
const { isBlob, isValidStatusCode } = require('./validation');
const { mask: applyMask, toBuffer } = require('./buffer-util');
const kByteLength = Symbol('kByteLength');
const maskBuffer = Buffer.alloc(4);
const RANDOM_POOL_SIZE = 8 * 1024;
let randomPool;
let randomPoolPointer = RANDOM_POOL_SIZE;
const DEFAULT = 0;
const DEFLATING = 1;
const GET_BLOB_DATA = 2;
/**
* HyBi Sender implementation.
*/
class Sender {
/**
* Creates a Sender instance.
*
* @param {Duplex} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/
constructor(socket, extensions, generateMask) {
this._extensions = extensions || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket;
this._firstFragment = true;
this._compress = false;
this._bufferedBytes = 0;
this._queue = [];
this._state = DEFAULT;
this.onerror = NOOP;
this[kWebSocket] = undefined;
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {(Buffer|String)} data The data to frame
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @return {(Buffer|String)[]} The framed data
* @public
*/
static frame(data, options) {
let mask;
let merge = false;
let offset = 2;
let skipMasking = false;
if (options.mask) {
mask = options.maskBuffer || maskBuffer;
if (options.generateMask) {
options.generateMask(mask);
} else {
if (randomPoolPointer === RANDOM_POOL_SIZE) {
/* istanbul ignore else */
if (randomPool === undefined) {
//
// This is lazily initialized because server-sent frames must not
// be masked so it may never be used.
//
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}
mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
offset = 6;
}
let dataLength;
if (typeof data === 'string') {
if (
(!options.mask || skipMasking) &&
options[kByteLength] !== undefined
) {
dataLength = options[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge = options.mask && options.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset += 8;
payloadLength = 127;
} else if (dataLength > 125) {
offset += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
if (options.rsv1) target[0] |= 0x40;
target[1] = payloadLength;
if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2);
} else if (payloadLength === 127) {
target[2] = target[3] = 0;
target.writeUIntBE(dataLength, 4, 6);
}
if (!options.mask) return [target, data];
target[1] |= 0x80;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge) {
applyMask(data, mask, target, offset, dataLength);
return [target];
}
applyMask(data, mask, data, 0, dataLength);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {Number} [code] The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
* @param {Function} [cb] Callback
* @public
*/
close(code, data, mask, cb) {
let buf;
if (code === undefined) {
buf = EMPTY_BUFFER;
} else if (typeof code !== 'number' || !isValidStatusCode(code)) {
throw new TypeError('First argument must be a valid error code number');
} else if (data === undefined || !data.length) {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError('The message must not be greater than 123 bytes');
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
if (typeof data === 'string') {
buf.write(data, 2);
} else {
buf.set(data, 2);
}
}
const options = {
[kByteLength]: buf.length,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x08,
readOnly: false,
rsv1: false
};
if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, buf, false, options, cb]);
} else {
this.sendFrame(Sender.frame(buf, options), cb);
}
}
/**
* Sends a ping message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
ping(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === 'string') {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x09,
readOnly,
rsv1: false
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb]);
} else {
this.getBlobData(data, false, options, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(Sender.frame(data, options), cb);
}
}
/**
* Sends a pong message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
pong(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === 'string') {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x0a,
readOnly,
rsv1: false
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb]);
} else {
this.getBlobData(data, false, options, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(Sender.frame(data, options), cb);
}
}
/**
* Sends a data message to the other peer.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
* or text
* @param {Boolean} [options.compress=false] Specifies whether or not to
* compress `data`
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Function} [cb] Callback
* @public
*/
send(data, options, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
let opcode = options.binary ? 2 : 1;
let rsv1 = options.compress;
let byteLength;
let readOnly;
if (typeof data === 'string') {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (this._firstFragment) {
this._firstFragment = false;
if (
rsv1 &&
perMessageDeflate &&
perMessageDeflate.params[
perMessageDeflate._isServer
? 'server_no_context_takeover'
: 'client_no_context_takeover'
]
) {
rsv1 = byteLength >= perMessageDeflate._threshold;
}
this._compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options.fin) this._firstFragment = true;
const opts = {
[kByteLength]: byteLength,
fin: options.fin,
generateMask: this._generateMask,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
} else {
this.getBlobData(data, this._compress, opts, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
} else {
this.dispatch(data, this._compress, opts, cb);
}
}
/**
* Gets the contents of a blob as binary data.
*
* @param {Blob} blob The blob
* @param {Boolean} [compress=false] Specifies whether or not to compress
* the data
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
getBlobData(blob, compress, options, cb) {
this._bufferedBytes += options[kByteLength];
this._state = GET_BLOB_DATA;
blob
.arrayBuffer()
.then((arrayBuffer) => {
if (this._socket.destroyed) {
const err = new Error(
'The socket was closed while the blob was being read'
);
//
// `callCallbacks` is called in the next tick to ensure that errors
// that might be thrown in the callbacks behave like errors thrown
// outside the promise chain.
//
process.nextTick(callCallbacks, this, err, cb);
return;
}
this._bufferedBytes -= options[kByteLength];
const data = toBuffer(arrayBuffer);
if (!compress) {
this._state = DEFAULT;
this.sendFrame(Sender.frame(data, options), cb);
this.dequeue();
} else {
this.dispatch(data, compress, options, cb);
}
})
.catch((err) => {
//
// `onError` is called in the next tick for the same reason that
// `callCallbacks` above is.
//
process.nextTick(onError, this, err, cb);
});
}
/**
* Dispatches a message.
*
* @param {(Buffer|String)} data The message to send
* @param {Boolean} [compress=false] Specifies whether or not to compress
* `data`
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
dispatch(data, compress, options, cb) {
if (!compress) {
this.sendFrame(Sender.frame(data, options), cb);
return;
}
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
this._bufferedBytes += options[kByteLength];
this._state = DEFLATING;
perMessageDeflate.compress(data, options.fin, (_, buf) => {
if (this._socket.destroyed) {
const err = new Error(
'The socket was closed while data was being compressed'
);
callCallbacks(this, err, cb);
return;
}
this._bufferedBytes -= options[kByteLength];
this._state = DEFAULT;
options.readOnly = false;
this.sendFrame(Sender.frame(buf, options), cb);
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (this._state === DEFAULT && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength];
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[3][kByteLength];
this._queue.push(params);
}
/**
* Sends a frame.
*
* @param {(Buffer | String)[]} list The frame to send
* @param {Function} [cb] Callback
* @private
*/
sendFrame(list, cb) {
if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]);
this._socket.write(list[1], cb);
this._socket.uncork();
} else {
this._socket.write(list[0], cb);
}
}
}
module.exports = Sender;
/**
* Calls queued callbacks with an error.
*
* @param {Sender} sender The `Sender` instance
* @param {Error} err The error to call the callbacks with
* @param {Function} [cb] The first callback
* @private
*/
function callCallbacks(sender, err, cb) {
if (typeof cb === 'function') cb(err);
for (let i = 0; i < sender._queue.length; i++) {
const params = sender._queue[i];
const callback = params[params.length - 1];
if (typeof callback === 'function') callback(err);
}
}
/**
* Handles a `Sender` error.
*
* @param {Sender} sender The `Sender` instance
* @param {Error} err The error
* @param {Function} [cb] The first pending callback
* @private
*/
function onError(sender, err, cb) {
callCallbacks(sender, err, cb);
sender.onerror(err);
}
+161
View File
@@ -0,0 +1,161 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */
'use strict';
const WebSocket = require('./websocket');
const { Duplex } = require('stream');
/**
* Emits the `'close'` event on a stream.
*
* @param {Duplex} stream The stream.
* @private
*/
function emitClose(stream) {
stream.emit('close');
}
/**
* The listener of the `'end'` event.
*
* @private
*/
function duplexOnEnd() {
if (!this.destroyed && this._writableState.finished) {
this.destroy();
}
}
/**
* The listener of the `'error'` event.
*
* @param {Error} err The error
* @private
*/
function duplexOnError(err) {
this.removeListener('error', duplexOnError);
this.destroy();
if (this.listenerCount('error') === 0) {
// Do not suppress the throwing behavior.
this.emit('error', err);
}
}
/**
* Wraps a `WebSocket` in a duplex stream.
*
* @param {WebSocket} ws The `WebSocket` to wrap
* @param {Object} [options] The options for the `Duplex` constructor
* @return {Duplex} The duplex stream
* @public
*/
function createWebSocketStream(ws, options) {
let terminateOnDestroy = true;
const duplex = new Duplex({
...options,
autoDestroy: false,
emitClose: false,
objectMode: false,
writableObjectMode: false
});
ws.on('message', function message(msg, isBinary) {
const data =
!isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
if (!duplex.push(data)) ws.pause();
});
ws.once('error', function error(err) {
if (duplex.destroyed) return;
// Prevent `ws.terminate()` from being called by `duplex._destroy()`.
//
// - If the `'error'` event is emitted before the `'open'` event, then
// `ws.terminate()` is a noop as no socket is assigned.
// - Otherwise, the error is re-emitted by the listener of the `'error'`
// event of the `Receiver` object. The listener already closes the
// connection by calling `ws.close()`. This allows a close frame to be
// sent to the other peer. If `ws.terminate()` is called right after this,
// then the close frame might not be sent.
terminateOnDestroy = false;
duplex.destroy(err);
});
ws.once('close', function close() {
if (duplex.destroyed) return;
duplex.push(null);
});
duplex._destroy = function (err, callback) {
if (ws.readyState === ws.CLOSED) {
callback(err);
process.nextTick(emitClose, duplex);
return;
}
let called = false;
ws.once('error', function error(err) {
called = true;
callback(err);
});
ws.once('close', function close() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
});
if (terminateOnDestroy) ws.terminate();
};
duplex._final = function (callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once('open', function open() {
duplex._final(callback);
});
return;
}
// If the value of the `_socket` property is `null` it means that `ws` is a
// client websocket and the handshake failed. In fact, when this happens, a
// socket is never assigned to the websocket. Wait for the `'error'` event
// that will be emitted by the websocket.
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
callback();
if (duplex._readableState.endEmitted) duplex.destroy();
} else {
ws._socket.once('finish', function finish() {
// `duplex` is not destroyed here because the `'end'` event will be
// emitted on `duplex` after this `'finish'` event. The EOF signaling
// `null` chunk is, in fact, pushed when the websocket emits `'close'`.
callback();
});
ws.close();
}
};
duplex._read = function () {
if (ws.isPaused) ws.resume();
};
duplex._write = function (chunk, encoding, callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once('open', function open() {
duplex._write(chunk, encoding, callback);
});
return;
}
ws.send(chunk, callback);
};
duplex.on('end', duplexOnEnd);
duplex.on('error', duplexOnError);
return duplex;
}
module.exports = createWebSocketStream;
+62
View File
@@ -0,0 +1,62 @@
'use strict';
const { tokenChars } = require('./validation');
/**
* Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
*
* @param {String} header The field value of the header
* @return {Set} The subprotocol names
* @public
*/
function parse(header) {
const protocols = new Set();
let start = -1;
let end = -1;
let i = 0;
for (i; i < header.length; i++) {
const code = header.charCodeAt(i);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x2c /* ',' */) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const protocol = header.slice(start, end);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError('Unexpected end of input');
}
const protocol = header.slice(start, i);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
return protocols;
}
module.exports = { parse };
+152
View File
@@ -0,0 +1,152 @@
'use strict';
const { isUtf8 } = require('buffer');
const { hasBlob } = require('./constants');
//
// Allowed token characters:
//
// '!', '#', '$', '%', '&', ''', '*', '+', '-',
// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
//
// tokenChars[32] === 0 // ' '
// tokenChars[33] === 1 // '!'
// tokenChars[34] === 0 // '"'
// ...
//
// prettier-ignore
const tokenChars = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
];
/**
* Checks if a status code is allowed in a close frame.
*
* @param {Number} code The status code
* @return {Boolean} `true` if the status code is valid, else `false`
* @public
*/
function isValidStatusCode(code) {
return (
(code >= 1000 &&
code <= 1014 &&
code !== 1004 &&
code !== 1005 &&
code !== 1006) ||
(code >= 3000 && code <= 4999)
);
}
/**
* Checks if a given buffer contains only correct UTF-8.
* Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
* Markus Kuhn.
*
* @param {Buffer} buf The buffer to check
* @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
* @public
*/
function _isValidUTF8(buf) {
const len = buf.length;
let i = 0;
while (i < len) {
if ((buf[i] & 0x80) === 0) {
// 0xxxxxxx
i++;
} else if ((buf[i] & 0xe0) === 0xc0) {
// 110xxxxx 10xxxxxx
if (
i + 1 === len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i] & 0xfe) === 0xc0 // Overlong
) {
return false;
}
i += 2;
} else if ((buf[i] & 0xf0) === 0xe0) {
// 1110xxxx 10xxxxxx 10xxxxxx
if (
i + 2 >= len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i + 2] & 0xc0) !== 0x80 ||
(buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
(buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
) {
return false;
}
i += 3;
} else if ((buf[i] & 0xf8) === 0xf0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (
i + 3 >= len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i + 2] & 0xc0) !== 0x80 ||
(buf[i + 3] & 0xc0) !== 0x80 ||
(buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
(buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
buf[i] > 0xf4 // > U+10FFFF
) {
return false;
}
i += 4;
} else {
return false;
}
}
return true;
}
/**
* Determines whether a value is a `Blob`.
*
* @param {*} value The value to be tested
* @return {Boolean} `true` if `value` is a `Blob`, else `false`
* @private
*/
function isBlob(value) {
return (
hasBlob &&
typeof value === 'object' &&
typeof value.arrayBuffer === 'function' &&
typeof value.type === 'string' &&
typeof value.stream === 'function' &&
(value[Symbol.toStringTag] === 'Blob' ||
value[Symbol.toStringTag] === 'File')
);
}
module.exports = {
isBlob,
isValidStatusCode,
isValidUTF8: _isValidUTF8,
tokenChars
};
if (isUtf8) {
module.exports.isValidUTF8 = function (buf) {
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
};
} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
try {
const isValidUTF8 = require('utf-8-validate');
module.exports.isValidUTF8 = function (buf) {
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
};
} catch (e) {
// Continue regardless of the error.
}
}
+554
View File
@@ -0,0 +1,554 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
'use strict';
const EventEmitter = require('events');
const http = require('http');
const { Duplex } = require('stream');
const { createHash } = require('crypto');
const extension = require('./extension');
const PerMessageDeflate = require('./permessage-deflate');
const subprotocol = require('./subprotocol');
const WebSocket = require('./websocket');
const { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');
const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
const RUNNING = 0;
const CLOSING = 1;
const CLOSED = 2;
/**
* Class representing a WebSocket server.
*
* @extends EventEmitter
*/
class WebSocketServer extends EventEmitter {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
* automatically send a pong in response to a ping
* @param {Number} [options.backlog=511] The maximum length of the queue of
* pending connections
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
* track clients
* @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
* wait for the closing handshake to finish after `websocket.close()` is
* called
* @param {Function} [options.handleProtocols] A hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Boolean} [options.noServer=false] Enable no server mode
* @param {String} [options.path] Accept only connections matching this path
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/
constructor(options, callback) {
super();
options = {
allowSynchronousEvents: true,
autoPong: true,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false,
handleProtocols: null,
clientTracking: true,
closeTimeout: CLOSE_TIMEOUT,
verifyClient: null,
noServer: false,
backlog: null, // use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null,
WebSocket,
...options
};
if (
(options.port == null && !options.server && !options.noServer) ||
(options.port != null && (options.server || options.noServer)) ||
(options.server && options.noServer)
) {
throw new TypeError(
'One and only one of the "port", "server", or "noServer" options ' +
'must be specified'
);
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
res.end(body);
});
this._server.listen(
options.port,
options.host,
options.backlog,
callback
);
} else if (options.server) {
this._server = options.server;
}
if (this._server) {
const emitConnection = this.emit.bind(this, 'connection');
this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, 'listening'),
error: this.emit.bind(this, 'error'),
upgrade: (req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection);
}
});
}
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
if (options.clientTracking) {
this.clients = new Set();
this._shouldEmitClose = false;
}
this.options = options;
this._state = RUNNING;
}
/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address() {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}
if (!this._server) return null;
return this._server.address();
}
/**
* Stop the server from accepting new connections and emit the `'close'` event
* when all existing connections are closed.
*
* @param {Function} [cb] A one-time listener for the `'close'` event
* @public
*/
close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once('close', () => {
cb(new Error('The server is not running'));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once('close', cb);
if (this._state === CLOSING) return;
this._state = CLOSING;
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) {
if (!this.clients.size) {
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
}
} else {
process.nextTick(emitClose, this);
}
} else {
const server = this._server;
this._removeListeners();
this._removeListeners = this._server = null;
//
// The HTTP/S server was created internally. Close it, and rely on its
// `'close'` event.
//
server.close(() => {
emitClose(this);
});
}
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle(req) {
if (this.options.path) {
const index = req.url.indexOf('?');
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
if (pathname !== this.options.path) return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade(req, socket, head, cb) {
socket.on('error', socketOnError);
const key = req.headers['sec-websocket-key'];
const upgrade = req.headers.upgrade;
const version = +req.headers['sec-websocket-version'];
if (req.method !== 'GET') {
const message = 'Invalid HTTP method';
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
return;
}
if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
const message = 'Invalid Upgrade header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (key === undefined || !keyRegex.test(key)) {
const message = 'Missing or invalid Sec-WebSocket-Key header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (version !== 13 && version !== 8) {
const message = 'Missing or invalid Sec-WebSocket-Version header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
'Sec-WebSocket-Version': '13, 8'
});
return;
}
if (!this.shouldHandle(req)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
let protocols = new Set();
if (secWebSocketProtocol !== undefined) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err) {
const message = 'Invalid Sec-WebSocket-Protocol header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
const extensions = {};
if (
this.options.perMessageDeflate &&
secWebSocketExtensions !== undefined
) {
const perMessageDeflate = new PerMessageDeflate({
...this.options.perMessageDeflate,
isServer: true,
maxPayload: this.options.maxPayload
});
try {
const offers = extension.parse(secWebSocketExtensions);
if (offers[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
} catch (err) {
const message =
'Invalid or unacceptable Sec-WebSocket-Extensions header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
//
// Optionally call external client verification handler.
//
if (this.options.verifyClient) {
const info = {
origin:
req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
secure: !!(req.socket.authorized || req.socket.encrypted),
req
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}
this.completeUpgrade(
extensions,
key,
protocols,
req,
socket,
head,
cb
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private
*/
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
//
// Destroy the socket if the client has already sent a FIN packet.
//
if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) {
throw new Error(
'server.handleUpgrade() was called more than once with the same ' +
'socket, possibly due to a misconfiguration'
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash('sha1')
.update(key + GUID)
.digest('base64');
const headers = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, undefined, this.options);
if (protocols.size) {
//
// Optionally call external protocol selection handler.
//
const protocol = this.options.handleProtocols
? this.options.handleProtocols(protocols, req)
: protocols.values().next().value;
if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value}`);
ws._extensions = extensions;
}
//
// Allow external modification/inspection of handshake headers.
//
this.emit('headers', headers, req);
socket.write(headers.concat('\r\n').join('\r\n'));
socket.removeListener('error', socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on('close', () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb(ws, req);
}
}
module.exports = WebSocketServer;
/**
* Add event listeners on an `EventEmitter` using a map of <event, listener>
* pairs.
*
* @param {EventEmitter} server The event emitter
* @param {Object.<String, Function>} map The listeners to add
* @return {Function} A function that will remove the added listeners when
* called
* @private
*/
function addListeners(server, map) {
for (const event of Object.keys(map)) server.on(event, map[event]);
return function removeListeners() {
for (const event of Object.keys(map)) {
server.removeListener(event, map[event]);
}
};
}
/**
* Emit a `'close'` event on an `EventEmitter`.
*
* @param {EventEmitter} server The event emitter
* @private
*/
function emitClose(server) {
server._state = CLOSED;
server.emit('close');
}
/**
* Handle socket errors.
*
* @private
*/
function socketOnError() {
this.destroy();
}
/**
* Close the connection when preconditions are not fulfilled.
*
* @param {Duplex} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} [message] The HTTP response body
* @param {Object} [headers] Additional HTTP response headers
* @private
*/
function abortHandshake(socket, code, message, headers) {
//
// The socket is writable unless the user destroyed or ended it before calling
// `server.handleUpgrade()` or in the `verifyClient` function, which is a user
// error. Handling this does not make much sense as the worst that can happen
// is that some of the data written by the user might be discarded due to the
// call to `socket.end()` below, which triggers an `'error'` event that in
// turn causes the socket to be destroyed.
//
message = message || http.STATUS_CODES[code];
headers = {
Connection: 'close',
'Content-Type': 'text/html',
'Content-Length': Buffer.byteLength(message),
...headers
};
socket.once('finish', socket.destroy);
socket.end(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
Object.keys(headers)
.map((h) => `${h}: ${headers[h]}`)
.join('\r\n') +
'\r\n\r\n' +
message
);
}
/**
* Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
* one listener for it, otherwise call `abortHandshake()`.
*
* @param {WebSocketServer} server The WebSocket server
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} message The HTTP response body
* @param {Object} [headers] The HTTP response headers
* @private
*/
function abortHandshakeOrEmitwsClientError(
server,
req,
socket,
code,
message,
headers
) {
if (server.listenerCount('wsClientError')) {
const err = new Error(message);
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
server.emit('wsClientError', err, socket, req);
} else {
abortHandshake(socket, code, message, headers);
}
}
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
{
"name": "ws",
"version": "8.20.0",
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"keywords": [
"HyBi",
"Push",
"RFC-6455",
"WebSocket",
"WebSockets",
"real-time"
],
"homepage": "https://github.com/websockets/ws",
"bugs": "https://github.com/websockets/ws/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/websockets/ws.git"
},
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"license": "MIT",
"main": "index.js",
"exports": {
".": {
"browser": "./browser.js",
"import": "./wrapper.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"browser": "browser.js",
"engines": {
"node": ">=10.0.0"
},
"files": [
"browser.js",
"index.js",
"lib/*.js",
"wrapper.mjs"
],
"scripts": {
"test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
"integration": "mocha --throw-deprecation test/*.integration.js",
"lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"benchmark": "^2.1.4",
"bufferutil": "^4.0.1",
"eslint": "^10.0.1",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.0.0",
"globals": "^17.0.0",
"mocha": "^8.4.0",
"nyc": "^15.0.0",
"prettier": "^3.0.0",
"utf-8-validate": "^6.0.0"
}
}
+21
View File
@@ -0,0 +1,21 @@
import createWebSocketStream from './lib/stream.js';
import extension from './lib/extension.js';
import PerMessageDeflate from './lib/permessage-deflate.js';
import Receiver from './lib/receiver.js';
import Sender from './lib/sender.js';
import subprotocol from './lib/subprotocol.js';
import WebSocket from './lib/websocket.js';
import WebSocketServer from './lib/websocket-server.js';
export {
createWebSocketStream,
extension,
PerMessageDeflate,
Receiver,
Sender,
subprotocol,
WebSocket,
WebSocketServer
};
export default WebSocket;
+34
View File
@@ -0,0 +1,34 @@
{
"name": "truckwash-edge-agent",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "truckwash-edge-agent",
"dependencies": {
"ws": "^8.18.0"
}
},
"node_modules/ws": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
"integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "truckwash-edge-agent",
"private": true,
"type": "module",
"scripts": {
"test": "node --test"
},
"dependencies": {
"ws": "^8.18.0"
}
}
+100
View File
@@ -0,0 +1,100 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
claimIfNeeded,
createShellBridge,
getRelayStatus,
setRelayState,
} from "../dist/agent.mjs";
test("claimIfNeeded persists claimed gateway credentials", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "edge-agent-"));
const configPath = path.join(tempDir, "config.json");
await writeFile(configPath, JSON.stringify({
apiUrl: "https://api.example.test",
installToken: "claim-token",
}));
const requests = [];
const fakeFetch = async (url, options) => {
requests.push({ url, options });
return {
ok: true,
async json() {
return {
data: {
gateway: { id: 9001 },
agent_token: "agent-token",
broker_url: "https://broker.example.test",
release_channel: "stable",
},
};
},
};
};
const config = await claimIfNeeded({
apiUrl: "https://api.example.test",
installToken: "claim-token",
}, configPath, fakeFetch);
assert.equal(requests.length, 1);
assert.equal(config.gatewayId, 9001);
assert.equal(config.agentToken, "agent-token");
assert.equal(config.brokerUrl, "https://broker.example.test");
await rm(tempDir, { recursive: true, force: true });
});
test("relay status and switch commands support both Shelly RPC and legacy endpoints", async () => {
const fakeFetch = async (url) => {
if (String(url).includes("Switch.GetStatus")) {
return {
ok: true,
async json() {
return { output: true };
},
};
}
if (String(url).includes("Switch.Set")) {
return {
ok: true,
async json() {
return { output: false };
},
};
}
throw new Error(`Unexpected URL: ${url}`);
};
const status = await getRelayStatus({ localIp: "10.1.0.31", channel: 0 }, fakeFetch);
const switched = await setRelayState({ localIp: "10.1.0.31", channel: 0, on: false }, fakeFetch);
assert.equal(status.online, true);
assert.equal(status.on, true);
assert.equal(switched.on, false);
});
test("shell bridge streams child process output", async () => {
const messages = [];
const shell = createShellBridge((message) => messages.push(message));
shell.open({
sessionId: "test-shell",
shellCommand: process.execPath,
shellArgs: ["-e", "process.stdin.on('data', (d) => process.stdout.write(d))"],
});
await new Promise((resolve) => setTimeout(resolve, 50));
shell.input({ sessionId: "test-shell", data: "hello\n" });
await new Promise((resolve) => setTimeout(resolve, 50));
shell.close({ sessionId: "test-shell" });
await new Promise((resolve) => setTimeout(resolve, 50));
assert.ok(messages.some((message) => message.type === "SHELL_OPENED"));
assert.ok(messages.some((message) => message.type === "SHELL_OUTPUT" && message.data.includes("hello")));
});
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
Copyright (c) 2013 Arnout Kazemier and contributors
Copyright (c) 2016 Luigi Pinca and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+548
View File
@@ -0,0 +1,548 @@
# ws: a Node.js WebSocket library
[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws)
[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster)
[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws)
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation.
Passes the quite extensive Autobahn test suite: [server][server-report],
[client][client-report].
**Note**: This module does not work in the browser. The client in the docs is a
reference to a backend with the role of a client in the WebSocket communication.
Browser clients must use the native
[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
object. To make the same code work seamlessly on Node.js and the browser, you
can use one of the many wrappers available on npm, like
[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws).
## Table of Contents
- [Protocol support](#protocol-support)
- [Installing](#installing)
- [Opt-in for performance](#opt-in-for-performance)
- [Legacy opt-in for performance](#legacy-opt-in-for-performance)
- [API docs](#api-docs)
- [WebSocket compression](#websocket-compression)
- [Usage examples](#usage-examples)
- [Sending and receiving text data](#sending-and-receiving-text-data)
- [Sending binary data](#sending-binary-data)
- [Simple server](#simple-server)
- [External HTTP/S server](#external-https-server)
- [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server)
- [Client authentication](#client-authentication)
- [Server broadcast](#server-broadcast)
- [Round-trip time](#round-trip-time)
- [Use the Node.js streams API](#use-the-nodejs-streams-api)
- [Other examples](#other-examples)
- [FAQ](#faq)
- [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client)
- [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections)
- [How to connect via a proxy?](#how-to-connect-via-a-proxy)
- [Changelog](#changelog)
- [License](#license)
## Protocol support
- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`)
- **HyBi drafts 13-17** (Current default, alternatively option
`protocolVersion: 13`)
## Installing
```
npm install ws
```
### Opt-in for performance
[bufferutil][] is an optional module that can be installed alongside the ws
module:
```
npm install --save-optional bufferutil
```
This is a binary addon that improves the performance of certain operations such
as masking and unmasking the data payload of the WebSocket frames. Prebuilt
binaries are available for the most popular platforms, so you don't necessarily
need to have a C++ compiler installed on your machine.
To force ws to not use bufferutil, use the
[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) environment variable. This
can be useful to enhance security in systems where a user can put a package in
the package search path of an application of another user, due to how the
Node.js resolver algorithm works.
#### Legacy opt-in for performance
If you are running on an old version of Node.js (prior to v18.14.0), ws also
supports the [utf-8-validate][] module:
```
npm install --save-optional utf-8-validate
```
This contains a binary polyfill for [`buffer.isUtf8()`][].
To force ws not to use utf-8-validate, use the
[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment variable.
## API docs
See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and
utility functions.
## WebSocket compression
ws supports the [permessage-deflate extension][permessage-deflate] which enables
the client and server to negotiate a compression algorithm and its parameters,
and then selectively apply it to the data payloads of each WebSocket message.
The extension is disabled by default on the server and enabled by default on the
client. It adds a significant overhead in terms of performance and memory
consumption so we suggest to enable it only if it is really needed.
Note that Node.js has a variety of issues with high-performance compression,
where increased concurrency, especially on Linux, can lead to [catastrophic
memory fragmentation][node-zlib-bug] and slow performance. If you intend to use
permessage-deflate in production, it is worthwhile to set up a test
representative of your workload and ensure Node.js/zlib will handle it with
acceptable performance and memory usage.
Tuning of permessage-deflate can be done via the options defined below. You can
also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly
into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
See [the docs][ws-server-options] for more options.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({
port: 8080,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled.
}
});
```
The client will only use the extension if it is supported and enabled on the
server. To always disable the extension on the client, set the
`perMessageDeflate` option to `false`.
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path', {
perMessageDeflate: false
});
```
## Usage examples
### Sending and receiving text data
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});
```
### Sending binary data
```js
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('error', console.error);
ws.on('open', function open() {
const array = new Float32Array(5);
for (var i = 0; i < array.length; ++i) {
array[i] = i / 2;
}
ws.send(array);
});
```
### Simple server
```js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
```
### External HTTP/S server
```js
import { createServer } from 'https';
import { readFileSync } from 'fs';
import { WebSocketServer } from 'ws';
const server = createServer({
cert: readFileSync('/path/to/cert.pem'),
key: readFileSync('/path/to/key.pem')
});
const wss = new WebSocketServer({ server });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
server.listen(8080);
```
### Multiple servers sharing a single HTTP/S server
```js
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });
wss1.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
wss2.on('connection', function connection(ws) {
ws.on('error', console.error);
// ...
});
server.on('upgrade', function upgrade(request, socket, head) {
const { pathname } = new URL(request.url, 'wss://base.url');
if (pathname === '/foo') {
wss1.handleUpgrade(request, socket, head, function done(ws) {
wss1.emit('connection', ws, request);
});
} else if (pathname === '/bar') {
wss2.handleUpgrade(request, socket, head, function done(ws) {
wss2.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
server.listen(8080);
```
### Client authentication
```js
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
function onSocketError(err) {
console.error(err);
}
const server = createServer();
const wss = new WebSocketServer({ noServer: true });
wss.on('connection', function connection(ws, request, client) {
ws.on('error', console.error);
ws.on('message', function message(data) {
console.log(`Received message ${data} from user ${client}`);
});
});
server.on('upgrade', function upgrade(request, socket, head) {
socket.on('error', onSocketError);
// This function is not defined on purpose. Implement it with your own logic.
authenticate(request, function next(err, client) {
if (err || !client) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
socket.removeListener('error', onSocketError);
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request, client);
});
});
});
server.listen(8080);
```
Also see the provided [example][session-parse-example] using `express-session`.
### Server broadcast
A client WebSocket broadcasting to all connected WebSocket clients, including
itself.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});
```
A client WebSocket broadcasting to every other connected WebSocket clients,
excluding itself.
```js
import WebSocket, { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('error', console.error);
ws.on('message', function message(data, isBinary) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data, { binary: isBinary });
}
});
});
});
```
### Round-trip time
```js
import WebSocket from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
ws.on('error', console.error);
ws.on('open', function open() {
console.log('connected');
ws.send(Date.now());
});
ws.on('close', function close() {
console.log('disconnected');
});
ws.on('message', function message(data) {
console.log(`Round-trip time: ${Date.now() - data} ms`);
setTimeout(function timeout() {
ws.send(Date.now());
}, 500);
});
```
### Use the Node.js streams API
```js
import WebSocket, { createWebSocketStream } from 'ws';
const ws = new WebSocket('wss://websocket-echo.com/');
const duplex = createWebSocketStream(ws, { encoding: 'utf8' });
duplex.on('error', console.error);
duplex.pipe(process.stdout);
process.stdin.pipe(duplex);
```
### Other examples
For a full example with a browser client communicating with a ws server, see the
examples folder.
Otherwise, see the test cases.
## FAQ
### How to get the IP address of the client?
The remote IP address can be obtained from the raw socket.
```js
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws, req) {
const ip = req.socket.remoteAddress;
ws.on('error', console.error);
});
```
When the server runs behind a proxy like NGINX, the de-facto standard is to use
the `X-Forwarded-For` header.
```js
wss.on('connection', function connection(ws, req) {
const ip = req.headers['x-forwarded-for'].split(',')[0].trim();
ws.on('error', console.error);
});
```
### How to detect and close broken connections?
Sometimes, the link between the server and the client can be interrupted in a
way that keeps both the server and the client unaware of the broken state of the
connection (e.g. when pulling the cord).
In these cases, ping messages can be used as a means to verify that the remote
endpoint is still responsive.
```js
import { WebSocketServer } from 'ws';
function heartbeat() {
this.isAlive = true;
}
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.isAlive = true;
ws.on('error', console.error);
ws.on('pong', heartbeat);
});
const interval = setInterval(function ping() {
wss.clients.forEach(function each(ws) {
if (ws.isAlive === false) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 30000);
wss.on('close', function close() {
clearInterval(interval);
});
```
Pong messages are automatically sent in response to ping messages as required by
the spec.
Just like the server example above, your clients might as well lose connection
without knowing it. You might want to add a ping listener on your clients to
prevent that. A simple implementation would be:
```js
import WebSocket from 'ws';
function heartbeat() {
clearTimeout(this.pingTimeout);
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
this.pingTimeout = setTimeout(() => {
this.terminate();
}, 30000 + 1000);
}
const client = new WebSocket('wss://websocket-echo.com/');
client.on('error', console.error);
client.on('open', heartbeat);
client.on('ping', heartbeat);
client.on('close', function clear() {
clearTimeout(this.pingTimeout);
});
```
### How to connect via a proxy?
Use a custom `http.Agent` implementation like [https-proxy-agent][] or
[socks-proxy-agent][].
## Changelog
We're using the GitHub [releases][changelog] for changelog entries.
## License
[MIT](LICENSE)
[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input
[bufferutil]: https://github.com/websockets/bufferutil
[changelog]: https://github.com/websockets/ws/releases
[client-report]: http://websockets.github.io/ws/autobahn/clients/
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[node-zlib-bug]: https://github.com/nodejs/node/issues/8871
[node-zlib-deflaterawdocs]:
https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
[permessage-deflate]: https://tools.ietf.org/html/rfc7692
[server-report]: http://websockets.github.io/ws/autobahn/servers/
[session-parse-example]: ./examples/express-session-parse
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[utf-8-validate]: https://github.com/websockets/utf-8-validate
[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback
+8
View File
@@ -0,0 +1,8 @@
'use strict';
module.exports = function () {
throw new Error(
'ws does not work in the browser. Browser clients must use the native ' +
'WebSocket object'
);
};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
const createWebSocketStream = require('./lib/stream');
const extension = require('./lib/extension');
const PerMessageDeflate = require('./lib/permessage-deflate');
const Receiver = require('./lib/receiver');
const Sender = require('./lib/sender');
const subprotocol = require('./lib/subprotocol');
const WebSocket = require('./lib/websocket');
const WebSocketServer = require('./lib/websocket-server');
WebSocket.createWebSocketStream = createWebSocketStream;
WebSocket.extension = extension;
WebSocket.PerMessageDeflate = PerMessageDeflate;
WebSocket.Receiver = Receiver;
WebSocket.Sender = Sender;
WebSocket.Server = WebSocketServer;
WebSocket.subprotocol = subprotocol;
WebSocket.WebSocket = WebSocket;
WebSocket.WebSocketServer = WebSocketServer;
module.exports = WebSocket;
+131
View File
@@ -0,0 +1,131 @@
'use strict';
const { EMPTY_BUFFER } = require('./constants');
const FastBuffer = Buffer[Symbol.species];
/**
* Merges an array of buffers into a new buffer.
*
* @param {Buffer[]} list The array of buffers to concat
* @param {Number} totalLength The total length of buffers in the list
* @return {Buffer} The resulting buffer
* @public
*/
function concat(list, totalLength) {
if (list.length === 0) return EMPTY_BUFFER;
if (list.length === 1) return list[0];
const target = Buffer.allocUnsafe(totalLength);
let offset = 0;
for (let i = 0; i < list.length; i++) {
const buf = list[i];
target.set(buf, offset);
offset += buf.length;
}
if (offset < totalLength) {
return new FastBuffer(target.buffer, target.byteOffset, offset);
}
return target;
}
/**
* Masks a buffer using the given mask.
*
* @param {Buffer} source The buffer to mask
* @param {Buffer} mask The mask to use
* @param {Buffer} output The buffer where to store the result
* @param {Number} offset The offset at which to start writing
* @param {Number} length The number of bytes to mask.
* @public
*/
function _mask(source, mask, output, offset, length) {
for (let i = 0; i < length; i++) {
output[offset + i] = source[i] ^ mask[i & 3];
}
}
/**
* Unmasks a buffer using the given mask.
*
* @param {Buffer} buffer The buffer to unmask
* @param {Buffer} mask The mask to use
* @public
*/
function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask[i & 3];
}
}
/**
* Converts a buffer to an `ArrayBuffer`.
*
* @param {Buffer} buf The buffer to convert
* @return {ArrayBuffer} Converted buffer
* @public
*/
function toArrayBuffer(buf) {
if (buf.length === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
/**
* Converts `data` to a `Buffer`.
*
* @param {*} data The data to convert
* @return {Buffer} The buffer
* @throws {TypeError}
* @public
*/
function toBuffer(data) {
toBuffer.readOnly = true;
if (Buffer.isBuffer(data)) return data;
let buf;
if (data instanceof ArrayBuffer) {
buf = new FastBuffer(data);
} else if (ArrayBuffer.isView(data)) {
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
} else {
buf = Buffer.from(data);
toBuffer.readOnly = false;
}
return buf;
}
module.exports = {
concat,
mask: _mask,
toArrayBuffer,
toBuffer,
unmask: _unmask
};
/* istanbul ignore else */
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil = require('bufferutil');
module.exports.mask = function (source, mask, output, offset, length) {
if (length < 48) _mask(source, mask, output, offset, length);
else bufferUtil.mask(source, mask, output, offset, length);
};
module.exports.unmask = function (buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil.unmask(buffer, mask);
};
} catch (e) {
// Continue regardless of the error.
}
}
+19
View File
@@ -0,0 +1,19 @@
'use strict';
const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];
const hasBlob = typeof Blob !== 'undefined';
if (hasBlob) BINARY_TYPES.push('blob');
module.exports = {
BINARY_TYPES,
CLOSE_TIMEOUT: 30000,
EMPTY_BUFFER: Buffer.alloc(0),
GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
hasBlob,
kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),
kListener: Symbol('kListener'),
kStatusCode: Symbol('status-code'),
kWebSocket: Symbol('websocket'),
NOOP: () => {}
};
+292
View File
@@ -0,0 +1,292 @@
'use strict';
const { kForOnEventAttribute, kListener } = require('./constants');
const kCode = Symbol('kCode');
const kData = Symbol('kData');
const kError = Symbol('kError');
const kMessage = Symbol('kMessage');
const kReason = Symbol('kReason');
const kTarget = Symbol('kTarget');
const kType = Symbol('kType');
const kWasClean = Symbol('kWasClean');
/**
* Class representing an event.
*/
class Event {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}
/**
* @type {*}
*/
get target() {
return this[kTarget];
}
/**
* @type {String}
*/
get type() {
return this[kType];
}
}
Object.defineProperty(Event.prototype, 'target', { enumerable: true });
Object.defineProperty(Event.prototype, 'type', { enumerable: true });
/**
* Class representing a close event.
*
* @extends Event
*/
class CloseEvent extends Event {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === undefined ? 0 : options.code;
this[kReason] = options.reason === undefined ? '' : options.reason;
this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
}
Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });
Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });
/**
* Class representing an error event.
*
* @extends Event
*/
class ErrorEvent extends Event {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === undefined ? null : options.error;
this[kMessage] = options.message === undefined ? '' : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
}
Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });
/**
* Class representing a message event.
*
* @extends Event
*/
class MessageEvent extends Event {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);
this[kData] = options.data === undefined ? null : options.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
}
Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });
/**
* This provides methods for emulating the `EventTarget` interface. It's not
* meant to be used directly.
*
* @mixin
*/
const EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options = {}) {
for (const listener of this.listeners(type)) {
if (
!options[kForOnEventAttribute] &&
listener[kListener] === handler &&
!listener[kForOnEventAttribute]
) {
return;
}
}
let wrapper;
if (type === 'message') {
wrapper = function onMessage(data, isBinary) {
const event = new MessageEvent('message', {
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'close') {
wrapper = function onClose(code, message) {
const event = new CloseEvent('close', {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'error') {
wrapper = function onError(error) {
const event = new ErrorEvent('error', {
error,
message: error.message
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === 'open') {
wrapper = function onOpen() {
const event = new Event('open');
event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
wrapper[kListener] = handler;
if (options.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},
/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener);
break;
}
}
}
};
module.exports = {
CloseEvent,
ErrorEvent,
Event,
EventTarget,
MessageEvent
};
/**
* Call an event listener
*
* @param {(Function|Object)} listener The listener to call
* @param {*} thisArg The value to use as `this`` when calling the listener
* @param {Event} event The event to pass to the listener
* @private
*/
function callListener(listener, thisArg, event) {
if (typeof listener === 'object' && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}
+203
View File
@@ -0,0 +1,203 @@
'use strict';
const { tokenChars } = require('./validation');
/**
* Adds an offer to the map of extension offers or a parameter to the map of
* parameters.
*
* @param {Object} dest The map of extension offers or parameters
* @param {String} name The extension or parameter name
* @param {(Object|Boolean|String)} elem The extension parameters or the
* parameter value
* @private
*/
function push(dest, name, elem) {
if (dest[name] === undefined) dest[name] = [elem];
else dest[name].push(elem);
}
/**
* Parses the `Sec-WebSocket-Extensions` header into an object.
*
* @param {String} header The field value of the header
* @return {Object} The parsed object
* @public
*/
function parse(header) {
const offers = Object.create(null);
let params = Object.create(null);
let mustUnescape = false;
let isEscaping = false;
let inQuotes = false;
let extensionName;
let paramName;
let start = -1;
let code = -1;
let end = -1;
let i = 0;
for (; i < header.length; i++) {
code = header.charCodeAt(i);
if (extensionName === undefined) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const name = header.slice(start, end);
if (code === 0x2c) {
push(offers, name, params);
params = Object.create(null);
} else {
extensionName = name;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (paramName === undefined) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 0x20 || code === 0x09) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x3b || code === 0x2c) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
push(params, header.slice(start, end), true);
if (code === 0x2c) {
push(offers, extensionName, params);
params = Object.create(null);
extensionName = undefined;
}
start = end = -1;
} else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {
paramName = header.slice(start, i);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else {
//
// The value of a quoted-string after unescaping must conform to the
// token ABNF, so only token characters are valid.
// Ref: https://tools.ietf.org/html/rfc6455#section-9.1
//
if (isEscaping) {
if (tokenChars[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (start === -1) start = i;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 0x22 /* '"' */ && start !== -1) {
inQuotes = false;
end = i;
} else if (code === 0x5c /* '\' */) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
inQuotes = true;
} else if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (start !== -1 && (code === 0x20 || code === 0x09)) {
if (end === -1) end = i;
} else if (code === 0x3b || code === 0x2c) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
let value = header.slice(start, end);
if (mustUnescape) {
value = value.replace(/\\/g, '');
mustUnescape = false;
}
push(params, paramName, value);
if (code === 0x2c) {
push(offers, extensionName, params);
params = Object.create(null);
extensionName = undefined;
}
paramName = undefined;
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
}
if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {
throw new SyntaxError('Unexpected end of input');
}
if (end === -1) end = i;
const token = header.slice(start, end);
if (extensionName === undefined) {
push(offers, token, params);
} else {
if (paramName === undefined) {
push(params, token, true);
} else if (mustUnescape) {
push(params, paramName, token.replace(/\\/g, ''));
} else {
push(params, paramName, token);
}
push(offers, extensionName, params);
}
return offers;
}
/**
* Builds the `Sec-WebSocket-Extensions` header field value.
*
* @param {Object} extensions The map of extensions and parameters to format
* @return {String} A string representing the given object
* @public
*/
function format(extensions) {
return Object.keys(extensions)
.map((extension) => {
let configurations = extensions[extension];
if (!Array.isArray(configurations)) configurations = [configurations];
return configurations
.map((params) => {
return [extension]
.concat(
Object.keys(params).map((k) => {
let values = params[k];
if (!Array.isArray(values)) values = [values];
return values
.map((v) => (v === true ? k : `${k}=${v}`))
.join('; ');
})
)
.join('; ');
})
.join(', ');
})
.join(', ');
}
module.exports = { format, parse };
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const kDone = Symbol('kDone');
const kRun = Symbol('kRun');
/**
* A very simple job queue with adjustable concurrency. Adapted from
* https://github.com/STRML/async-limiter
*/
class Limiter {
/**
* Creates a new `Limiter`.
*
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
* to run concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @param {Function} job The job to run
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
}
module.exports = Limiter;
+528
View File
@@ -0,0 +1,528 @@
'use strict';
const zlib = require('zlib');
const bufferUtil = require('./buffer-util');
const Limiter = require('./limiter');
const { kStatusCode } = require('./constants');
const FastBuffer = Buffer[Symbol.species];
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
const kPerMessageDeflate = Symbol('permessage-deflate');
const kTotalLength = Symbol('total-length');
const kCallback = Symbol('callback');
const kBuffers = Symbol('buffers');
const kError = Symbol('error');
//
// We limit zlib concurrency, which prevents severe memory fragmentation
// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
// and https://github.com/websockets/ws/issues/1202
//
// Intentionally global; it's the global thread pool that's an issue.
//
let zlibLimiter;
/**
* permessage-deflate implementation.
*/
class PerMessageDeflate {
/**
* Creates a PerMessageDeflate instance.
*
* @param {Object} [options] Configuration options
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
* for, or request, a custom client window size
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
* acknowledge disabling of client context takeover
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
* calls to zlib
* @param {Boolean} [options.isServer=false] Create the instance in either
* server or client mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
* use of a custom server window size
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
* disabling of server context takeover
* @param {Number} [options.threshold=1024] Size (in bytes) below which
* messages should not be compressed if context takeover is disabled
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
* deflate
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
* inflate
*/
constructor(options) {
this._options = options || {};
this._threshold =
this._options.threshold !== undefined ? this._options.threshold : 1024;
this._maxPayload = this._options.maxPayload | 0;
this._isServer = !!this._options.isServer;
this._deflate = null;
this._inflate = null;
this.params = null;
if (!zlibLimiter) {
const concurrency =
this._options.concurrencyLimit !== undefined
? this._options.concurrencyLimit
: 10;
zlibLimiter = new Limiter(concurrency);
}
}
/**
* @type {String}
*/
static get extensionName() {
return 'permessage-deflate';
}
/**
* Create an extension negotiation offer.
*
* @return {Object} Extension parameters
* @public
*/
offer() {
const params = {};
if (this._options.serverNoContextTakeover) {
params.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
params.client_no_context_takeover = true;
}
if (this._options.serverMaxWindowBits) {
params.server_max_window_bits = this._options.serverMaxWindowBits;
}
if (this._options.clientMaxWindowBits) {
params.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (this._options.clientMaxWindowBits == null) {
params.client_max_window_bits = true;
}
return params;
}
/**
* Accept an extension negotiation offer/response.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Object} Accepted configuration
* @public
*/
accept(configurations) {
configurations = this.normalizeParams(configurations);
this.params = this._isServer
? this.acceptAsServer(configurations)
: this.acceptAsClient(configurations);
return this.params;
}
/**
* Releases all resources used by the extension.
*
* @public
*/
cleanup() {
if (this._inflate) {
this._inflate.close();
this._inflate = null;
}
if (this._deflate) {
const callback = this._deflate[kCallback];
this._deflate.close();
this._deflate = null;
if (callback) {
callback(
new Error(
'The deflate stream was closed while data was being processed'
)
);
}
}
}
/**
* Accept an extension negotiation offer.
*
* @param {Array} offers The extension negotiation offers
* @return {Object} Accepted configuration
* @private
*/
acceptAsServer(offers) {
const opts = this._options;
const accepted = offers.find((params) => {
if (
(opts.serverNoContextTakeover === false &&
params.server_no_context_takeover) ||
(params.server_max_window_bits &&
(opts.serverMaxWindowBits === false ||
(typeof opts.serverMaxWindowBits === 'number' &&
opts.serverMaxWindowBits > params.server_max_window_bits))) ||
(typeof opts.clientMaxWindowBits === 'number' &&
!params.client_max_window_bits)
) {
return false;
}
return true;
});
if (!accepted) {
throw new Error('None of the extension offers can be accepted');
}
if (opts.serverNoContextTakeover) {
accepted.server_no_context_takeover = true;
}
if (opts.clientNoContextTakeover) {
accepted.client_no_context_takeover = true;
}
if (typeof opts.serverMaxWindowBits === 'number') {
accepted.server_max_window_bits = opts.serverMaxWindowBits;
}
if (typeof opts.clientMaxWindowBits === 'number') {
accepted.client_max_window_bits = opts.clientMaxWindowBits;
} else if (
accepted.client_max_window_bits === true ||
opts.clientMaxWindowBits === false
) {
delete accepted.client_max_window_bits;
}
return accepted;
}
/**
* Accept the extension negotiation response.
*
* @param {Array} response The extension negotiation response
* @return {Object} Accepted configuration
* @private
*/
acceptAsClient(response) {
const params = response[0];
if (
this._options.clientNoContextTakeover === false &&
params.client_no_context_takeover
) {
throw new Error('Unexpected parameter "client_no_context_takeover"');
}
if (!params.client_max_window_bits) {
if (typeof this._options.clientMaxWindowBits === 'number') {
params.client_max_window_bits = this._options.clientMaxWindowBits;
}
} else if (
this._options.clientMaxWindowBits === false ||
(typeof this._options.clientMaxWindowBits === 'number' &&
params.client_max_window_bits > this._options.clientMaxWindowBits)
) {
throw new Error(
'Unexpected or invalid parameter "client_max_window_bits"'
);
}
return params;
}
/**
* Normalize parameters.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Array} The offers/response with normalized parameters
* @private
*/
normalizeParams(configurations) {
configurations.forEach((params) => {
Object.keys(params).forEach((key) => {
let value = params[key];
if (value.length > 1) {
throw new Error(`Parameter "${key}" must have only a single value`);
}
value = value[0];
if (key === 'client_max_window_bits') {
if (value !== true) {
const num = +value;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
value = num;
} else if (!this._isServer) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
} else if (key === 'server_max_window_bits') {
const num = +value;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
value = num;
} else if (
key === 'client_no_context_takeover' ||
key === 'server_no_context_takeover'
) {
if (value !== true) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value}`
);
}
} else {
throw new Error(`Unknown parameter "${key}"`);
}
params[key] = value;
});
});
return configurations;
}
/**
* Decompress data. Concurrency limited.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
decompress(data, fin, callback) {
zlibLimiter.add((done) => {
this._decompress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Compress data. Concurrency limited.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
compress(data, fin, callback) {
zlibLimiter.add((done) => {
this._compress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Decompress data.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_decompress(data, fin, callback) {
const endpoint = this._isServer ? 'client' : 'server';
if (!this._inflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits =
typeof this.params[key] !== 'number'
? zlib.Z_DEFAULT_WINDOWBITS
: this.params[key];
this._inflate = zlib.createInflateRaw({
...this._options.zlibInflateOptions,
windowBits
});
this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
this._inflate.on('error', inflateOnError);
this._inflate.on('data', inflateOnData);
}
this._inflate[kCallback] = callback;
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
const err = this._inflate[kError];
if (err) {
this._inflate.close();
this._inflate = null;
callback(err);
return;
}
const data = bufferUtil.concat(
this._inflate[kBuffers],
this._inflate[kTotalLength]
);
if (this._inflate._readableState.endEmitted) {
this._inflate.close();
this._inflate = null;
} else {
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.reset();
}
}
callback(null, data);
});
}
/**
* Compress data.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_compress(data, fin, callback) {
const endpoint = this._isServer ? 'server' : 'client';
if (!this._deflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits =
typeof this.params[key] !== 'number'
? zlib.Z_DEFAULT_WINDOWBITS
: this.params[key];
this._deflate = zlib.createDeflateRaw({
...this._options.zlibDeflateOptions,
windowBits
});
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
this._deflate.on('data', deflateOnData);
}
this._deflate[kCallback] = callback;
this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
//
// The deflate stream was closed while data was being processed.
//
return;
}
let data = bufferUtil.concat(
this._deflate[kBuffers],
this._deflate[kTotalLength]
);
if (fin) {
data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);
}
//
// Ensure that the callback will not be called again in
// `PerMessageDeflate#cleanup()`.
//
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
}
callback(null, data);
});
}
}
module.exports = PerMessageDeflate;
/**
* The listener of the `zlib.DeflateRaw` stream `'data'` event.
*
* @param {Buffer} chunk A chunk of data
* @private
*/
function deflateOnData(chunk) {
this[kBuffers].push(chunk);
this[kTotalLength] += chunk.length;
}
/**
* The listener of the `zlib.InflateRaw` stream `'data'` event.
*
* @param {Buffer} chunk A chunk of data
* @private
*/
function inflateOnData(chunk) {
this[kTotalLength] += chunk.length;
if (
this[kPerMessageDeflate]._maxPayload < 1 ||
this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
) {
this[kBuffers].push(chunk);
return;
}
this[kError] = new RangeError('Max payload size exceeded');
this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
this[kError][kStatusCode] = 1009;
this.removeListener('data', inflateOnData);
//
// The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the
// fact that in Node.js versions prior to 13.10.0, the callback for
// `zlib.flush()` is not called if `zlib.close()` is used. Utilizing
// `zlib.reset()` ensures that either the callback is invoked or an error is
// emitted.
//
this.reset();
}
/**
* The listener of the `zlib.InflateRaw` stream `'error'` event.
*
* @param {Error} err The emitted error
* @private
*/
function inflateOnError(err) {
//
// There is no need to call `Zlib#close()` as the handle is automatically
// closed when an error is emitted.
//
this[kPerMessageDeflate]._inflate = null;
if (this[kError]) {
this[kCallback](this[kError]);
return;
}
err[kStatusCode] = 1007;
this[kCallback](err);
}
+706
View File
@@ -0,0 +1,706 @@
'use strict';
const { Writable } = require('stream');
const PerMessageDeflate = require('./permessage-deflate');
const {
BINARY_TYPES,
EMPTY_BUFFER,
kStatusCode,
kWebSocket
} = require('./constants');
const { concat, toArrayBuffer, unmask } = require('./buffer-util');
const { isValidStatusCode, isValidUTF8 } = require('./validation');
const FastBuffer = Buffer[Symbol.species];
const GET_INFO = 0;
const GET_PAYLOAD_LENGTH_16 = 1;
const GET_PAYLOAD_LENGTH_64 = 2;
const GET_MASK = 3;
const GET_DATA = 4;
const INFLATING = 5;
const DEFER_EVENT = 6;
/**
* HyBi Receiver implementation.
*
* @extends Writable
*/
class Receiver extends Writable {
/**
* Creates a Receiver instance.
*
* @param {Object} [options] Options object
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {String} [options.binaryType=nodebuffer] The type for binary data
* @param {Object} [options.extensions] An object containing the negotiated
* extensions
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
* client or server mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
*/
constructor(options = {}) {
super();
this._allowSynchronousEvents =
options.allowSynchronousEvents !== undefined
? options.allowSynchronousEvents
: true;
this._binaryType = options.binaryType || BINARY_TYPES[0];
this._extensions = options.extensions || {};
this._isServer = !!options.isServer;
this._maxPayload = options.maxPayload | 0;
this._skipUTF8Validation = !!options.skipUTF8Validation;
this[kWebSocket] = undefined;
this._bufferedBytes = 0;
this._buffers = [];
this._compressed = false;
this._payloadLength = 0;
this._mask = undefined;
this._fragmented = 0;
this._masked = false;
this._fin = false;
this._opcode = 0;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragments = [];
this._errored = false;
this._loop = false;
this._state = GET_INFO;
}
/**
* Implements `Writable.prototype._write()`.
*
* @param {Buffer} chunk The chunk of data to write
* @param {String} encoding The character encoding of `chunk`
* @param {Function} cb Callback
* @private
*/
_write(chunk, encoding, cb) {
if (this._opcode === 0x08 && this._state == GET_INFO) return cb();
this._bufferedBytes += chunk.length;
this._buffers.push(chunk);
this.startLoop(cb);
}
/**
* Consumes `n` bytes from the buffered data.
*
* @param {Number} n The number of bytes to consume
* @return {Buffer} The consumed bytes
* @private
*/
consume(n) {
this._bufferedBytes -= n;
if (n === this._buffers[0].length) return this._buffers.shift();
if (n < this._buffers[0].length) {
const buf = this._buffers[0];
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
return new FastBuffer(buf.buffer, buf.byteOffset, n);
}
const dst = Buffer.allocUnsafe(n);
do {
const buf = this._buffers[0];
const offset = dst.length - n;
if (n >= buf.length) {
dst.set(this._buffers.shift(), offset);
} else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
}
n -= buf.length;
} while (n > 0);
return dst;
}
/**
* Starts the parsing loop.
*
* @param {Function} cb Callback
* @private
*/
startLoop(cb) {
this._loop = true;
do {
switch (this._state) {
case GET_INFO:
this.getInfo(cb);
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16(cb);
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64(cb);
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData(cb);
break;
case INFLATING:
case DEFER_EVENT:
this._loop = false;
return;
}
} while (this._loop);
if (!this._errored) cb();
}
/**
* Reads the first two bytes of a frame.
*
* @param {Function} cb Callback
* @private
*/
getInfo(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
const buf = this.consume(2);
if ((buf[0] & 0x30) !== 0x00) {
const error = this.createError(
RangeError,
'RSV2 and RSV3 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_2_3'
);
cb(error);
return;
}
const compressed = (buf[0] & 0x40) === 0x40;
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
const error = this.createError(
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
cb(error);
return;
}
this._fin = (buf[0] & 0x80) === 0x80;
this._opcode = buf[0] & 0x0f;
this._payloadLength = buf[1] & 0x7f;
if (this._opcode === 0x00) {
if (compressed) {
const error = this.createError(
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
cb(error);
return;
}
if (!this._fragmented) {
const error = this.createError(
RangeError,
'invalid opcode 0',
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
cb(error);
return;
}
this._opcode = this._fragmented;
} else if (this._opcode === 0x01 || this._opcode === 0x02) {
if (this._fragmented) {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
cb(error);
return;
}
this._compressed = compressed;
} else if (this._opcode > 0x07 && this._opcode < 0x0b) {
if (!this._fin) {
const error = this.createError(
RangeError,
'FIN must be set',
true,
1002,
'WS_ERR_EXPECTED_FIN'
);
cb(error);
return;
}
if (compressed) {
const error = this.createError(
RangeError,
'RSV1 must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_RSV_1'
);
cb(error);
return;
}
if (
this._payloadLength > 0x7d ||
(this._opcode === 0x08 && this._payloadLength === 1)
) {
const error = this.createError(
RangeError,
`invalid payload length ${this._payloadLength}`,
true,
1002,
'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'
);
cb(error);
return;
}
} else {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
'WS_ERR_INVALID_OPCODE'
);
cb(error);
return;
}
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 0x80) === 0x80;
if (this._isServer) {
if (!this._masked) {
const error = this.createError(
RangeError,
'MASK must be set',
true,
1002,
'WS_ERR_EXPECTED_MASK'
);
cb(error);
return;
}
} else if (this._masked) {
const error = this.createError(
RangeError,
'MASK must be clear',
true,
1002,
'WS_ERR_UNEXPECTED_MASK'
);
cb(error);
return;
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else this.haveLength(cb);
}
/**
* Gets extended payload length (7+16).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength16(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
this._payloadLength = this.consume(2).readUInt16BE(0);
this.haveLength(cb);
}
/**
* Gets extended payload length (7+64).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength64(cb) {
if (this._bufferedBytes < 8) {
this._loop = false;
return;
}
const buf = this.consume(8);
const num = buf.readUInt32BE(0);
//
// The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
// if payload length is greater than this number.
//
if (num > Math.pow(2, 53 - 32) - 1) {
const error = this.createError(
RangeError,
'Unsupported WebSocket frame: payload length > 2^53 - 1',
false,
1009,
'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'
);
cb(error);
return;
}
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
this.haveLength(cb);
}
/**
* Payload length has been read.
*
* @param {Function} cb Callback
* @private
*/
haveLength(cb) {
if (this._payloadLength && this._opcode < 0x08) {
this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
'Max payload size exceeded',
false,
1009,
'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
);
cb(error);
return;
}
}
if (this._masked) this._state = GET_MASK;
else this._state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask() {
if (this._bufferedBytes < 4) {
this._loop = false;
return;
}
this._mask = this.consume(4);
this._state = GET_DATA;
}
/**
* Reads data bytes.
*
* @param {Function} cb Callback
* @private
*/
getData(cb) {
let data = EMPTY_BUFFER;
if (this._payloadLength) {
if (this._bufferedBytes < this._payloadLength) {
this._loop = false;
return;
}
data = this.consume(this._payloadLength);
if (
this._masked &&
(this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0
) {
unmask(data, this._mask);
}
}
if (this._opcode > 0x07) {
this.controlMessage(data, cb);
return;
}
if (this._compressed) {
this._state = INFLATING;
this.decompress(data, cb);
return;
}
if (data.length) {
//
// This message is not compressed so its length is the sum of the payload
// length of all fragments.
//
this._messageLength = this._totalPayloadLength;
this._fragments.push(data);
}
this.dataMessage(cb);
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @param {Function} cb Callback
* @private
*/
decompress(data, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
if (err) return cb(err);
if (buf.length) {
this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
'Max payload size exceeded',
false,
1009,
'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
);
cb(error);
return;
}
this._fragments.push(buf);
}
this.dataMessage(cb);
if (this._state === GET_INFO) this.startLoop(cb);
});
}
/**
* Handles a data message.
*
* @param {Function} cb Callback
* @private
*/
dataMessage(cb) {
if (!this._fin) {
this._state = GET_INFO;
return;
}
const messageLength = this._messageLength;
const fragments = this._fragments;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragmented = 0;
this._fragments = [];
if (this._opcode === 2) {
let data;
if (this._binaryType === 'nodebuffer') {
data = concat(fragments, messageLength);
} else if (this._binaryType === 'arraybuffer') {
data = toArrayBuffer(concat(fragments, messageLength));
} else if (this._binaryType === 'blob') {
data = new Blob(fragments);
} else {
data = fragments;
}
if (this._allowSynchronousEvents) {
this.emit('message', data, true);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit('message', data, true);
this._state = GET_INFO;
this.startLoop(cb);
});
}
} else {
const buf = concat(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
'invalid UTF-8 sequence',
true,
1007,
'WS_ERR_INVALID_UTF8'
);
cb(error);
return;
}
if (this._state === INFLATING || this._allowSynchronousEvents) {
this.emit('message', buf, false);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit('message', buf, false);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @return {(Error|RangeError|undefined)} A possible error
* @private
*/
controlMessage(data, cb) {
if (this._opcode === 0x08) {
if (data.length === 0) {
this._loop = false;
this.emit('conclude', 1005, EMPTY_BUFFER);
this.end();
} else {
const code = data.readUInt16BE(0);
if (!isValidStatusCode(code)) {
const error = this.createError(
RangeError,
`invalid status code ${code}`,
true,
1002,
'WS_ERR_INVALID_CLOSE_CODE'
);
cb(error);
return;
}
const buf = new FastBuffer(
data.buffer,
data.byteOffset + 2,
data.length - 2
);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
'invalid UTF-8 sequence',
true,
1007,
'WS_ERR_INVALID_UTF8'
);
cb(error);
return;
}
this._loop = false;
this.emit('conclude', code, buf);
this.end();
}
this._state = GET_INFO;
return;
}
if (this._allowSynchronousEvents) {
this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
/**
* Builds an error object.
*
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
* @param {String} message The error message
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
* `message`
* @param {Number} statusCode The status code
* @param {String} errorCode The exposed error code
* @return {(Error|RangeError)} The error
* @private
*/
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
this._loop = false;
this._errored = true;
const err = new ErrorCtor(
prefix ? `Invalid WebSocket frame: ${message}` : message
);
Error.captureStackTrace(err, this.createError);
err.code = errorCode;
err[kStatusCode] = statusCode;
return err;
}
}
module.exports = Receiver;
+602
View File
@@ -0,0 +1,602 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */
'use strict';
const { Duplex } = require('stream');
const { randomFillSync } = require('crypto');
const PerMessageDeflate = require('./permessage-deflate');
const { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');
const { isBlob, isValidStatusCode } = require('./validation');
const { mask: applyMask, toBuffer } = require('./buffer-util');
const kByteLength = Symbol('kByteLength');
const maskBuffer = Buffer.alloc(4);
const RANDOM_POOL_SIZE = 8 * 1024;
let randomPool;
let randomPoolPointer = RANDOM_POOL_SIZE;
const DEFAULT = 0;
const DEFLATING = 1;
const GET_BLOB_DATA = 2;
/**
* HyBi Sender implementation.
*/
class Sender {
/**
* Creates a Sender instance.
*
* @param {Duplex} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/
constructor(socket, extensions, generateMask) {
this._extensions = extensions || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket;
this._firstFragment = true;
this._compress = false;
this._bufferedBytes = 0;
this._queue = [];
this._state = DEFAULT;
this.onerror = NOOP;
this[kWebSocket] = undefined;
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {(Buffer|String)} data The data to frame
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @return {(Buffer|String)[]} The framed data
* @public
*/
static frame(data, options) {
let mask;
let merge = false;
let offset = 2;
let skipMasking = false;
if (options.mask) {
mask = options.maskBuffer || maskBuffer;
if (options.generateMask) {
options.generateMask(mask);
} else {
if (randomPoolPointer === RANDOM_POOL_SIZE) {
/* istanbul ignore else */
if (randomPool === undefined) {
//
// This is lazily initialized because server-sent frames must not
// be masked so it may never be used.
//
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}
mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
offset = 6;
}
let dataLength;
if (typeof data === 'string') {
if (
(!options.mask || skipMasking) &&
options[kByteLength] !== undefined
) {
dataLength = options[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge = options.mask && options.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset += 8;
payloadLength = 127;
} else if (dataLength > 125) {
offset += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
if (options.rsv1) target[0] |= 0x40;
target[1] = payloadLength;
if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2);
} else if (payloadLength === 127) {
target[2] = target[3] = 0;
target.writeUIntBE(dataLength, 4, 6);
}
if (!options.mask) return [target, data];
target[1] |= 0x80;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge) {
applyMask(data, mask, target, offset, dataLength);
return [target];
}
applyMask(data, mask, data, 0, dataLength);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {Number} [code] The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
* @param {Function} [cb] Callback
* @public
*/
close(code, data, mask, cb) {
let buf;
if (code === undefined) {
buf = EMPTY_BUFFER;
} else if (typeof code !== 'number' || !isValidStatusCode(code)) {
throw new TypeError('First argument must be a valid error code number');
} else if (data === undefined || !data.length) {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError('The message must not be greater than 123 bytes');
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
if (typeof data === 'string') {
buf.write(data, 2);
} else {
buf.set(data, 2);
}
}
const options = {
[kByteLength]: buf.length,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x08,
readOnly: false,
rsv1: false
};
if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, buf, false, options, cb]);
} else {
this.sendFrame(Sender.frame(buf, options), cb);
}
}
/**
* Sends a ping message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
ping(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === 'string') {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x09,
readOnly,
rsv1: false
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb]);
} else {
this.getBlobData(data, false, options, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(Sender.frame(data, options), cb);
}
}
/**
* Sends a pong message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
pong(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === 'string') {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (byteLength > 125) {
throw new RangeError('The data size must not be greater than 125 bytes');
}
const options = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 0x0a,
readOnly,
rsv1: false
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options, cb]);
} else {
this.getBlobData(data, false, options, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(Sender.frame(data, options), cb);
}
}
/**
* Sends a data message to the other peer.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
* or text
* @param {Boolean} [options.compress=false] Specifies whether or not to
* compress `data`
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Function} [cb] Callback
* @public
*/
send(data, options, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
let opcode = options.binary ? 2 : 1;
let rsv1 = options.compress;
let byteLength;
let readOnly;
if (typeof data === 'string') {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer(data);
byteLength = data.length;
readOnly = toBuffer.readOnly;
}
if (this._firstFragment) {
this._firstFragment = false;
if (
rsv1 &&
perMessageDeflate &&
perMessageDeflate.params[
perMessageDeflate._isServer
? 'server_no_context_takeover'
: 'client_no_context_takeover'
]
) {
rsv1 = byteLength >= perMessageDeflate._threshold;
}
this._compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options.fin) this._firstFragment = true;
const opts = {
[kByteLength]: byteLength,
fin: options.fin,
generateMask: this._generateMask,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1
};
if (isBlob(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
} else {
this.getBlobData(data, this._compress, opts, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
} else {
this.dispatch(data, this._compress, opts, cb);
}
}
/**
* Gets the contents of a blob as binary data.
*
* @param {Blob} blob The blob
* @param {Boolean} [compress=false] Specifies whether or not to compress
* the data
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
getBlobData(blob, compress, options, cb) {
this._bufferedBytes += options[kByteLength];
this._state = GET_BLOB_DATA;
blob
.arrayBuffer()
.then((arrayBuffer) => {
if (this._socket.destroyed) {
const err = new Error(
'The socket was closed while the blob was being read'
);
//
// `callCallbacks` is called in the next tick to ensure that errors
// that might be thrown in the callbacks behave like errors thrown
// outside the promise chain.
//
process.nextTick(callCallbacks, this, err, cb);
return;
}
this._bufferedBytes -= options[kByteLength];
const data = toBuffer(arrayBuffer);
if (!compress) {
this._state = DEFAULT;
this.sendFrame(Sender.frame(data, options), cb);
this.dequeue();
} else {
this.dispatch(data, compress, options, cb);
}
})
.catch((err) => {
//
// `onError` is called in the next tick for the same reason that
// `callCallbacks` above is.
//
process.nextTick(onError, this, err, cb);
});
}
/**
* Dispatches a message.
*
* @param {(Buffer|String)} data The message to send
* @param {Boolean} [compress=false] Specifies whether or not to compress
* `data`
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
dispatch(data, compress, options, cb) {
if (!compress) {
this.sendFrame(Sender.frame(data, options), cb);
return;
}
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
this._bufferedBytes += options[kByteLength];
this._state = DEFLATING;
perMessageDeflate.compress(data, options.fin, (_, buf) => {
if (this._socket.destroyed) {
const err = new Error(
'The socket was closed while data was being compressed'
);
callCallbacks(this, err, cb);
return;
}
this._bufferedBytes -= options[kByteLength];
this._state = DEFAULT;
options.readOnly = false;
this.sendFrame(Sender.frame(buf, options), cb);
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (this._state === DEFAULT && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength];
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[3][kByteLength];
this._queue.push(params);
}
/**
* Sends a frame.
*
* @param {(Buffer | String)[]} list The frame to send
* @param {Function} [cb] Callback
* @private
*/
sendFrame(list, cb) {
if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]);
this._socket.write(list[1], cb);
this._socket.uncork();
} else {
this._socket.write(list[0], cb);
}
}
}
module.exports = Sender;
/**
* Calls queued callbacks with an error.
*
* @param {Sender} sender The `Sender` instance
* @param {Error} err The error to call the callbacks with
* @param {Function} [cb] The first callback
* @private
*/
function callCallbacks(sender, err, cb) {
if (typeof cb === 'function') cb(err);
for (let i = 0; i < sender._queue.length; i++) {
const params = sender._queue[i];
const callback = params[params.length - 1];
if (typeof callback === 'function') callback(err);
}
}
/**
* Handles a `Sender` error.
*
* @param {Sender} sender The `Sender` instance
* @param {Error} err The error
* @param {Function} [cb] The first pending callback
* @private
*/
function onError(sender, err, cb) {
callCallbacks(sender, err, cb);
sender.onerror(err);
}
+161
View File
@@ -0,0 +1,161 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^WebSocket$" }] */
'use strict';
const WebSocket = require('./websocket');
const { Duplex } = require('stream');
/**
* Emits the `'close'` event on a stream.
*
* @param {Duplex} stream The stream.
* @private
*/
function emitClose(stream) {
stream.emit('close');
}
/**
* The listener of the `'end'` event.
*
* @private
*/
function duplexOnEnd() {
if (!this.destroyed && this._writableState.finished) {
this.destroy();
}
}
/**
* The listener of the `'error'` event.
*
* @param {Error} err The error
* @private
*/
function duplexOnError(err) {
this.removeListener('error', duplexOnError);
this.destroy();
if (this.listenerCount('error') === 0) {
// Do not suppress the throwing behavior.
this.emit('error', err);
}
}
/**
* Wraps a `WebSocket` in a duplex stream.
*
* @param {WebSocket} ws The `WebSocket` to wrap
* @param {Object} [options] The options for the `Duplex` constructor
* @return {Duplex} The duplex stream
* @public
*/
function createWebSocketStream(ws, options) {
let terminateOnDestroy = true;
const duplex = new Duplex({
...options,
autoDestroy: false,
emitClose: false,
objectMode: false,
writableObjectMode: false
});
ws.on('message', function message(msg, isBinary) {
const data =
!isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
if (!duplex.push(data)) ws.pause();
});
ws.once('error', function error(err) {
if (duplex.destroyed) return;
// Prevent `ws.terminate()` from being called by `duplex._destroy()`.
//
// - If the `'error'` event is emitted before the `'open'` event, then
// `ws.terminate()` is a noop as no socket is assigned.
// - Otherwise, the error is re-emitted by the listener of the `'error'`
// event of the `Receiver` object. The listener already closes the
// connection by calling `ws.close()`. This allows a close frame to be
// sent to the other peer. If `ws.terminate()` is called right after this,
// then the close frame might not be sent.
terminateOnDestroy = false;
duplex.destroy(err);
});
ws.once('close', function close() {
if (duplex.destroyed) return;
duplex.push(null);
});
duplex._destroy = function (err, callback) {
if (ws.readyState === ws.CLOSED) {
callback(err);
process.nextTick(emitClose, duplex);
return;
}
let called = false;
ws.once('error', function error(err) {
called = true;
callback(err);
});
ws.once('close', function close() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
});
if (terminateOnDestroy) ws.terminate();
};
duplex._final = function (callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once('open', function open() {
duplex._final(callback);
});
return;
}
// If the value of the `_socket` property is `null` it means that `ws` is a
// client websocket and the handshake failed. In fact, when this happens, a
// socket is never assigned to the websocket. Wait for the `'error'` event
// that will be emitted by the websocket.
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
callback();
if (duplex._readableState.endEmitted) duplex.destroy();
} else {
ws._socket.once('finish', function finish() {
// `duplex` is not destroyed here because the `'end'` event will be
// emitted on `duplex` after this `'finish'` event. The EOF signaling
// `null` chunk is, in fact, pushed when the websocket emits `'close'`.
callback();
});
ws.close();
}
};
duplex._read = function () {
if (ws.isPaused) ws.resume();
};
duplex._write = function (chunk, encoding, callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once('open', function open() {
duplex._write(chunk, encoding, callback);
});
return;
}
ws.send(chunk, callback);
};
duplex.on('end', duplexOnEnd);
duplex.on('error', duplexOnError);
return duplex;
}
module.exports = createWebSocketStream;
+62
View File
@@ -0,0 +1,62 @@
'use strict';
const { tokenChars } = require('./validation');
/**
* Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
*
* @param {String} header The field value of the header
* @return {Set} The subprotocol names
* @public
*/
function parse(header) {
const protocols = new Set();
let start = -1;
let end = -1;
let i = 0;
for (i; i < header.length; i++) {
const code = header.charCodeAt(i);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (
i !== 0 &&
(code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */
) {
if (end === -1 && start !== -1) end = i;
} else if (code === 0x2c /* ',' */) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const protocol = header.slice(start, end);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError('Unexpected end of input');
}
const protocol = header.slice(start, i);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
return protocols;
}
module.exports = { parse };
+152
View File
@@ -0,0 +1,152 @@
'use strict';
const { isUtf8 } = require('buffer');
const { hasBlob } = require('./constants');
//
// Allowed token characters:
//
// '!', '#', '$', '%', '&', ''', '*', '+', '-',
// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
//
// tokenChars[32] === 0 // ' '
// tokenChars[33] === 1 // '!'
// tokenChars[34] === 0 // '"'
// ...
//
// prettier-ignore
const tokenChars = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
];
/**
* Checks if a status code is allowed in a close frame.
*
* @param {Number} code The status code
* @return {Boolean} `true` if the status code is valid, else `false`
* @public
*/
function isValidStatusCode(code) {
return (
(code >= 1000 &&
code <= 1014 &&
code !== 1004 &&
code !== 1005 &&
code !== 1006) ||
(code >= 3000 && code <= 4999)
);
}
/**
* Checks if a given buffer contains only correct UTF-8.
* Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
* Markus Kuhn.
*
* @param {Buffer} buf The buffer to check
* @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
* @public
*/
function _isValidUTF8(buf) {
const len = buf.length;
let i = 0;
while (i < len) {
if ((buf[i] & 0x80) === 0) {
// 0xxxxxxx
i++;
} else if ((buf[i] & 0xe0) === 0xc0) {
// 110xxxxx 10xxxxxx
if (
i + 1 === len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i] & 0xfe) === 0xc0 // Overlong
) {
return false;
}
i += 2;
} else if ((buf[i] & 0xf0) === 0xe0) {
// 1110xxxx 10xxxxxx 10xxxxxx
if (
i + 2 >= len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i + 2] & 0xc0) !== 0x80 ||
(buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong
(buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)
) {
return false;
}
i += 3;
} else if ((buf[i] & 0xf8) === 0xf0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (
i + 3 >= len ||
(buf[i + 1] & 0xc0) !== 0x80 ||
(buf[i + 2] & 0xc0) !== 0x80 ||
(buf[i + 3] & 0xc0) !== 0x80 ||
(buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong
(buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||
buf[i] > 0xf4 // > U+10FFFF
) {
return false;
}
i += 4;
} else {
return false;
}
}
return true;
}
/**
* Determines whether a value is a `Blob`.
*
* @param {*} value The value to be tested
* @return {Boolean} `true` if `value` is a `Blob`, else `false`
* @private
*/
function isBlob(value) {
return (
hasBlob &&
typeof value === 'object' &&
typeof value.arrayBuffer === 'function' &&
typeof value.type === 'string' &&
typeof value.stream === 'function' &&
(value[Symbol.toStringTag] === 'Blob' ||
value[Symbol.toStringTag] === 'File')
);
}
module.exports = {
isBlob,
isValidStatusCode,
isValidUTF8: _isValidUTF8,
tokenChars
};
if (isUtf8) {
module.exports.isValidUTF8 = function (buf) {
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
};
} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {
try {
const isValidUTF8 = require('utf-8-validate');
module.exports.isValidUTF8 = function (buf) {
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
};
} catch (e) {
// Continue regardless of the error.
}
}
+554
View File
@@ -0,0 +1,554 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
'use strict';
const EventEmitter = require('events');
const http = require('http');
const { Duplex } = require('stream');
const { createHash } = require('crypto');
const extension = require('./extension');
const PerMessageDeflate = require('./permessage-deflate');
const subprotocol = require('./subprotocol');
const WebSocket = require('./websocket');
const { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');
const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
const RUNNING = 0;
const CLOSING = 1;
const CLOSED = 2;
/**
* Class representing a WebSocket server.
*
* @extends EventEmitter
*/
class WebSocketServer extends EventEmitter {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
* automatically send a pong in response to a ping
* @param {Number} [options.backlog=511] The maximum length of the queue of
* pending connections
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
* track clients
* @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
* wait for the closing handshake to finish after `websocket.close()` is
* called
* @param {Function} [options.handleProtocols] A hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Boolean} [options.noServer=false] Enable no server mode
* @param {String} [options.path] Accept only connections matching this path
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/
constructor(options, callback) {
super();
options = {
allowSynchronousEvents: true,
autoPong: true,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false,
handleProtocols: null,
clientTracking: true,
closeTimeout: CLOSE_TIMEOUT,
verifyClient: null,
noServer: false,
backlog: null, // use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null,
WebSocket,
...options
};
if (
(options.port == null && !options.server && !options.noServer) ||
(options.port != null && (options.server || options.noServer)) ||
(options.server && options.noServer)
) {
throw new TypeError(
'One and only one of the "port", "server", or "noServer" options ' +
'must be specified'
);
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
res.end(body);
});
this._server.listen(
options.port,
options.host,
options.backlog,
callback
);
} else if (options.server) {
this._server = options.server;
}
if (this._server) {
const emitConnection = this.emit.bind(this, 'connection');
this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, 'listening'),
error: this.emit.bind(this, 'error'),
upgrade: (req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection);
}
});
}
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
if (options.clientTracking) {
this.clients = new Set();
this._shouldEmitClose = false;
}
this.options = options;
this._state = RUNNING;
}
/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address() {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}
if (!this._server) return null;
return this._server.address();
}
/**
* Stop the server from accepting new connections and emit the `'close'` event
* when all existing connections are closed.
*
* @param {Function} [cb] A one-time listener for the `'close'` event
* @public
*/
close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once('close', () => {
cb(new Error('The server is not running'));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once('close', cb);
if (this._state === CLOSING) return;
this._state = CLOSING;
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) {
if (!this.clients.size) {
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
}
} else {
process.nextTick(emitClose, this);
}
} else {
const server = this._server;
this._removeListeners();
this._removeListeners = this._server = null;
//
// The HTTP/S server was created internally. Close it, and rely on its
// `'close'` event.
//
server.close(() => {
emitClose(this);
});
}
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle(req) {
if (this.options.path) {
const index = req.url.indexOf('?');
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
if (pathname !== this.options.path) return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade(req, socket, head, cb) {
socket.on('error', socketOnError);
const key = req.headers['sec-websocket-key'];
const upgrade = req.headers.upgrade;
const version = +req.headers['sec-websocket-version'];
if (req.method !== 'GET') {
const message = 'Invalid HTTP method';
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
return;
}
if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
const message = 'Invalid Upgrade header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (key === undefined || !keyRegex.test(key)) {
const message = 'Missing or invalid Sec-WebSocket-Key header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (version !== 13 && version !== 8) {
const message = 'Missing or invalid Sec-WebSocket-Version header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
'Sec-WebSocket-Version': '13, 8'
});
return;
}
if (!this.shouldHandle(req)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
let protocols = new Set();
if (secWebSocketProtocol !== undefined) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err) {
const message = 'Invalid Sec-WebSocket-Protocol header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
const extensions = {};
if (
this.options.perMessageDeflate &&
secWebSocketExtensions !== undefined
) {
const perMessageDeflate = new PerMessageDeflate({
...this.options.perMessageDeflate,
isServer: true,
maxPayload: this.options.maxPayload
});
try {
const offers = extension.parse(secWebSocketExtensions);
if (offers[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
} catch (err) {
const message =
'Invalid or unacceptable Sec-WebSocket-Extensions header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
//
// Optionally call external client verification handler.
//
if (this.options.verifyClient) {
const info = {
origin:
req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
secure: !!(req.socket.authorized || req.socket.encrypted),
req
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}
this.completeUpgrade(
extensions,
key,
protocols,
req,
socket,
head,
cb
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private
*/
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
//
// Destroy the socket if the client has already sent a FIN packet.
//
if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) {
throw new Error(
'server.handleUpgrade() was called more than once with the same ' +
'socket, possibly due to a misconfiguration'
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash('sha1')
.update(key + GUID)
.digest('base64');
const headers = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, undefined, this.options);
if (protocols.size) {
//
// Optionally call external protocol selection handler.
//
const protocol = this.options.handleProtocols
? this.options.handleProtocols(protocols, req)
: protocols.values().next().value;
if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value}`);
ws._extensions = extensions;
}
//
// Allow external modification/inspection of handshake headers.
//
this.emit('headers', headers, req);
socket.write(headers.concat('\r\n').join('\r\n'));
socket.removeListener('error', socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on('close', () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb(ws, req);
}
}
module.exports = WebSocketServer;
/**
* Add event listeners on an `EventEmitter` using a map of <event, listener>
* pairs.
*
* @param {EventEmitter} server The event emitter
* @param {Object.<String, Function>} map The listeners to add
* @return {Function} A function that will remove the added listeners when
* called
* @private
*/
function addListeners(server, map) {
for (const event of Object.keys(map)) server.on(event, map[event]);
return function removeListeners() {
for (const event of Object.keys(map)) {
server.removeListener(event, map[event]);
}
};
}
/**
* Emit a `'close'` event on an `EventEmitter`.
*
* @param {EventEmitter} server The event emitter
* @private
*/
function emitClose(server) {
server._state = CLOSED;
server.emit('close');
}
/**
* Handle socket errors.
*
* @private
*/
function socketOnError() {
this.destroy();
}
/**
* Close the connection when preconditions are not fulfilled.
*
* @param {Duplex} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} [message] The HTTP response body
* @param {Object} [headers] Additional HTTP response headers
* @private
*/
function abortHandshake(socket, code, message, headers) {
//
// The socket is writable unless the user destroyed or ended it before calling
// `server.handleUpgrade()` or in the `verifyClient` function, which is a user
// error. Handling this does not make much sense as the worst that can happen
// is that some of the data written by the user might be discarded due to the
// call to `socket.end()` below, which triggers an `'error'` event that in
// turn causes the socket to be destroyed.
//
message = message || http.STATUS_CODES[code];
headers = {
Connection: 'close',
'Content-Type': 'text/html',
'Content-Length': Buffer.byteLength(message),
...headers
};
socket.once('finish', socket.destroy);
socket.end(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
Object.keys(headers)
.map((h) => `${h}: ${headers[h]}`)
.join('\r\n') +
'\r\n\r\n' +
message
);
}
/**
* Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
* one listener for it, otherwise call `abortHandshake()`.
*
* @param {WebSocketServer} server The WebSocket server
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} message The HTTP response body
* @param {Object} [headers] The HTTP response headers
* @private
*/
function abortHandshakeOrEmitwsClientError(
server,
req,
socket,
code,
message,
headers
) {
if (server.listenerCount('wsClientError')) {
const err = new Error(message);
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
server.emit('wsClientError', err, socket, req);
} else {
abortHandshake(socket, code, message, headers);
}
}
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
{
"name": "ws",
"version": "8.20.0",
"description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
"keywords": [
"HyBi",
"Push",
"RFC-6455",
"WebSocket",
"WebSockets",
"real-time"
],
"homepage": "https://github.com/websockets/ws",
"bugs": "https://github.com/websockets/ws/issues",
"repository": {
"type": "git",
"url": "git+https://github.com/websockets/ws.git"
},
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"license": "MIT",
"main": "index.js",
"exports": {
".": {
"browser": "./browser.js",
"import": "./wrapper.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"browser": "browser.js",
"engines": {
"node": ">=10.0.0"
},
"files": [
"browser.js",
"index.js",
"lib/*.js",
"wrapper.mjs"
],
"scripts": {
"test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
"integration": "mocha --throw-deprecation test/*.integration.js",
"lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"benchmark": "^2.1.4",
"bufferutil": "^4.0.1",
"eslint": "^10.0.1",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.0.0",
"globals": "^17.0.0",
"mocha": "^8.4.0",
"nyc": "^15.0.0",
"prettier": "^3.0.0",
"utf-8-validate": "^6.0.0"
}
}
+21
View File
@@ -0,0 +1,21 @@
import createWebSocketStream from './lib/stream.js';
import extension from './lib/extension.js';
import PerMessageDeflate from './lib/permessage-deflate.js';
import Receiver from './lib/receiver.js';
import Sender from './lib/sender.js';
import subprotocol from './lib/subprotocol.js';
import WebSocket from './lib/websocket.js';
import WebSocketServer from './lib/websocket-server.js';
export {
createWebSocketStream,
extension,
PerMessageDeflate,
Receiver,
Sender,
subprotocol,
WebSocket,
WebSocketServer
};
export default WebSocket;
+34
View File
@@ -0,0 +1,34 @@
{
"name": "truckwash-edge-broker",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "truckwash-edge-broker",
"dependencies": {
"ws": "^8.18.0"
}
},
"node_modules/ws": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz",
"integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "truckwash-edge-broker",
"private": true,
"type": "module",
"scripts": {
"test": "node --test"
},
"dependencies": {
"ws": "^8.18.0"
}
}
+286
View File
@@ -0,0 +1,286 @@
import http from "node:http";
import { randomUUID } from "node:crypto";
import { WebSocketServer } from "ws";
function parseJsonBody(req) {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk.toString("utf8");
});
req.on("end", () => {
try {
resolve(raw === "" ? {} : JSON.parse(raw));
} catch (error) {
reject(error);
}
});
req.on("error", reject);
});
}
function jsonResponse(res, statusCode, body) {
res.writeHead(statusCode, { "content-type": "application/json" });
res.end(JSON.stringify(body));
}
export function createBrokerServer(options = {}) {
const authMode = options.authMode || process.env.EDGE_AUTH_MODE || "stub";
const sharedSecret = options.sharedSecret ?? process.env.EDGE_BROKER_SHARED_SECRET ?? "";
const commandTimeoutMs = options.commandTimeoutMs ?? 10000;
const agents = new Map();
const pendingCommands = new Map();
const browserSessions = new Map();
const validateAgent = options.validateAgent || (async ({ gatewayId }) => ({ id: gatewayId }));
const validateShellSession = options.validateShellSession || (async ({ token }) => ({ id: token, gateway_id: 1, reason: "stub" }));
const closeShellSession = options.closeShellSession || (async () => ({}));
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://localhost");
if (req.method === "POST" && /^\/api\/gateways\/\d+\/commands$/.test(url.pathname)) {
if (sharedSecret && req.headers["x-edge-broker-secret"] !== sharedSecret) {
jsonResponse(res, 403, { error: "Forbidden" });
return;
}
const gatewayId = url.pathname.split("/")[3];
const agent = agents.get(String(gatewayId));
if (!agent || agent.readyState !== 1) {
jsonResponse(res, 503, { error: "Gateway agent is offline" });
return;
}
const body = await parseJsonBody(req);
const commandId = randomUUID();
const promise = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
pendingCommands.delete(commandId);
reject(new Error("Agent command timed out"));
}, commandTimeoutMs);
pendingCommands.set(commandId, {
resolve,
reject,
timeout,
});
});
agent.send(JSON.stringify({
type: "COMMAND",
commandId,
commandType: body.commandType,
payload: body.payload || {},
}));
try {
const result = await promise;
jsonResponse(res, 200, result);
} catch (error) {
jsonResponse(res, 504, { ok: false, error: error instanceof Error ? error.message : String(error) });
}
return;
}
jsonResponse(res, 404, { error: "Not found" });
} catch (error) {
jsonResponse(res, 500, { error: error instanceof Error ? error.message : String(error) });
}
});
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", async (req, socket, head) => {
const url = new URL(req.url, "http://localhost");
try {
if (url.pathname === "/ws/agent") {
const gatewayId = String(url.searchParams.get("gatewayId") || "");
const token = String(url.searchParams.get("token") || "");
if (gatewayId === "" || token === "") {
socket.destroy();
return;
}
if (authMode !== "stub") {
await validateAgent({ gatewayId, token, headers: req.headers });
}
wss.handleUpgrade(req, socket, head, (ws) => {
ws.gatewayId = gatewayId;
agents.set(gatewayId, ws);
wss.emit("connection", ws, req);
});
return;
}
if (url.pathname === "/ws/browser-shell") {
const token = String(url.searchParams.get("token") || "");
if (token === "") {
socket.destroy();
return;
}
const session = authMode === "stub"
? await validateShellSession({ token })
: await validateShellSession({ token, headers: req.headers });
wss.handleUpgrade(req, socket, head, (ws) => {
ws.sessionToken = token;
ws.sessionInfo = session;
browserSessions.set(String(session.id), { ws, session, transcript: "" });
const agent = agents.get(String(session.gateway_id));
if (agent && agent.readyState === 1) {
agent.send(JSON.stringify({
type: "OPEN_ROOT_SHELL",
payload: {
sessionId: String(session.id),
reason: session.reason,
},
}));
}
wss.emit("connection", ws, req);
});
return;
}
} catch {
socket.destroy();
return;
}
socket.destroy();
});
wss.on("connection", (ws) => {
ws.on("message", async (raw) => {
const message = JSON.parse(raw.toString());
if (ws.gatewayId) {
if (message.type === "COMMAND_RESULT") {
const pending = pendingCommands.get(message.commandId);
if (!pending) {
return;
}
clearTimeout(pending.timeout);
pendingCommands.delete(message.commandId);
pending.resolve({
ok: Boolean(message.ok),
payload: message.payload,
error: message.error,
});
return;
}
if (["SHELL_OUTPUT", "SHELL_OPENED", "SHELL_EXIT"].includes(message.type)) {
const sessionRecord = browserSessions.get(String(message.sessionId));
if (!sessionRecord) {
return;
}
if (message.type === "SHELL_OUTPUT") {
sessionRecord.transcript += String(message.data || "");
sessionRecord.ws.send(JSON.stringify({ type: "output", data: String(message.data || "") }));
}
if (message.type === "SHELL_OPENED") {
sessionRecord.ws.send(JSON.stringify({ type: "opened" }));
}
if (message.type === "SHELL_EXIT") {
sessionRecord.ws.send(JSON.stringify({ type: "closed", code: message.code ?? 0 }));
await closeShellSession(sessionRecord.session.id, sessionRecord.ws.sessionToken, sessionRecord.transcript, "agent_exit");
browserSessions.delete(String(message.sessionId));
}
}
return;
}
if (ws.sessionInfo) {
const sessionId = String(ws.sessionInfo.id);
const agent = agents.get(String(ws.sessionInfo.gateway_id));
if (!agent || agent.readyState !== 1) {
return;
}
if (message.type === "input") {
agent.send(JSON.stringify({
type: "SHELL_INPUT",
payload: {
sessionId,
data: String(message.data || ""),
},
}));
}
if (message.type === "close") {
agent.send(JSON.stringify({
type: "CLOSE_ROOT_SHELL",
payload: { sessionId },
}));
}
}
});
ws.on("close", async () => {
if (ws.gatewayId) {
agents.delete(String(ws.gatewayId));
return;
}
if (ws.sessionInfo) {
const sessionId = String(ws.sessionInfo.id);
const agent = agents.get(String(ws.sessionInfo.gateway_id));
if (agent && agent.readyState === 1) {
agent.send(JSON.stringify({
type: "CLOSE_ROOT_SHELL",
payload: { sessionId },
}));
}
const sessionRecord = browserSessions.get(sessionId);
if (sessionRecord) {
await closeShellSession(sessionRecord.session.id, ws.sessionToken, sessionRecord.transcript, "browser_closed");
browserSessions.delete(sessionId);
}
}
});
});
return {
server,
listen(port = Number(process.env.PORT || 4300)) {
return new Promise((resolve) => {
server.listen(port, () => resolve(server.address()));
});
},
close() {
return new Promise((resolve, reject) => {
for (const agent of agents.values()) {
agent.terminate();
}
for (const session of browserSessions.values()) {
session.ws.terminate();
}
for (const pending of pendingCommands.values()) {
clearTimeout(pending.timeout);
pending.reject(new Error("Broker shutting down"));
}
pendingCommands.clear();
wss.close(() => {
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
});
},
state: {
agents,
browserSessions,
pendingCommands,
},
};
}
if (import.meta.url === `file://${process.argv[1]}`) {
const broker = createBrokerServer();
broker.listen().then(() => {
console.log("TruckWash edge broker listening");
}).catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}
+99
View File
@@ -0,0 +1,99 @@
import test from "node:test";
import assert from "node:assert/strict";
import WebSocket from "ws";
import { createBrokerServer } from "../server.mjs";
function waitForMessage(socket) {
return new Promise((resolve) => {
socket.once("message", (raw) => resolve(JSON.parse(raw.toString())));
});
}
function collectMessages(socket) {
const messages = [];
socket.on("message", (raw) => {
messages.push(JSON.parse(raw.toString()));
});
return messages;
}
test("broker dispatches commands to connected agents", async () => {
const broker = createBrokerServer({ authMode: "stub", sharedSecret: "secret", commandTimeoutMs: 2000 });
const address = await broker.listen(0);
const port = address.port;
const agent = new WebSocket(`ws://127.0.0.1:${port}/ws/agent?gatewayId=701&token=agent-token`);
await new Promise((resolve) => agent.once("open", resolve));
agent.on("message", (raw) => {
const message = JSON.parse(raw.toString());
if (message.type === "COMMAND") {
agent.send(JSON.stringify({
type: "COMMAND_RESULT",
commandId: message.commandId,
ok: true,
payload: { online: true, on: true },
}));
}
});
const response = await fetch(`http://127.0.0.1:${port}/api/gateways/701/commands`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-edge-broker-secret": "secret",
},
body: JSON.stringify({
commandType: "GET_RELAY_STATUS",
payload: { relayId: "M-7" },
}),
});
const json = await response.json();
assert.equal(response.status, 200);
assert.equal(json.ok, true);
assert.equal(json.payload.on, true);
agent.terminate();
await broker.close();
});
test("broker bridges browser shell sessions through the connected agent", async () => {
const closedSessions = [];
const broker = createBrokerServer({
authMode: "stub",
validateShellSession: async () => ({ id: "shell-1", gateway_id: "701", reason: "diagnostic" }),
closeShellSession: async (_id, _token, transcript, reason) => {
closedSessions.push({ transcript, reason });
},
});
const address = await broker.listen(0);
const port = address.port;
const agent = new WebSocket(`ws://127.0.0.1:${port}/ws/agent?gatewayId=701&token=agent-token`);
await new Promise((resolve) => agent.once("open", resolve));
agent.on("message", (raw) => {
const message = JSON.parse(raw.toString());
if (message.type === "OPEN_ROOT_SHELL") {
agent.send(JSON.stringify({ type: "SHELL_OPENED", sessionId: "shell-1" }));
agent.send(JSON.stringify({ type: "SHELL_OUTPUT", sessionId: "shell-1", data: "root@pi:~# " }));
agent.send(JSON.stringify({ type: "SHELL_EXIT", sessionId: "shell-1", code: 0 }));
}
});
const browser = new WebSocket(`ws://127.0.0.1:${port}/ws/browser-shell?token=session-token`);
const browserMessages = collectMessages(browser);
await new Promise((resolve) => browser.once("open", resolve));
await new Promise((resolve) => setTimeout(resolve, 100));
assert.ok(browserMessages.some((message) => message.type === "opened"));
assert.ok(browserMessages.some((message) => message.type === "output" && /root@pi/.test(message.data)));
assert.ok(browserMessages.some((message) => message.type === "closed" && message.code === 0));
assert.equal(closedSessions.length, 1);
assert.equal(closedSessions[0].reason, "agent_exit");
browser.terminate();
agent.terminate();
await broker.close();
});
+19
View File
@@ -0,0 +1,19 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
const composeSource = readFileSync(new URL("../../../docker-compose.yml", import.meta.url), "utf8");
const traefikSource = readFileSync(new URL("../../../services/traefik/traefik.yml", import.meta.url), "utf8");
const traefikProdSource = readFileSync(new URL("../../../services/traefik/traefik.prod.yml", import.meta.url), "utf8");
test("traefik exposes a dedicated edge broker entrypoint on port 4300", () => {
assert.match(traefikSource, /edge-broker:\s*\n\s*address:\s*":4300"/);
assert.match(traefikProdSource, /edge-broker:\s*\n\s*address:\s*":4300"/);
assert.match(composeSource, /traefik:[\s\S]*ports:[\s\S]*"4300:4300"/);
});
test("edge broker is routed through traefik on port 4300 for public api hosts", () => {
assert.match(composeSource, /edge-broker:[\s\S]*traefik\.http\.routers\.edge-broker-dk\.entrypoints=edge-broker/);
assert.match(composeSource, /edge-broker:[\s\S]*traefik\.http\.routers\.edge-broker-io\.entrypoints=edge-broker/);
assert.match(composeSource, /edge-broker:[\s\S]*traefik\.http\.services\.edge-broker\.loadbalancer\.server\.port=4300/);
});
+37 -5
View File
@@ -12,6 +12,31 @@ use objects\subusers_o;
class authentication implements authentication_i
{
private function touchResolvedUserSession(users_o $user, string $token): void
{
if (trim($token) === '') {
return;
}
try {
(new system_session_activity_tracker())->touchUser($user, $token);
} catch (\Throwable) {
// Session tracking must never block authentication resolution.
}
}
private function touchResolvedSubuserSession(subusers_o $subuser, string $token, int|null $customerNumberContext = null): void
{
if (trim($token) === '') {
return;
}
try {
(new system_session_activity_tracker())->touchSubuser($subuser, $token, $customerNumberContext);
} catch (\Throwable) {
// Session tracking must never block authentication resolution.
}
}
/**
* @throws Exception
@@ -125,11 +150,11 @@ class authentication implements authentication_i
if (!isset($headers['Authorization'])) {
return false;
}
$token = $headers['Authorization'];
$rawToken = $headers['Authorization'];
// Strip the Bearer prefix
$token = str_replace('Bearer ', '', $token);
$rawToken = str_replace('Bearer ', '', $rawToken);
// Get the token from the database
$token = (new tokens_o())->getToken($token);
$token = (new tokens_o())->getToken($rawToken);
// Check if the token exists
if (!$token->id) {
return false;
@@ -144,7 +169,9 @@ class authentication implements authentication_i
return (new users_o())->getUserByCustomerNumber($customer_number);
}
// Get the user from the database
return (new users_o())->getUserById($token->user_id->value());
$user = (new users_o())->getUserById($token->user_id->value());
$this->touchResolvedUserSession($user, $rawToken);
return $user;
}
public function get_plate_scanner(): plate_scanners_o|false
@@ -197,6 +224,11 @@ class authentication implements authentication_i
if ($subuser === null) {
return false;
}
$customerNumberContext = null;
if (isset($headers['X-Customer-Number'])) {
$customerNumberContext = (int)$headers['X-Customer-Number'];
}
$this->touchResolvedSubuserSession($subuser, $token, $customerNumberContext);
return $subuser;
}
@@ -232,4 +264,4 @@ class authentication implements authentication_i
}
return (int)$headers['X-Customer-Number'];
}
}
}
@@ -0,0 +1,35 @@
<?php
namespace classes;
require_once WD . '/interfaces/shelly_transport_i.php';
require_once WD . '/classes/shelly.php';
use interfaces\shelly_transport_i;
class cloud_shelly_transport implements shelly_transport_i
{
public function __construct(private readonly ?shelly $client = null)
{
}
private function client(): shelly
{
return $this->client ?? new shelly();
}
public function requireModuleEnabled(): void
{
$this->client()->requireModuleEnabled();
}
public function requireValidSecretKey(): void
{
$this->client()->requireValidSecretKey();
}
public function sendPostRequest(string $endpoint, array $data, ?int $department_id = null): array|object|null
{
return $this->client()->sendPostRequest($endpoint, $data);
}
}
@@ -0,0 +1,34 @@
<?php
namespace classes;
/**
* Ensures additive schema for department daily report customer complaints.
*/
class department_daily_report_complaints_schema_bootstrap
{
private static bool $initialized = false;
public static function ensureTables(): void
{
if (self::$initialized) {
return;
}
global $db;
$db->query(
"CREATE TABLE IF NOT EXISTS department_daily_report_complaints (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
department_id INT NOT NULL,
customer_number INT NULL,
description TEXT NOT NULL,
created_by INT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_department_daily_report_complaints_department_created (department_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
);
self::$initialized = true;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,113 @@
<?php
namespace classes;
use Exception;
class edge_broker_client
{
public function __construct(
private readonly ?string $baseUrl = null,
private readonly ?string $sharedSecret = null,
private readonly int $timeoutSeconds = 10
) {
}
public function isConfigured(): bool
{
return trim((string)$this->resolveBaseUrl()) !== '';
}
public function dispatchCommand(int $gatewayId, string $commandType, array $payload): array
{
$url = rtrim($this->resolveBaseUrl(), '/') . '/api/gateways/' . $gatewayId . '/commands';
$response = $this->request('POST', $url, [
'commandType' => $commandType,
'payload' => $payload,
]);
return is_array($response) ? $response : ['ok' => false, 'response' => $response];
}
public function validateAgent(int $gatewayId, string $agentToken): array
{
$url = rtrim($this->resolveBaseUrl(), '/') . '/api/internal/agent/auth';
$response = $this->request('POST', $url, [
'gatewayId' => $gatewayId,
'agentToken' => $agentToken,
]);
return is_array($response) ? $response : [];
}
public function validateShellSession(string $sessionToken): array
{
$url = rtrim($this->resolveBaseUrl(), '/') . '/api/internal/shell/auth';
$response = $this->request('POST', $url, [
'sessionToken' => $sessionToken,
]);
return is_array($response) ? $response : [];
}
public function closeShellSession(int $sessionId, string $sessionToken, string $transcript, string $closedReason): array
{
$url = rtrim($this->resolveBaseUrl(), '/') . '/api/internal/shell-sessions/' . $sessionId . '/close';
$response = $this->request('POST', $url, [
'sessionToken' => $sessionToken,
'transcript' => $transcript,
'closedReason' => $closedReason,
]);
return is_array($response) ? $response : [];
}
private function resolveBaseUrl(): string
{
return trim((string)($this->baseUrl ?? getenv('EDGE_BROKER_URL') ?: 'http://edge-broker:4300'));
}
private function resolveSharedSecret(): string
{
return trim((string)($this->sharedSecret ?? getenv('EDGE_BROKER_SHARED_SECRET') ?: getenv('EDGE_INTERNAL_SECRET') ?: ''));
}
/**
* @throws Exception
*/
private function request(string $method, string $url, array $payload): array|object|null
{
if (trim($url) === '') {
throw new Exception('Edge broker URL is not configured');
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeoutSeconds);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_values(array_filter([
'Content-Type: application/json',
$this->resolveSharedSecret() !== '' ? 'X-Edge-Broker-Secret: ' . $this->resolveSharedSecret() : null,
])));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE));
$rawResponse = curl_exec($ch);
$statusCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($rawResponse === false) {
throw new Exception('Edge broker request failed: ' . $curlError);
}
$decoded = json_decode((string)$rawResponse, true);
if ($statusCode >= 400) {
$message = is_array($decoded)
? (string)($decoded['error'] ?? $decoded['message'] ?? 'Edge broker request failed')
: 'Edge broker request failed';
throw new Exception($message);
}
return $decoded;
}
}
@@ -0,0 +1,975 @@
<?php
namespace classes;
use Exception;
use objects\departments_o;
use objects\department_variables_o;
use objects\edge_gateway_audit_logs_o;
use objects\edge_gateway_claim_tokens_o;
use objects\edge_gateway_command_jobs_o;
use objects\edge_gateway_device_inventory_o;
use objects\edge_gateway_relay_bindings_o;
use objects\edge_gateway_shell_sessions_o;
use objects\edge_gateway_update_jobs_o;
use objects\edge_gateways_o;
class edge_gateway_manager
{
public const DEPARTMENT_VARIABLE_TRANSPORT_MODE = 'shelly_transport_mode';
public const TRANSPORT_MODE_CLOUD = 'cloud';
public const TRANSPORT_MODE_GATEWAY = 'gateway';
public const STATUS_PENDING = 'PENDING';
public const STATUS_ONLINE = 'ONLINE';
public const STATUS_DEGRADED = 'DEGRADED';
public const STATUS_OFFLINE = 'OFFLINE';
public const DEFAULT_RELEASE_CHANNEL = 'stable';
public const INSTALL_TOKEN_TTL_SECONDS = 1800;
public const SHELL_SESSION_TTL_SECONDS = 900;
public function __construct(private readonly ?edge_broker_client $brokerClient = null)
{
edge_gateway_schema_bootstrap::ensureTables();
}
public function createInstallToken(int $departmentId, ?string $label, ?int $createdBy = null): array
{
$this->requireDepartment($departmentId);
$token = bin2hex(random_bytes(24));
$claimToken = new edge_gateway_claim_tokens_o();
$claimTokenId = $claimToken->add_object([
'department_id' => $departmentId,
'label' => $label,
'token_hash' => $this->hashToken($token),
'created_by' => $createdBy,
'expires_at' => $this->formatDateTime(time() + self::INSTALL_TOKEN_TTL_SECONDS),
'metadata_json' => [],
]);
$claimToken->select($claimTokenId);
$this->writeAudit(
null,
$departmentId,
'INSTALL_TOKEN_CREATED',
$createdBy,
['claim_token_id' => $claimTokenId, 'label' => $label]
);
return [
'claim_token_id' => $claimTokenId,
'token' => $token,
'expires_at' => (string)$claimToken->expires_at->value(),
'install_command' => $this->buildInstallCommand($token),
'install_url' => $this->buildInstallScriptUrl($token),
];
}
/**
* @throws Exception
*/
public function claimGateway(string $token, string $hostname, ?string $installedVersion = null, array $metadata = []): array
{
$claimToken = $this->requireClaimToken($token);
if ($claimToken->used_at->value() !== null) {
throw new Exception('Install token has already been used');
}
$departmentId = (int)$claimToken->department_id->value();
$label = trim((string)($claimToken->label->value() ?? $hostname));
$label = $label !== '' ? $label : 'Department gateway';
$agentToken = bin2hex(random_bytes(32));
$gateway = new edge_gateways_o();
$gatewayId = $gateway->add_object([
'department_id' => $departmentId,
'label' => $label,
'hostname' => trim($hostname) !== '' ? trim($hostname) : null,
'agent_token_hash' => $this->hashToken($agentToken),
'status' => self::STATUS_ONLINE,
'transport_mode' => self::TRANSPORT_MODE_GATEWAY,
'release_channel' => self::DEFAULT_RELEASE_CHANNEL,
'installed_version' => $installedVersion,
'target_version' => $installedVersion,
'last_heartbeat_at' => $this->now(),
'last_seen_ip' => $this->remoteIp(),
'discovery_status' => 'PENDING',
'is_primary' => 1,
'metadata_json' => $metadata,
]);
$claimToken->used_at->set($this->now());
$gateway->select($gatewayId);
$this->writeAudit(
$gatewayId,
$departmentId,
'GATEWAY_CLAIMED',
null,
['hostname' => $hostname, 'installed_version' => $installedVersion]
);
return [
'gateway' => $this->getGateway($gatewayId),
'agent_token' => $agentToken,
'broker_url' => $this->getBrokerPublicUrl(),
'heartbeat_url' => $this->getApiBaseUrl() . '/edge-agent/gateways/' . $gatewayId . '/heartbeat',
'release_channel' => (string)$gateway->release_channel->value(),
];
}
/**
* @throws Exception
*/
public function rotateGatewayCredentials(int $gatewayId, ?int $userId = null): array
{
$gateway = $this->requireGateway($gatewayId);
$token = bin2hex(random_bytes(32));
$gateway->agent_token_hash->set($this->hashToken($token));
$this->writeAudit(
$gatewayId,
(int)$gateway->department_id->value(),
'GATEWAY_CREDENTIALS_ROTATED',
$userId,
[]
);
return [
'gateway' => $this->getGateway($gatewayId),
'agent_token' => $token,
];
}
/**
* @throws Exception
*/
public function authenticateGateway(int $gatewayId, string $plainToken): edge_gateways_o
{
$gateway = $this->requireGateway($gatewayId);
if (!hash_equals((string)$gateway->agent_token_hash->value(), $this->hashToken($plainToken))) {
throw new Exception('Invalid edge gateway token');
}
return $gateway;
}
/**
* @throws Exception
*/
public function recordHeartbeat(int $gatewayId, string $plainToken, array $payload): array
{
$gateway = $this->authenticateGateway($gatewayId, $plainToken);
$gateway->status->set((string)($payload['status'] ?? self::STATUS_ONLINE));
$gateway->hostname->set($payload['hostname'] ?? $gateway->hostname->value());
$gateway->installed_version->set($payload['installed_version'] ?? $gateway->installed_version->value());
$gateway->target_version->set($payload['target_version'] ?? $gateway->target_version->value());
$gateway->last_heartbeat_at->set($this->now());
$gateway->last_seen_ip->set($this->remoteIp());
$gateway->discovery_status->set((string)($payload['discovery_status'] ?? $gateway->discovery_status->value()));
$gateway->metadata_json->set((array)($payload['metadata'] ?? $gateway->metadata_json->value() ?? []));
if (isset($payload['inventory']) && is_array($payload['inventory'])) {
$this->syncDeviceInventory($gatewayId, $payload['inventory']);
}
return $this->getGateway($gatewayId);
}
/**
* @return array<int,array<string,mixed>>
* @throws Exception
*/
public function listGateways(?int $departmentId = null): array
{
$gatewayObject = new edge_gateways_o();
$rows = $departmentId === null
? $gatewayObject->getFieldsWhere(['deleted_at' => null], ['id'])
: $gatewayObject->getFieldsWhere(['department_id' => $departmentId, 'deleted_at' => null], ['id']);
$gateways = [];
foreach ($rows as $row) {
$gateways[] = $this->getGateway((int)$row['id']);
}
usort($gateways, static fn(array $a, array $b): int => ($a['department_id'] <=> $b['department_id']) ?: ($a['id'] <=> $b['id']));
return $gateways;
}
/**
* @throws Exception
*/
public function getGateway(int $gatewayId): array
{
$gateway = $this->requireGateway($gatewayId);
$data = $gateway->asArray();
$data['inventory'] = $this->listInventory($gatewayId);
$data['bindings'] = $this->listBindings($gatewayId);
$data['recent_commands'] = $this->listRecentObjects(new edge_gateway_command_jobs_o(), ['gateway_id' => $gatewayId, 'deleted_at' => null]);
$data['recent_updates'] = $this->listRecentObjects(new edge_gateway_update_jobs_o(), ['gateway_id' => $gatewayId, 'deleted_at' => null]);
$data['recent_shell_sessions'] = $this->listRecentObjects(new edge_gateway_shell_sessions_o(), ['gateway_id' => $gatewayId, 'deleted_at' => null]);
$data['audit_logs'] = $this->listRecentObjects(new edge_gateway_audit_logs_o(), ['gateway_id' => $gatewayId]);
$data['department_transport_mode'] = $this->getDepartmentTransportMode((int)$gateway->department_id->value());
return $data;
}
/**
* @throws Exception
*/
public function setDepartmentTransportMode(int $departmentId, string $transportMode, ?int $userId = null): array
{
if (!in_array($transportMode, [self::TRANSPORT_MODE_CLOUD, self::TRANSPORT_MODE_GATEWAY], true)) {
throw new Exception('Invalid transport mode');
}
$department = $this->requireDepartment($departmentId);
$department->variables->set(self::DEPARTMENT_VARIABLE_TRANSPORT_MODE, $transportMode);
$this->writeAudit(
null,
$departmentId,
'DEPARTMENT_TRANSPORT_MODE_UPDATED',
$userId,
['transport_mode' => $transportMode]
);
return [
'department_id' => $departmentId,
'transport_mode' => $transportMode,
];
}
public function getDepartmentTransportMode(int $departmentId): string
{
$variables = (new department_variables_o())->selectDepartment($departmentId);
$mode = $variables->getVariable(self::DEPARTMENT_VARIABLE_TRANSPORT_MODE);
if ($mode === self::TRANSPORT_MODE_GATEWAY) {
return self::TRANSPORT_MODE_GATEWAY;
}
return self::TRANSPORT_MODE_CLOUD;
}
/**
* @return array<int,array<string,mixed>>
* @throws Exception
*/
public function setRelayBindings(int $gatewayId, array $bindings, ?int $userId = null): array
{
$gateway = $this->requireGateway($gatewayId);
$departmentId = (int)$gateway->department_id->value();
$incomingRelayIds = [];
foreach ($bindings as $binding) {
$relayId = trim((string)($binding['relay_id'] ?? ''));
$deviceId = trim((string)($binding['device_id'] ?? ''));
if ($relayId === '' || $deviceId === '') {
throw new Exception('Each relay binding must contain relay_id and device_id');
}
$incomingRelayIds[] = $relayId;
$existing = (new edge_gateway_relay_bindings_o())->getFieldsWhere([
'gateway_id' => $gatewayId,
'relay_id' => $relayId,
'deleted_at' => null,
], ['id']);
if ($existing !== []) {
$bindingObject = (new edge_gateway_relay_bindings_o())->select((int)$existing[0]['id']);
$bindingObject->device_id->set($deviceId);
$bindingObject->local_ip->set($binding['local_ip'] ?? null);
$bindingObject->channel->set((int)($binding['channel'] ?? 0));
$bindingObject->binding_source->set((string)($binding['binding_source'] ?? 'MANUAL'));
$bindingObject->approved_by->set($userId);
$bindingObject->approved_at->set($this->now());
$bindingObject->metadata_json->set((array)($binding['metadata'] ?? []));
continue;
}
(new edge_gateway_relay_bindings_o())->add_object([
'gateway_id' => $gatewayId,
'department_id' => $departmentId,
'relay_id' => $relayId,
'device_id' => $deviceId,
'local_ip' => $binding['local_ip'] ?? null,
'channel' => (int)($binding['channel'] ?? 0),
'binding_source' => (string)($binding['binding_source'] ?? 'MANUAL'),
'approved_by' => $userId,
'approved_at' => $this->now(),
'metadata_json' => (array)($binding['metadata'] ?? []),
]);
}
foreach ($this->listBindings($gatewayId) as $existingBinding) {
if (in_array((string)$existingBinding['relay_id'], $incomingRelayIds, true)) {
continue;
}
$bindingObject = (new edge_gateway_relay_bindings_o())->select((int)$existingBinding['id']);
$bindingObject->deleted_at->set($this->now());
}
$this->writeAudit(
$gatewayId,
$departmentId,
'RELAY_BINDINGS_UPDATED',
$userId,
['binding_count' => count($bindings)]
);
return $this->listBindings($gatewayId);
}
/**
* @throws Exception
*/
public function queueDiscovery(int $gatewayId, ?int $userId = null): array
{
$gateway = $this->requireGateway($gatewayId);
$job = $this->createCommandJob($gatewayId, 'DISCOVER_SHELLY', [], $userId);
$response = $this->dispatchCommandJob($job, $gateway, [
'requestedBy' => $userId,
]);
if (isset($response['inventory']) && is_array($response['inventory'])) {
$this->syncDeviceInventory($gatewayId, $response['inventory']);
}
return $this->getGateway($gatewayId);
}
/**
* @throws Exception
*/
public function queueUpdate(int $gatewayId, string $targetVersion, string $releaseChannel, ?int $userId = null): array
{
$gateway = $this->requireGateway($gatewayId);
$jobObject = new edge_gateway_update_jobs_o();
$jobId = $jobObject->add_object([
'gateway_id' => $gatewayId,
'target_version' => $targetVersion,
'release_channel' => $releaseChannel,
'status' => 'PENDING',
'requested_by' => $userId,
'requested_at' => $this->now(),
'result_json' => [],
]);
$jobObject->select($jobId);
$command = $this->createCommandJob($gatewayId, 'RUN_UPDATE', [
'targetVersion' => $targetVersion,
'releaseChannel' => $releaseChannel,
], $userId);
try {
$response = $this->dispatchCommandJob($command, $gateway, [
'targetVersion' => $targetVersion,
'releaseChannel' => $releaseChannel,
]);
$jobObject->status->set('COMPLETED');
$jobObject->started_at->set($this->now());
$jobObject->completed_at->set($this->now());
$jobObject->result_json->set($response);
} catch (\Throwable $throwable) {
$jobObject->status->set('FAILED');
$jobObject->completed_at->set($this->now());
$jobObject->result_json->set(['error' => $throwable->getMessage()]);
throw $throwable;
}
$this->writeAudit(
$gatewayId,
(int)$gateway->department_id->value(),
'UPDATE_QUEUED',
$userId,
['target_version' => $targetVersion, 'release_channel' => $releaseChannel]
);
return $jobObject->asArray();
}
/**
* @throws Exception
*/
public function createShellSession(int $gatewayId, string $reason, ?int $userId = null): array
{
$gateway = $this->requireGateway($gatewayId);
$sessionToken = bin2hex(random_bytes(32));
$sessionObject = new edge_gateway_shell_sessions_o();
$sessionId = $sessionObject->add_object([
'gateway_id' => $gatewayId,
'reason' => $reason,
'approval_status' => 'APPROVED',
'session_token_hash' => $this->hashToken($sessionToken),
'requested_by' => $userId,
'approved_by' => $userId,
'approved_at' => $this->now(),
'expires_at' => $this->formatDateTime(time() + self::SHELL_SESSION_TTL_SECONDS),
'metadata_json' => [
'ttl_seconds' => self::SHELL_SESSION_TTL_SECONDS,
],
]);
$sessionObject->select($sessionId);
$this->writeAudit(
$gatewayId,
(int)$gateway->department_id->value(),
'ROOT_SHELL_APPROVED',
$userId,
['reason' => $reason, 'session_id' => $sessionId]
);
return [
'session' => $sessionObject->asArray(),
'session_token' => $sessionToken,
'websocket_url' => $this->buildBrowserShellWsUrl($sessionToken),
];
}
/**
* @throws Exception
*/
public function validateShellSessionToken(string $plainToken): array
{
$tokenHash = $this->hashToken($plainToken);
$rows = (new edge_gateway_shell_sessions_o())->getFieldsWhere([
'session_token_hash' => $tokenHash,
'deleted_at' => null,
], ['id']);
if ($rows === []) {
throw new Exception('Invalid shell session token');
}
$session = (new edge_gateway_shell_sessions_o())->select((int)$rows[0]['id']);
if (!$session->exists()) {
throw new Exception('Shell session not found');
}
if (strtotime((string)$session->expires_at->value()) < time()) {
throw new Exception('Shell session has expired');
}
return $session->asArray();
}
/**
* @throws Exception
*/
public function closeShellSession(string $plainToken, string $transcript, string $closedReason): array
{
$sessionData = $this->validateShellSessionToken($plainToken);
$session = (new edge_gateway_shell_sessions_o())->select((int)$sessionData['id']);
$session->closed_at->set($this->now());
$session->transcript_text->set($transcript);
$metadata = (array)($session->metadata_json->value() ?? []);
$metadata['closed_reason'] = $closedReason;
$session->metadata_json->set($metadata);
$this->writeAudit(
(int)$session->gateway_id->value(),
null,
'ROOT_SHELL_CLOSED',
null,
['session_id' => (int)$session->id, 'closed_reason' => $closedReason]
);
return $session->asArray();
}
/**
* @throws Exception
*/
public function resolveRelayBinding(int $departmentId, string $logicalRelayId): array
{
$gateway = $this->getPrimaryGatewayForDepartment($departmentId);
$rows = (new edge_gateway_relay_bindings_o())->getFieldsWhere([
'department_id' => $departmentId,
'gateway_id' => (int)$gateway->id,
'relay_id' => $logicalRelayId,
'deleted_at' => null,
], ['id']);
if ($rows === []) {
throw new Exception('No edge gateway relay binding found for relay ' . $logicalRelayId);
}
return (new edge_gateway_relay_bindings_o())->select((int)$rows[0]['id'])->asArray();
}
/**
* @throws Exception
*/
public function dispatchRelayStatus(int $departmentId, string $logicalRelayId): array
{
$binding = $this->resolveRelayBinding($departmentId, $logicalRelayId);
$gateway = $this->requireGateway((int)$binding['gateway_id']);
$job = $this->createCommandJob((int)$gateway->id, 'GET_RELAY_STATUS', [
'relayId' => $logicalRelayId,
'deviceId' => $binding['device_id'],
'localIp' => $binding['local_ip'],
'channel' => (int)$binding['channel'],
], null);
return $this->dispatchCommandJob($job, $gateway, [
'relayId' => $logicalRelayId,
'deviceId' => $binding['device_id'],
'localIp' => $binding['local_ip'],
'channel' => (int)$binding['channel'],
]);
}
/**
* @throws Exception
*/
public function dispatchRelaySwitch(int $departmentId, string $logicalRelayId, bool $on): array
{
$binding = $this->resolveRelayBinding($departmentId, $logicalRelayId);
$gateway = $this->requireGateway((int)$binding['gateway_id']);
$job = $this->createCommandJob((int)$gateway->id, 'SET_RELAY_STATE', [
'relayId' => $logicalRelayId,
'deviceId' => $binding['device_id'],
'localIp' => $binding['local_ip'],
'channel' => (int)$binding['channel'],
'on' => $on,
], null);
return $this->dispatchCommandJob($job, $gateway, [
'relayId' => $logicalRelayId,
'deviceId' => $binding['device_id'],
'localIp' => $binding['local_ip'],
'channel' => (int)$binding['channel'],
'on' => $on,
]);
}
/**
* @return array<int,array<string,mixed>>
*/
public function listBindings(int $gatewayId): array
{
return $this->listRecentObjects(new edge_gateway_relay_bindings_o(), [
'gateway_id' => $gatewayId,
'deleted_at' => null,
], 100);
}
/**
* @return array<int,array<string,mixed>>
*/
public function listInventory(int $gatewayId): array
{
return $this->listRecentObjects(new edge_gateway_device_inventory_o(), [
'gateway_id' => $gatewayId,
'deleted_at' => null,
], 100);
}
public function buildInstallCommand(string $plainToken): string
{
return 'curl -fsSL ' . escapeshellarg($this->buildInstallScriptUrl($plainToken)) . ' | sudo bash';
}
public function buildInstallScriptUrl(string $plainToken): string
{
return rtrim($this->getApiBaseUrl(), '/') . '/edge-agent/install.sh?token=' . urlencode($plainToken);
}
public function buildInstallScript(string $plainToken): string
{
$configJson = json_encode([
'apiUrl' => $this->getApiBaseUrl(),
'brokerUrl' => $this->getBrokerPublicUrl(),
'installToken' => $plainToken,
'gatewayId' => null,
'agentToken' => null,
'heartbeatIntervalSeconds' => 15,
], JSON_UNESCAPED_SLASHES);
$script = <<<'BASH'
#!/usr/bin/env bash
set -euo pipefail
INSTALL_DIR=/opt/truckwash-edge-agent
mkdir -p "$INSTALL_DIR"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y curl ca-certificates nodejs npm
curl -fsSL "__PACKAGE_URL__" -o "$INSTALL_DIR/package.json"
curl -fsSL "__AGENT_URL__" -o "$INSTALL_DIR/agent.mjs"
cat > "$INSTALL_DIR/config.json" <<'EOF_JSON'
__CONFIG_JSON__
EOF_JSON
cd "$INSTALL_DIR"
npm install --omit=dev
cat >/etc/systemd/system/truckwash-edge-agent.service <<'EOF'
[Unit]
Description=TruckWash Edge Agent
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/truckwash-edge-agent
ExecStart=/usr/bin/node /opt/truckwash-edge-agent/agent.mjs --config /opt/truckwash-edge-agent/config.json
Restart=always
RestartSec=5
User=root
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now truckwash-edge-agent.service
echo 'TruckWash edge agent installed.'
BASH;
return strtr($script, [
'__PACKAGE_URL__' => rtrim($this->getApiBaseUrl(), '/') . '/edge-agent/artifacts/package.json',
'__AGENT_URL__' => rtrim($this->getApiBaseUrl(), '/') . '/edge-agent/artifacts/agent.mjs',
'__CONFIG_JSON__' => (string)$configJson,
]);
}
public function buildBrowserShellWsUrl(string $sessionToken): ?string
{
$brokerUrl = $this->getBrokerPublicUrl();
if ($brokerUrl === null) {
return null;
}
$parsed = parse_url($brokerUrl);
if (!is_array($parsed) || !isset($parsed['host'])) {
return null;
}
$scheme = (($parsed['scheme'] ?? 'http') === 'https') ? 'wss' : 'ws';
$url = $scheme . '://' . $parsed['host'];
if (isset($parsed['port'])) {
$url .= ':' . $parsed['port'];
}
$url .= '/ws/browser-shell?token=' . urlencode($sessionToken);
return $url;
}
public function getBrokerPublicUrl(): ?string
{
$configured = trim((string)(getenv('EDGE_BROKER_PUBLIC_URL') ?: ''));
if ($configured !== '') {
return $configured;
}
$apiBaseUrl = $this->getApiBaseUrl();
$parsed = parse_url($apiBaseUrl);
if (!is_array($parsed) || !isset($parsed['host'])) {
return null;
}
$scheme = ($parsed['scheme'] ?? 'https') === 'https' ? 'https' : 'http';
$port = getenv('EDGE_BROKER_PUBLIC_PORT') ?: '4300';
return $scheme . '://' . $parsed['host'] . ':' . $port;
}
public function getApiBaseUrl(): string
{
$configured = trim((string)(getenv('EDGE_PUBLIC_API_URL') ?: ''));
if ($configured !== '') {
return $configured;
}
$forwardedScheme = $this->detectForwardedScheme();
if ($forwardedScheme !== null) {
$scheme = strtolower($forwardedScheme) === 'https' ? 'https' : 'http';
} else {
$requestScheme = strtolower(trim((string)($_SERVER['REQUEST_SCHEME'] ?? '')));
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $requestScheme === 'https' ? 'https' : 'http';
}
$host = trim((string)($this->firstForwardedHeaderValue($_SERVER['HTTP_X_FORWARDED_HOST'] ?? null) ?? ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost')));
if ($host === '') {
$host = 'localhost';
}
$forwardedPort = $this->firstForwardedHeaderValue($_SERVER['HTTP_X_FORWARDED_PORT'] ?? null);
$port = $forwardedPort !== null ? (int)$forwardedPort : 0;
if ($port <= 0) {
$hostPort = parse_url($scheme . '://' . $host, PHP_URL_PORT);
$port = is_int($hostPort) ? $hostPort : (int)($_SERVER['SERVER_PORT'] ?? 0);
}
if ($scheme === 'http' && in_array($port, [443, 4433], true)) {
$scheme = 'https';
}
if ($port > 0 && !str_contains($host, ':') && !(($scheme === 'https' && $port === 443) || ($scheme === 'http' && $port === 80))) {
$host .= ':' . $port;
}
return $scheme . '://' . $host;
}
private function detectForwardedScheme(): ?string
{
$forwardedScheme = $this->firstForwardedHeaderValue($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null);
if ($forwardedScheme !== null) {
return $forwardedScheme;
}
$forwardedScheme = $this->firstForwardedHeaderValue($_SERVER['HTTP_X_FORWARDED_PROTOCOL'] ?? null);
if ($forwardedScheme !== null) {
return $forwardedScheme;
}
$forwardedHeader = trim((string)($_SERVER['HTTP_FORWARDED'] ?? ''));
if ($forwardedHeader !== '' && preg_match('/proto=([^;,\s]+)/i', $forwardedHeader, $matches) === 1) {
return trim($matches[1], "\"'");
}
return null;
}
private function firstForwardedHeaderValue(mixed $value): ?string
{
if (!is_string($value)) {
return null;
}
foreach (explode(',', $value) as $segment) {
$normalized = trim($segment);
if ($normalized !== '') {
return $normalized;
}
}
return null;
}
/**
* @throws Exception
*/
private function requireGateway(int $gatewayId): edge_gateways_o
{
$gateway = (new edge_gateways_o())->select($gatewayId);
if (!$gateway->exists()) {
throw new Exception('Edge gateway not found');
}
return $gateway;
}
/**
* @throws Exception
*/
private function requireDepartment(int $departmentId): departments_o
{
$department = (new departments_o())->select($departmentId);
if (!$department->exists()) {
throw new Exception('Department not found');
}
return $department;
}
/**
* @throws Exception
*/
private function requireClaimToken(string $plainToken): edge_gateway_claim_tokens_o
{
$rows = (new edge_gateway_claim_tokens_o())->getFieldsWhere([
'token_hash' => $this->hashToken($plainToken),
'deleted_at' => null,
], ['id']);
if ($rows === []) {
throw new Exception('Invalid install token');
}
$claimToken = (new edge_gateway_claim_tokens_o())->select((int)$rows[0]['id']);
if (!$claimToken->exists()) {
throw new Exception('Invalid install token');
}
if (strtotime((string)$claimToken->expires_at->value()) < time()) {
throw new Exception('Install token has expired');
}
return $claimToken;
}
/**
* @throws Exception
*/
private function getPrimaryGatewayForDepartment(int $departmentId): edge_gateways_o
{
$rows = (new edge_gateways_o())->getFieldsWhere([
'department_id' => $departmentId,
'deleted_at' => null,
], ['id']);
if ($rows === []) {
throw new Exception('No edge gateway found for department');
}
$gatewayIds = array_map(static fn(array $row): int => (int)$row['id'], $rows);
$gateways = array_map(static fn(int $id): edge_gateways_o => (new edge_gateways_o())->select($id), $gatewayIds);
usort($gateways, static function (edge_gateways_o $a, edge_gateways_o $b): int {
return ((int)$b->is_primary->value() <=> (int)$a->is_primary->value())
?: strcmp((string)$b->status->value(), (string)$a->status->value());
});
$gateway = $gateways[0];
if (!in_array((string)$gateway->status->value(), [self::STATUS_ONLINE, self::STATUS_DEGRADED], true)) {
throw new Exception('Department edge gateway is offline');
}
return $gateway;
}
private function createCommandJob(int $gatewayId, string $commandType, array $request, ?int $userId): edge_gateway_command_jobs_o
{
$jobObject = new edge_gateway_command_jobs_o();
$jobId = $jobObject->add_object([
'gateway_id' => $gatewayId,
'command_type' => $commandType,
'status' => 'PENDING',
'request_json' => $request,
'response_json' => [],
'correlation_id' => bin2hex(random_bytes(16)),
'requested_by' => $userId,
'requested_at' => $this->now(),
]);
return $jobObject->select($jobId);
}
/**
* @throws Exception
*/
private function dispatchCommandJob(edge_gateway_command_jobs_o $job, edge_gateways_o $gateway, array $payload): array
{
$job->status->set('DISPATCHING');
$response = $this->broker()->dispatchCommand(
(int)$gateway->id,
(string)$job->command_type->value(),
[
'jobId' => (int)$job->id,
'gatewayId' => (int)$gateway->id,
'departmentId' => (int)$gateway->department_id->value(),
'payload' => $payload,
]
);
$job->response_json->set($response);
$job->completed_at->set($this->now());
$ok = (bool)($response['ok'] ?? false);
$job->status->set($ok ? 'COMPLETED' : 'FAILED');
if (!$ok) {
$job->error_message->set((string)($response['error'] ?? 'Edge broker command failed'));
throw new Exception((string)($response['error'] ?? 'Edge broker command failed'));
}
return (array)($response['payload'] ?? $response);
}
/**
* @param array<int,array<string,mixed>> $inventory
*/
private function syncDeviceInventory(int $gatewayId, array $inventory): void
{
foreach ($inventory as $device) {
$deviceId = trim((string)($device['device_id'] ?? $device['id'] ?? ''));
if ($deviceId === '') {
continue;
}
$rows = (new edge_gateway_device_inventory_o())->getFieldsWhere([
'gateway_id' => $gatewayId,
'device_id' => $deviceId,
'deleted_at' => null,
], ['id']);
if ($rows === []) {
(new edge_gateway_device_inventory_o())->add_object([
'gateway_id' => $gatewayId,
'device_id' => $deviceId,
'local_ip' => $device['local_ip'] ?? $device['ip'] ?? null,
'model' => $device['model'] ?? null,
'channel_count' => (int)($device['channel_count'] ?? $device['channels'] ?? 1),
'capabilities_json' => (array)($device['capabilities'] ?? []),
'online' => (bool)($device['online'] ?? true),
'last_seen_at' => $this->now(),
'metadata_json' => (array)($device['metadata'] ?? []),
]);
continue;
}
$inventoryObject = (new edge_gateway_device_inventory_o())->select((int)$rows[0]['id']);
$inventoryObject->local_ip->set($device['local_ip'] ?? $device['ip'] ?? null);
$inventoryObject->model->set($device['model'] ?? null);
$inventoryObject->channel_count->set((int)($device['channel_count'] ?? $device['channels'] ?? 1));
$inventoryObject->capabilities_json->set((array)($device['capabilities'] ?? []));
$inventoryObject->online->set((bool)($device['online'] ?? true));
$inventoryObject->last_seen_at->set($this->now());
$inventoryObject->metadata_json->set((array)($device['metadata'] ?? []));
}
}
/**
* @return array<int,array<string,mixed>>
*/
private function listRecentObjects(object $object, array $conditions, int $limit = 20): array
{
if (!method_exists($object, 'getFieldsWhere') || !method_exists($object, 'select')) {
return [];
}
$rows = $object->getFieldsWhere($conditions, ['id']);
$ids = array_map(static fn(array $row): int => (int)$row['id'], $rows);
rsort($ids);
$ids = array_slice($ids, 0, $limit);
$result = [];
foreach ($ids as $id) {
$tmp = $object::class;
$selected = (new $tmp())->select($id);
if (method_exists($selected, 'asArray')) {
$result[] = $selected->asArray();
}
}
return $result;
}
private function writeAudit(?int $gatewayId, ?int $departmentId, string $action, ?int $userId, array $context): void
{
(new edge_gateway_audit_logs_o())->add_object([
'gateway_id' => $gatewayId,
'department_id' => $departmentId,
'action' => $action,
'actor_user_id' => $userId,
'actor_type' => $userId === null ? 'SYSTEM' : 'USER',
'severity' => 'INFO',
'context_json' => $context,
]);
}
private function broker(): edge_broker_client
{
return $this->brokerClient ?? new edge_broker_client();
}
private function hashToken(string $plainToken): string
{
return hash('sha256', $plainToken);
}
private function now(): string
{
return date('Y-m-d H:i:s');
}
private function formatDateTime(int $timestamp): string
{
return date('Y-m-d H:i:s', $timestamp);
}
private function remoteIp(): ?string
{
$ip = trim((string)($_SERVER['REMOTE_ADDR'] ?? ''));
return $ip !== '' ? $ip : null;
}
}
@@ -0,0 +1,187 @@
<?php
namespace classes;
/**
* Ensures additive department edge gateway tables exist.
*
* The legacy PHP stack has no centralized migration runner, so this bootstrap
* must be safe to call from runtime flows and tests.
*/
class edge_gateway_schema_bootstrap
{
private static bool $initialized = false;
public static function ensureTables(): void
{
if (self::$initialized) {
return;
}
global $db;
$queries = [
"CREATE TABLE IF NOT EXISTS edge_gateways (
id INT AUTO_INCREMENT PRIMARY KEY,
department_id INT NOT NULL,
label VARCHAR(255) NOT NULL,
hostname VARCHAR(255) NULL,
agent_token_hash VARCHAR(255) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
transport_mode VARCHAR(32) NOT NULL DEFAULT 'gateway',
release_channel VARCHAR(32) NOT NULL DEFAULT 'stable',
installed_version VARCHAR(64) NULL,
target_version VARCHAR(64) NULL,
last_heartbeat_at DATETIME NULL,
last_seen_ip VARCHAR(64) NULL,
discovery_status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
is_primary TINYINT(1) NOT NULL DEFAULT 1,
metadata_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
INDEX idx_edge_gateways_department_status (department_id, status),
INDEX idx_edge_gateways_department_primary (department_id, is_primary),
INDEX idx_edge_gateways_last_heartbeat (last_heartbeat_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_claim_tokens (
id INT AUTO_INCREMENT PRIMARY KEY,
department_id INT NOT NULL,
label VARCHAR(255) NULL,
token_hash VARCHAR(255) NOT NULL,
created_by INT NULL,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
metadata_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
INDEX idx_edge_gateway_claim_tokens_department (department_id),
INDEX idx_edge_gateway_claim_tokens_expires (expires_at),
INDEX idx_edge_gateway_claim_tokens_used (used_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_device_inventory (
id INT AUTO_INCREMENT PRIMARY KEY,
gateway_id INT NOT NULL,
device_id VARCHAR(255) NOT NULL,
local_ip VARCHAR(64) NULL,
model VARCHAR(255) NULL,
channel_count INT NOT NULL DEFAULT 1,
capabilities_json JSON NULL,
online TINYINT(1) NOT NULL DEFAULT 0,
last_seen_at DATETIME NULL,
metadata_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
UNIQUE KEY uniq_edge_gateway_inventory_device (gateway_id, device_id),
INDEX idx_edge_gateway_inventory_gateway (gateway_id),
INDEX idx_edge_gateway_inventory_ip (local_ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_relay_bindings (
id INT AUTO_INCREMENT PRIMARY KEY,
gateway_id INT NOT NULL,
department_id INT NOT NULL,
relay_id VARCHAR(255) NOT NULL,
device_id VARCHAR(255) NOT NULL,
local_ip VARCHAR(64) NULL,
channel INT NOT NULL DEFAULT 0,
binding_source VARCHAR(64) NOT NULL DEFAULT 'MANUAL',
approved_by INT NULL,
approved_at DATETIME NULL,
metadata_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
UNIQUE KEY uniq_edge_gateway_binding (gateway_id, relay_id),
INDEX idx_edge_gateway_binding_department (department_id),
INDEX idx_edge_gateway_binding_device (gateway_id, device_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_command_jobs (
id INT AUTO_INCREMENT PRIMARY KEY,
gateway_id INT NOT NULL,
command_type VARCHAR(64) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
request_json JSON NULL,
response_json JSON NULL,
correlation_id VARCHAR(128) NOT NULL,
requested_by INT NULL,
requested_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME NULL,
error_message TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
UNIQUE KEY uniq_edge_gateway_command_correlation (correlation_id),
INDEX idx_edge_gateway_command_gateway (gateway_id),
INDEX idx_edge_gateway_command_status (status),
INDEX idx_edge_gateway_command_type (command_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_update_jobs (
id INT AUTO_INCREMENT PRIMARY KEY,
gateway_id INT NOT NULL,
target_version VARCHAR(64) NOT NULL,
release_channel VARCHAR(32) NOT NULL DEFAULT 'stable',
status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
requested_by INT NULL,
requested_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
started_at DATETIME NULL,
completed_at DATETIME NULL,
result_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
INDEX idx_edge_gateway_update_gateway (gateway_id),
INDEX idx_edge_gateway_update_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_shell_sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
gateway_id INT NOT NULL,
reason TEXT NOT NULL,
approval_status VARCHAR(32) NOT NULL DEFAULT 'APPROVED',
session_token_hash VARCHAR(255) NOT NULL,
requested_by INT NULL,
approved_by INT NULL,
approved_at DATETIME NULL,
expires_at DATETIME NOT NULL,
opened_at DATETIME NULL,
closed_at DATETIME NULL,
transcript_text LONGTEXT NULL,
metadata_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted_at TIMESTAMP NULL DEFAULT NULL,
INDEX idx_edge_gateway_shell_gateway (gateway_id),
INDEX idx_edge_gateway_shell_expires (expires_at),
INDEX idx_edge_gateway_shell_status (approval_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
"CREATE TABLE IF NOT EXISTS edge_gateway_audit_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
gateway_id INT NULL,
department_id INT NULL,
action VARCHAR(128) NOT NULL,
actor_user_id INT NULL,
actor_type VARCHAR(32) NOT NULL DEFAULT 'USER',
severity VARCHAR(16) NOT NULL DEFAULT 'INFO',
context_json JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX idx_edge_gateway_audit_gateway (gateway_id),
INDEX idx_edge_gateway_audit_department (department_id),
INDEX idx_edge_gateway_audit_action (action)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
];
foreach ($queries as $sql) {
$db->query($sql);
}
self::$initialized = true;
}
}
@@ -0,0 +1,109 @@
<?php
namespace classes;
require_once WD . '/interfaces/shelly_transport_i.php';
require_once WD . '/classes/edge_gateway_manager.php';
use Exception;
use interfaces\shelly_transport_i;
class gateway_shelly_transport implements shelly_transport_i
{
public function __construct(private readonly ?edge_gateway_manager $manager = null)
{
}
public function requireModuleEnabled(): void
{
// Gateway mode is department-scoped and does not depend on the Shelly cloud module flag.
}
public function requireValidSecretKey(): void
{
// Gateway mode does not use the Shelly cloud auth key.
}
/**
* @throws Exception
*/
public function sendPostRequest(string $endpoint, array $data, ?int $department_id = null): array|object|null
{
if ($department_id === null || $department_id <= 0) {
throw new Exception('A department_id is required for gateway Shelly transport');
}
return match ($endpoint) {
'/v2/devices/api/get' => $this->handleGetStates($department_id, $data),
'/v2/devices/api/set/switch' => $this->handleSetSwitch($department_id, $data),
default => throw new Exception('Unsupported gateway Shelly transport endpoint: ' . $endpoint),
};
}
/**
* @return array<int,array<string,mixed>>
* @throws Exception
*/
private function handleGetStates(int $departmentId, array $data): array
{
$ids = array_values(array_filter(
array_map(static fn(mixed $value): string => trim((string)$value), (array)($data['ids'] ?? [])),
static fn(string $value): bool => $value !== ''
));
$result = [];
foreach ($ids as $logicalRelayId) {
$status = $this->manager()->dispatchRelayStatus($departmentId, $logicalRelayId);
$result[] = $this->normalizeRelayPayload($logicalRelayId, $status);
}
return $result;
}
/**
* @throws Exception
*/
private function handleSetSwitch(int $departmentId, array $data): array
{
$logicalRelayId = trim((string)($data['id'] ?? ''));
if ($logicalRelayId === '') {
throw new Exception('Shelly gateway switch requests require an id');
}
$status = $this->manager()->dispatchRelaySwitch(
$departmentId,
$logicalRelayId,
(bool)($data['on'] ?? false)
);
return [$this->normalizeRelayPayload($logicalRelayId, $status)];
}
/**
* @param array<string,mixed> $status
* @return array<string,mixed>
*/
private function normalizeRelayPayload(string $logicalRelayId, array $status): array
{
$on = (bool)($status['on'] ?? $status['output'] ?? false);
$online = (bool)($status['online'] ?? true);
return [
'id' => $logicalRelayId,
'online' => $online,
'on' => $on,
'status' => [
'switch:0' => [
'output' => $on,
],
],
'binding' => (array)($status['binding'] ?? []),
'raw' => (array)($status['raw'] ?? []),
];
}
private function manager(): edge_gateway_manager
{
return $this->manager ?? new edge_gateway_manager();
}
}
@@ -0,0 +1,35 @@
<?php
namespace classes;
require_once WD . '/interfaces/shelly_transport_i.php';
require_once WD . '/classes/edge_gateway_manager.php';
require_once WD . '/classes/cloud_shelly_transport.php';
require_once WD . '/classes/gateway_shelly_transport.php';
use interfaces\shelly_transport_i;
class shelly_transport_resolver
{
public function __construct(
private readonly ?edge_gateway_manager $edgeGatewayManager = null,
private readonly ?shelly_transport_i $cloudTransport = null,
private readonly ?shelly_transport_i $gatewayTransport = null
) {
}
public function resolveForDepartment(int $departmentId): shelly_transport_i
{
$mode = $this->manager()->getDepartmentTransportMode($departmentId);
if ($mode === edge_gateway_manager::TRANSPORT_MODE_GATEWAY) {
return $this->gatewayTransport ?? new gateway_shelly_transport($this->manager());
}
return $this->cloudTransport ?? new cloud_shelly_transport();
}
private function manager(): edge_gateway_manager
{
return $this->edgeGatewayManager ?? new edge_gateway_manager();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,124 @@
<?php
namespace classes;
/**
* Ensures additive system session activity storage exists.
*
* This project uses lazy runtime schema bootstraps instead of a central
* migration runner, so every change must be idempotent.
*/
class system_session_activity_schema_bootstrap
{
private static bool $initialized = false;
public static function ensureTables(): void
{
if (self::$initialized) {
return;
}
global $db;
$queries = [
"CREATE TABLE IF NOT EXISTS system_session_activity (
id INT AUTO_INCREMENT PRIMARY KEY,
session_hash CHAR(64) NOT NULL,
session_kind VARCHAR(16) NOT NULL,
principal_id INT NOT NULL,
customer_number_context INT NULL,
device_type VARCHAR(16) NOT NULL DEFAULT 'unknown',
user_agent VARCHAR(1024) NULL,
last_route VARCHAR(255) NULL,
first_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uniq_system_session_activity_session_hash (session_hash),
INDEX idx_system_session_activity_last_seen_at (last_seen_at),
INDEX idx_system_session_activity_principal (session_kind, principal_id),
INDEX idx_system_session_activity_customer_context (customer_number_context)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci",
];
foreach ($queries as $sql) {
$db->query($sql);
}
self::ensureColumn(
'system_session_activity',
'customer_number_context',
'ALTER TABLE system_session_activity ADD COLUMN customer_number_context INT NULL AFTER principal_id'
);
self::ensureColumn(
'system_session_activity',
'device_type',
"ALTER TABLE system_session_activity ADD COLUMN device_type VARCHAR(16) NOT NULL DEFAULT 'unknown' AFTER customer_number_context"
);
self::ensureColumn(
'system_session_activity',
'user_agent',
'ALTER TABLE system_session_activity ADD COLUMN user_agent VARCHAR(1024) NULL AFTER device_type'
);
self::ensureColumn(
'system_session_activity',
'last_route',
'ALTER TABLE system_session_activity ADD COLUMN last_route VARCHAR(255) NULL AFTER user_agent'
);
self::ensureColumn(
'system_session_activity',
'first_seen_at',
'ALTER TABLE system_session_activity ADD COLUMN first_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER last_route'
);
self::ensureColumn(
'system_session_activity',
'last_seen_at',
'ALTER TABLE system_session_activity ADD COLUMN last_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER first_seen_at'
);
self::ensureColumn(
'system_session_activity',
'created_at',
'ALTER TABLE system_session_activity ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER last_seen_at'
);
self::ensureColumn(
'system_session_activity',
'updated_at',
'ALTER TABLE system_session_activity ADD COLUMN updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER created_at'
);
self::$initialized = true;
}
public static function tableHasColumn(string $table, string $column): bool
{
global $db;
$table = $db->escape_string($table);
$column = $db->escape_string($column);
$database = $db->escape_string($db->getDatabase());
$sql = "SELECT COUNT(*) AS c
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = '$database'
AND TABLE_NAME = '$table'
AND COLUMN_NAME = '$column'";
$result = $db->query($sql);
if (!$result) {
return false;
}
$row = $result->fetch_assoc();
return ((int)($row['c'] ?? 0)) > 0;
}
public static function ensureColumn(string $table, string $column, string $alterSql): void
{
global $db;
if (self::tableHasColumn($table, $column)) {
return;
}
$db->query($alterSql);
}
}
@@ -0,0 +1,266 @@
<?php
namespace classes;
use Exception;
use objects\subusers_o;
use objects\users_o;
class system_session_activity_tracker
{
public const ACTIVE_WINDOW_MINUTES = 15;
public const PRUNE_AFTER_DAYS = 30;
/**
* Deduplicate touches within a single request lifecycle.
*
* @var array<string, bool>
*/
private static array $touchedSessions = [];
public function __construct()
{
system_session_activity_schema_bootstrap::ensureTables();
}
public function touchUser(users_o $user, string $token): void
{
$customerNumber = null;
if (isset($user->customer_number)) {
try {
$customerNumber = (int)$user->customer_number->value();
} catch (Exception) {
$customerNumber = null;
}
}
$this->touch('user', (int)$user->id, $token, $customerNumber);
}
public function touchSubuser(subusers_o $subuser, string $token, ?int $customerNumberContext = null): void
{
$this->touch('subuser', (int)$subuser->id, $token, $customerNumberContext);
}
public function touch(string $sessionKind, int $principalId, string $token, ?int $customerNumberContext = null): void
{
global $db;
$token = trim($token);
if ($token === '' || $principalId <= 0) {
return;
}
$sessionHash = hash('sha256', $token);
if (isset(self::$touchedSessions[$sessionHash])) {
return;
}
self::$touchedSessions[$sessionHash] = true;
$headers = function_exists('getallheaders') ? (getallheaders() ?: []) : [];
$userAgent = trim((string)($headers['User-Agent'] ?? $headers['user-agent'] ?? ''));
$lastRoute = trim((string)($_SERVER['REQUEST_URI'] ?? ''));
if ($lastRoute !== '') {
$lastRoute = explode('?', $lastRoute)[0] ?? $lastRoute;
}
$sessionHashEscaped = $db->escape_string($sessionHash);
$sessionKindEscaped = $db->escape_string($sessionKind);
$deviceTypeEscaped = $db->escape_string(self::detectDeviceType($userAgent));
$userAgentEscaped = $db->escape_string(substr($userAgent, 0, 1024));
$lastRouteEscaped = $db->escape_string(substr($lastRoute, 0, 255));
$customerNumberSql = $customerNumberContext === null ? 'NULL' : (string)(int)$customerNumberContext;
$sql = "INSERT INTO system_session_activity (
session_hash,
session_kind,
principal_id,
customer_number_context,
device_type,
user_agent,
last_route,
first_seen_at,
last_seen_at
) VALUES (
'$sessionHashEscaped',
'$sessionKindEscaped',
" . (int)$principalId . ",
$customerNumberSql,
'$deviceTypeEscaped',
'$userAgentEscaped',
'$lastRouteEscaped',
NOW(),
NOW()
)
ON DUPLICATE KEY UPDATE
customer_number_context = VALUES(customer_number_context),
device_type = VALUES(device_type),
user_agent = VALUES(user_agent),
last_route = VALUES(last_route),
last_seen_at = VALUES(last_seen_at)";
$db->query($sql);
}
public function getSnapshot(int $limit = 50): array
{
global $db;
system_session_activity_schema_bootstrap::ensureTables();
$limit = max(1, min(200, $limit));
$cutoff = date('Y-m-d H:i:s', time() - (self::ACTIVE_WINDOW_MINUTES * 60));
$cutoffEscaped = $db->escape_string($cutoff);
$activeUsersResult = $db->query(
"SELECT COUNT(DISTINCT CONCAT(session_kind, ':', principal_id)) AS c
FROM system_session_activity
WHERE last_seen_at >= '$cutoffEscaped'"
);
$activeSessionsResult = $db->query(
"SELECT COUNT(*) AS c
FROM system_session_activity
WHERE last_seen_at >= '$cutoffEscaped'"
);
$recentRows = $db->query(
"SELECT
s.session_kind,
s.principal_id,
s.customer_number_context,
s.device_type,
s.user_agent,
s.last_route,
s.first_seen_at,
s.last_seen_at,
u.display_name AS user_display_name,
u.customer_number AS user_customer_number,
su.name AS subuser_name,
su.username AS subuser_username
FROM system_session_activity s
LEFT JOIN users u
ON s.session_kind = 'user'
AND u.id = s.principal_id
LEFT JOIN subusers su
ON s.session_kind = 'subuser'
AND su.id = s.principal_id
ORDER BY s.last_seen_at DESC
LIMIT $limit"
);
$recentSessions = [];
while ($row = $recentRows->fetch_assoc()) {
$isUser = ($row['session_kind'] ?? '') === 'user';
$displayName = $isUser
? trim((string)($row['user_display_name'] ?? ''))
: trim((string)($row['subuser_name'] ?? ''));
if ($displayName === '') {
if ($isUser && !empty($row['user_customer_number'])) {
$displayName = 'Customer ' . $row['user_customer_number'];
} elseif (!$isUser && !empty($row['subuser_username'])) {
$displayName = $row['subuser_username'];
} else {
$displayName = ucfirst((string)($row['session_kind'] ?? 'session')) . ' #' . (int)($row['principal_id'] ?? 0);
}
}
$contextLabel = null;
if ($isUser && !empty($row['user_customer_number'])) {
$contextLabel = 'Customer ' . $row['user_customer_number'];
} elseif (!empty($row['customer_number_context'])) {
$contextLabel = 'Customer ' . $row['customer_number_context'];
}
$recentSessions[] = [
'session_kind' => (string)($row['session_kind'] ?? 'unknown'),
'principal_id' => (int)($row['principal_id'] ?? 0),
'display_name' => $displayName,
'context_label' => $contextLabel,
'customer_number_context' => isset($row['customer_number_context']) ? (int)$row['customer_number_context'] : null,
'device_type' => (string)($row['device_type'] ?? 'unknown'),
'user_agent' => (string)($row['user_agent'] ?? ''),
'last_route' => (string)($row['last_route'] ?? ''),
'first_seen_at' => self::toIso8601($row['first_seen_at'] ?? null),
'last_seen_at' => self::toIso8601($row['last_seen_at'] ?? null),
'active' => self::isActive($row['last_seen_at'] ?? null),
];
}
$activeUsers = (int)(($activeUsersResult?->fetch_assoc()['c']) ?? 0);
$activeSessions = (int)(($activeSessionsResult?->fetch_assoc()['c']) ?? 0);
return [
'active_window_minutes' => self::ACTIVE_WINDOW_MINUTES,
'active_users' => $activeUsers,
'active_sessions' => $activeSessions,
'recent_sessions' => $recentSessions,
];
}
public function pruneOlderThanDays(int $days = self::PRUNE_AFTER_DAYS): int
{
global $db;
system_session_activity_schema_bootstrap::ensureTables();
$days = max(1, $days);
$cutoff = date('Y-m-d H:i:s', time() - ($days * 86400));
$cutoffEscaped = $db->escape_string($cutoff);
$db->query("DELETE FROM system_session_activity WHERE last_seen_at < '$cutoffEscaped'");
return (int)$db->conn()->affected_rows;
}
public static function detectDeviceType(string $userAgent): string
{
$userAgent = strtolower(trim($userAgent));
if ($userAgent === '') {
return 'unknown';
}
if (preg_match('/bot|crawler|spider|slurp|curl|wget|postman|insomnia/', $userAgent) === 1) {
return 'bot';
}
if (preg_match('/ipad|tablet|kindle|playbook|silk/', $userAgent) === 1) {
return 'tablet';
}
if (preg_match('/iphone|ipod|android.+mobile|windows phone|mobile/', $userAgent) === 1) {
return 'mobile';
}
if (preg_match('/macintosh|windows nt|linux|x11|cros/', $userAgent) === 1) {
return 'desktop';
}
return 'unknown';
}
public static function isActive(?string $lastSeenAt, int $windowMinutes = self::ACTIVE_WINDOW_MINUTES, ?int $referenceTimestamp = null): bool
{
if ($lastSeenAt === null || trim($lastSeenAt) === '') {
return false;
}
$lastSeenTimestamp = strtotime($lastSeenAt);
if ($lastSeenTimestamp === false) {
return false;
}
$referenceTimestamp = $referenceTimestamp ?? time();
return $lastSeenTimestamp >= ($referenceTimestamp - (max(1, $windowMinutes) * 60));
}
private static function toIso8601(?string $value): ?string
{
if ($value === null || trim($value) === '') {
return null;
}
$timestamp = strtotime($value);
if ($timestamp === false) {
return null;
}
return date('c', $timestamp);
}
}
+18
View File
@@ -129,6 +129,12 @@ $cron_tasks = [
'next_run' => 0,
'function' => 'GoalsProgressAlertsCron',
],
'PruneSystemSessionActivityCron' => [
'interval' => 86400, // 24 hours
'last_run' => 0,
'next_run' => 0,
'function' => 'PruneSystemSessionActivityCron',
],
];
function checkUnfulfilledBookings(): void
@@ -256,6 +262,18 @@ function EconomicTransferQueueCron(): void
}
}
function PruneSystemSessionActivityCron(): void
{
try {
$deleted = (new \classes\system_session_activity_tracker())->pruneOlderThanDays(30);
if ($deleted > 0) {
echo "[" . date('Y-m-d H:i:s') . "][CRON] Pruned $deleted stale system session activity rows\n";
}
} catch (Throwable $e) {
warn('PruneSystemSessionActivityCron failed: ' . $e->getMessage());
}
}
function SystemSearchCacheMaintenanceCron(): void
{
try {
@@ -0,0 +1,12 @@
<?php
namespace interfaces;
interface shelly_transport_i
{
public function requireModuleEnabled(): void;
public function requireValidSecretKey(): void;
public function sendPostRequest(string $endpoint, array $data, ?int $department_id = null): array|object|null;
}
@@ -45,7 +45,10 @@ class selfserve_lane implements selfserve_lane_i
selfserve_lane_invoice_t,
selfserve_lane_reservation_timer_t,
selfserve_lane_relay_controller_t,
selfserve_lane_log_t;
selfserve_lane_log_t {
selfserve_lane_relay_controller_t::createShellyTransport insteadof selfserve_lane_port_controller_t;
selfserve_lane_relay_controller_t::resolveShellyTransportDepartmentId insteadof selfserve_lane_port_controller_t;
}
/**
* @throws \Exception
@@ -86,4 +89,4 @@ class selfserve_lane implements selfserve_lane_i
{
$this->bypass_customer_number_validation = $bypass;
}
}
}
@@ -4,6 +4,8 @@ namespace modules\selfserve\traits;
require_once WD . '/modules/selfserve/helpers/selfserve_lane_port.php';
require_once WD . '/modules/selfserve/classes/selfserve_lane.php';
use classes\shelly_transport_resolver;
use interfaces\shelly_transport_i;
use modules\selfserve\helpers\selfserve_lane_port;
use modules\selfserve\helpers\selfserve_lane_log_action;
use modules\selfserve\helpers\selfserve_lane_state;
@@ -84,6 +86,39 @@ trait selfserve_lane_port_controller_t
protected function createShellySwitchDevice(): shelly_device_switch
{
return new shelly_device_switch();
return (new shelly_device_switch())->setRequestSender(
fn(array $parameters): array|object|null => $this
->createShellyTransport()
->sendPostRequest(
'/v2/devices/api/set/switch',
$parameters,
$this->resolveShellyTransportDepartmentId()
)
);
}
/**
* @throws \Exception
*/
protected function createShellyTransport(): shelly_transport_i
{
return (new shelly_transport_resolver())->resolveForDepartment($this->resolveShellyTransportDepartmentId());
}
/**
* @throws \Exception
*/
protected function resolveShellyTransportDepartmentId(): int
{
if (empty($this->department_lane)) {
throw new \Exception("Department lane object not found for lane ID {$this->id}");
}
$department_id = (int)$this->department_lane->department->value();
if ($department_id <= 0) {
throw new \Exception('Unable to resolve department for Shelly transport');
}
return $department_id;
}
}
@@ -5,6 +5,8 @@ require_once WD . '/modules/selfserve/helpers/selfserve_lane_relay.php';
require_once WD . '/modules/selfserve/classes/selfserve_lane.php';
use classes\shelly;
use classes\shelly_transport_resolver;
use interfaces\shelly_transport_i;
use modules\selfserve\helpers\selfserve_lane_relay;
use modules\selfserve\helpers\selfserve_lane_services;
use modules\selfserve\helpers\selfserve_lane_status;
@@ -680,10 +682,10 @@ trait selfserve_lane_relay_controller_t
*/
protected function sendShellyPost(string $endpoint, array $payload): array|object|null
{
$shelly = $this->createShellyClient();
$shelly->requireModuleEnabled();
$shelly->requireValidSecretKey();
return $shelly->sendPostRequest($endpoint, $payload);
$transport = $this->createShellyTransport();
$transport->requireModuleEnabled();
$transport->requireValidSecretKey();
return $transport->sendPostRequest($endpoint, $payload, $this->resolveShellyTransportDepartmentId());
}
protected function createShellyClient(): shelly
@@ -691,6 +693,28 @@ trait selfserve_lane_relay_controller_t
return new shelly();
}
protected function createShellyTransport(): shelly_transport_i
{
return (new shelly_transport_resolver())->resolveForDepartment($this->resolveShellyTransportDepartmentId());
}
/**
* @throws \Exception
*/
protected function resolveShellyTransportDepartmentId(): int
{
if (empty($this->department_lane)) {
throw new \Exception("Department lane object not found for lane ID {$this->id}");
}
$department_id = (int)$this->department_lane->department->value();
if ($department_id <= 0) {
throw new \Exception('Unable to resolve department for Shelly transport');
}
return $department_id;
}
protected function redisFacade(): mixed
{
return defined('redis') ? redis : null;
@@ -12,6 +12,9 @@ use Exception;
*/
class shelly_device_switch extends shelly_device_state
{
/** @var callable|null */
private $request_sender = null;
/**
* @var boolean $on
* @description The output state
@@ -55,6 +58,10 @@ class shelly_device_switch extends shelly_device_state
*/
protected function sendShellySwitchRequest(array $parameters): array|object|null
{
if (is_callable($this->request_sender)) {
$sender = $this->request_sender;
return $sender($parameters);
}
return (new shelly())->sendPostRequest('/v2/devices/api/set/switch', $parameters);
}
@@ -69,4 +76,10 @@ class shelly_device_switch extends shelly_device_state
];
return $this->sendShellySwitchRequest($parameters);
}
public function setRequestSender(callable $sender): self
{
$this->request_sender = $sender;
return $this;
}
}
@@ -0,0 +1,113 @@
<?php
namespace objects;
use classes\db;
use classes\department_daily_report_complaints_schema_bootstrap;
use classes\object_property;
use Exception;
use traits\db_object_t;
class department_daily_report_complaints_o extends db
{
use db_object_t;
public object_property $department_id;
public object_property $customer_number;
public object_property $description;
public object_property $created_by;
public object_property $created_at;
public function structure(): void
{
department_daily_report_complaints_schema_bootstrap::ensureTables();
$this->setTable('department_daily_report_complaints');
}
public function getObjectProperties(): void
{
$this->department_id = new object_property($this->table, $this->id, 'department_id', 'int', false);
$this->customer_number = new object_property($this->table, $this->id, 'customer_number', 'int', false);
$this->description = new object_property($this->table, $this->id, 'description', 'string', false);
$this->created_by = new object_property($this->table, $this->id, 'created_by', 'int', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'string', false);
}
public function objectChanged(): void
{
// No additional cache invalidation is needed for complaint rows in v1.
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'department_id' => (int)$this->department_id->value(),
'customer_number' => $this->customer_number->value() === null ? null : (int)$this->customer_number->value(),
'description' => (string)$this->description->value(),
'created_by' => (int)$this->created_by->value(),
'created_at' => (string)$this->created_at->value(),
];
}
/**
* @throws Exception
*/
public function addComplaint(int $department_id, ?int $customer_number, string $description, int $created_by): self
{
$description = trim($description);
if ($description === '') {
throw new Exception('Description is required');
}
$this->id = $this->add_object([
'department_id' => (int)$department_id,
'customer_number' => $customer_number === null ? null : (int)$customer_number,
'description' => $description,
'created_by' => (int)$created_by,
]);
$this->getObjectProperties();
$this->objectChanged();
return $this;
}
/**
* @param array<int> $department_ids
*/
public function countForDepartmentsInRange(array $department_ids, string $date, ?string $date_to = null): int
{
global $db;
$normalized_department_ids = array_values(array_unique(array_filter(
array_map('intval', $department_ids),
static fn (int $department_id): bool => $department_id > 0
)));
if ($normalized_department_ids === []) {
return 0;
}
if ($date_to === null) {
$date_to = $date;
}
$range_start = date('Y-m-d 00:00:00', strtotime($date));
$range_end = date('Y-m-d 23:59:59', strtotime($date_to));
$department_ids_sql = implode(',', $normalized_department_ids);
$range_start_sql = $db->escape_string($range_start);
$range_end_sql = $db->escape_string($range_end);
$result = $db->query(
"SELECT COUNT(*) AS total
FROM department_daily_report_complaints
WHERE department_id IN ($department_ids_sql)
AND created_at BETWEEN '$range_start_sql' AND '$range_end_sql'"
);
$row = $db->fetch_assoc($result);
return (int)($row['total'] ?? 0);
}
}
@@ -609,4 +609,231 @@ class department_daily_reports_o extends db
});
}
}
/**
* @param array<int|string> $department_ids
* @return array{quantity:int,products:int,earnings:int,washes:int,water_usage:int}
* @throws Exception
*/
public function getTransactionSummaryForDepartments(string $date, array $department_ids, string $date_to = null): array
{
global /** @var db $db */
$db;
$normalized_department_ids = $this->normalizeDepartmentIds($department_ids);
if ($normalized_department_ids === []) {
return [
'quantity' => 0,
'products' => 0,
'earnings' => 0,
'washes' => 0,
'water_usage' => 0,
];
}
[$date_start, $date_end] = $this->resolveDateRange($date, $date_to);
$department_ids_sql = implode(',', $normalized_department_ids);
$escaped_start = $db->escape_string($date_start);
$escaped_end = $db->escape_string($date_end);
$sql = "SELECT COUNT(DISTINCT o.id) AS quantity,
COALESCE(SUM(oi.quantity), 0) AS products,
COALESCE(SUM(oi.price * oi.quantity), 0) AS earnings,
COUNT(DISTINCT CASE WHEN p.is_wash = 1 THEN o.id END) AS washes
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
LEFT JOIN products p ON p.id = oi.product_id
WHERE o.department_id IN ($department_ids_sql)
AND o.created_at BETWEEN '$escaped_start' AND '$escaped_end'
AND o.deleted_at IS NULL
AND oi.deleted_at IS NULL";
$result = $db->query($sql);
$row = is_object($result) ? $result->fetch_assoc() : null;
return [
'quantity' => (int)($row['quantity'] ?? 0),
'products' => (int)($row['products'] ?? 0),
'earnings' => (int)round((float)($row['earnings'] ?? 0)),
'washes' => (int)($row['washes'] ?? 0),
'water_usage' => $this->getWaterUsageForDepartments($date, $normalized_department_ids, $date_to),
];
}
/**
* @param array<int|string> $department_ids
* @return array{completed:int,total:int}
* @throws Exception
*/
public function getBookingSummaryForDepartments(string $date, array $department_ids, string $date_to = null): array
{
global /** @var db $db */
$db;
$normalized_department_ids = $this->normalizeDepartmentIds($department_ids);
if ($normalized_department_ids === []) {
return [
'completed' => 0,
'total' => 0,
];
}
[$date_start, $date_end] = $this->resolveDateRange($date, $date_to);
$department_ids_sql = implode(',', $normalized_department_ids);
$escaped_start = $db->escape_string($date_start);
$escaped_end = $db->escape_string($date_end);
$sql = "SELECT COUNT(*) AS total,
COALESCE(SUM(CASE WHEN order_id IS NOT NULL THEN 1 ELSE 0 END), 0) AS completed
FROM order_bookings
WHERE department IN ($department_ids_sql)
AND datetime BETWEEN '$escaped_start' AND '$escaped_end'
AND deleted_at IS NULL";
$result = $db->query($sql);
$row = is_object($result) ? $result->fetch_assoc() : null;
return [
'completed' => (int)($row['completed'] ?? 0),
'total' => (int)($row['total'] ?? 0),
];
}
/**
* @param array<int|string> $department_ids
* @param array<int|string> $product_ids
* @return array<int,array{product_id:int,quantity:int,out_of:int}>
* @throws Exception
*/
public function getProductOverviewForDepartments(string $date, array $department_ids, array $product_ids, string $date_to = null): array
{
$normalized_department_ids = $this->normalizeDepartmentIds($department_ids);
$normalized_product_ids = $this->normalizeDepartmentIds($product_ids);
$overview = [];
foreach ($normalized_product_ids as $product_id) {
$quantity = 0;
$out_of = 0;
foreach ($normalized_department_ids as $department_id) {
$quantity += $this->getProductsSoldOnDate($date, $department_id, $product_id, $date_to);
$out_of += (int)(new departments_o())->getTotalMaxAddonsInDepartment(
[$product_id],
$date,
$date_to ?? $date,
$department_id
);
}
$overview[$product_id] = [
'product_id' => (int)$product_id,
'quantity' => (int)$quantity,
'out_of' => (int)$out_of,
];
}
return $overview;
}
/**
* @param array<int|string> $department_ids
* @return int
* @throws Exception
*/
public function getWaterUsageForDepartments(string $date, array $department_ids, string $date_to = null): int
{
$normalized_department_ids = $this->normalizeDepartmentIds($department_ids);
$water_usage = 0;
foreach ($normalized_department_ids as $department_id) {
$water_usage += $this->getTransactionsOnDateWaterUsage($date, $department_id, $date_to);
}
return $water_usage;
}
/**
* @param array<int|string> $department_ids
* @return array<int,array{id:int,department_id:int,created_at:string}>
* @throws Exception
*/
public function getWashTransactionsForDepartments(string $date, array $department_ids, string $date_to = null): array
{
global /** @var db $db */
$db;
$normalized_department_ids = $this->normalizeDepartmentIds($department_ids);
if ($normalized_department_ids === []) {
return [];
}
[$date_start, $date_end] = $this->resolveDateRange($date, $date_to);
$department_ids_sql = implode(',', $normalized_department_ids);
$escaped_start = $db->escape_string($date_start);
$escaped_end = $db->escape_string($date_end);
$sql = "SELECT DISTINCT o.id, o.department_id, o.created_at
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.department_id IN ($department_ids_sql)
AND o.created_at BETWEEN '$escaped_start' AND '$escaped_end'
AND o.deleted_at IS NULL
AND oi.deleted_at IS NULL
AND p.is_wash = 1
ORDER BY o.created_at ASC";
$result = $db->query($sql);
if (!is_object($result) || $result->num_rows === 0) {
return [];
}
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = [
'id' => (int)($row['id'] ?? 0),
'department_id' => (int)($row['department_id'] ?? 0),
'created_at' => (string)($row['created_at'] ?? ''),
];
}
return $rows;
}
/**
* @param array<int|string> $values
* @return array<int>
*/
private function normalizeDepartmentIds(array $values): array
{
$normalized = [];
foreach ($values as $value) {
$id = (int)$value;
if ($id > 0) {
$normalized[$id] = $id;
}
}
return array_values($normalized);
}
/**
* @return array{0:string,1:string}
* @throws Exception
*/
private function resolveDateRange(string $date, string $date_to = null): array
{
if ($date_to === null) {
$date_to = $date;
}
$date_start = date('Y-m-d 00:00:00', strtotime($date));
$date_end = date('Y-m-d 23:59:59', strtotime($date_to));
if ($date_start === false || $date_end === false) {
throw new Exception('Invalid date range provided');
}
return [$date_start, $date_end];
}
}
@@ -0,0 +1,61 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_audit_logs_o extends db
{
use db_object_t;
public object_property $gateway_id;
public object_property $department_id;
public object_property $action;
public object_property $actor_user_id;
public object_property $actor_type;
public object_property $severity;
public object_property $context_json;
public object_property $created_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_audit_logs');
}
public function getObjectProperties(): void
{
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
$this->department_id = new object_property($this->table, $this->id, 'department_id', 'int', false);
$this->action = new object_property($this->table, $this->id, 'action', 'string', false);
$this->actor_user_id = new object_property($this->table, $this->id, 'actor_user_id', 'int', false);
$this->actor_type = new object_property($this->table, $this->id, 'actor_type', 'string', false);
$this->severity = new object_property($this->table, $this->id, 'severity', 'string', false);
$this->context_json = new object_property($this->table, $this->id, 'context_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'gateway_id' => $this->gateway_id->value() === null ? null : (int)$this->gateway_id->value(),
'department_id' => $this->department_id->value() === null ? null : (int)$this->department_id->value(),
'action' => (string)$this->action->value(),
'actor_user_id' => $this->actor_user_id->value() === null ? null : (int)$this->actor_user_id->value(),
'actor_type' => (string)$this->actor_type->value(),
'severity' => (string)$this->severity->value(),
'context' => (array)($this->context_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
];
}
}
@@ -0,0 +1,65 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_claim_tokens_o extends db
{
use db_object_t;
public object_property $department_id;
public object_property $label;
public object_property $token_hash;
public object_property $created_by;
public object_property $expires_at;
public object_property $used_at;
public object_property $metadata_json;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_claim_tokens');
}
public function getObjectProperties(): void
{
$this->department_id = new object_property($this->table, $this->id, 'department_id', 'int', false);
$this->label = new object_property($this->table, $this->id, 'label', 'string', false);
$this->token_hash = new object_property($this->table, $this->id, 'token_hash', 'string', false);
$this->created_by = new object_property($this->table, $this->id, 'created_by', 'int', false);
$this->expires_at = new object_property($this->table, $this->id, 'expires_at', 'string', false);
$this->used_at = new object_property($this->table, $this->id, 'used_at', 'string', false);
$this->metadata_json = new object_property($this->table, $this->id, 'metadata_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'department_id' => (int)$this->department_id->value(),
'label' => $this->label->value() === null ? null : (string)$this->label->value(),
'created_by' => $this->created_by->value() === null ? null : (int)$this->created_by->value(),
'expires_at' => (string)$this->expires_at->value(),
'used_at' => $this->used_at->value() === null ? null : (string)$this->used_at->value(),
'metadata' => (array)($this->metadata_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
@@ -0,0 +1,75 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_command_jobs_o extends db
{
use db_object_t;
public object_property $gateway_id;
public object_property $command_type;
public object_property $status;
public object_property $request_json;
public object_property $response_json;
public object_property $correlation_id;
public object_property $requested_by;
public object_property $requested_at;
public object_property $completed_at;
public object_property $error_message;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_command_jobs');
}
public function getObjectProperties(): void
{
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
$this->command_type = new object_property($this->table, $this->id, 'command_type', 'string', false);
$this->status = new object_property($this->table, $this->id, 'status', 'string', false);
$this->request_json = new object_property($this->table, $this->id, 'request_json', 'json', false);
$this->response_json = new object_property($this->table, $this->id, 'response_json', 'json', false);
$this->correlation_id = new object_property($this->table, $this->id, 'correlation_id', 'string', false);
$this->requested_by = new object_property($this->table, $this->id, 'requested_by', 'int', false);
$this->requested_at = new object_property($this->table, $this->id, 'requested_at', 'string', false);
$this->completed_at = new object_property($this->table, $this->id, 'completed_at', 'string', false);
$this->error_message = new object_property($this->table, $this->id, 'error_message', 'text', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'gateway_id' => (int)$this->gateway_id->value(),
'command_type' => (string)$this->command_type->value(),
'status' => (string)$this->status->value(),
'request' => (array)($this->request_json->value() ?? []),
'response' => (array)($this->response_json->value() ?? []),
'correlation_id' => (string)$this->correlation_id->value(),
'requested_by' => $this->requested_by->value() === null ? null : (int)$this->requested_by->value(),
'requested_at' => (string)$this->requested_at->value(),
'completed_at' => $this->completed_at->value() === null ? null : (string)$this->completed_at->value(),
'error_message' => $this->error_message->value() === null ? null : (string)$this->error_message->value(),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
@@ -0,0 +1,72 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_device_inventory_o extends db
{
use db_object_t;
public object_property $gateway_id;
public object_property $device_id;
public object_property $local_ip;
public object_property $model;
public object_property $channel_count;
public object_property $capabilities_json;
public object_property $online;
public object_property $last_seen_at;
public object_property $metadata_json;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_device_inventory');
}
public function getObjectProperties(): void
{
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
$this->device_id = new object_property($this->table, $this->id, 'device_id', 'string', false);
$this->local_ip = new object_property($this->table, $this->id, 'local_ip', 'string', false);
$this->model = new object_property($this->table, $this->id, 'model', 'string', false);
$this->channel_count = new object_property($this->table, $this->id, 'channel_count', 'int', false);
$this->capabilities_json = new object_property($this->table, $this->id, 'capabilities_json', 'json', false);
$this->online = new object_property($this->table, $this->id, 'online', 'bool', false);
$this->last_seen_at = new object_property($this->table, $this->id, 'last_seen_at', 'string', false);
$this->metadata_json = new object_property($this->table, $this->id, 'metadata_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'gateway_id' => (int)$this->gateway_id->value(),
'device_id' => (string)$this->device_id->value(),
'local_ip' => $this->local_ip->value() === null ? null : (string)$this->local_ip->value(),
'model' => $this->model->value() === null ? null : (string)$this->model->value(),
'channel_count' => (int)$this->channel_count->value(),
'capabilities' => (array)($this->capabilities_json->value() ?? []),
'online' => (bool)$this->online->value(),
'last_seen_at' => $this->last_seen_at->value() === null ? null : (string)$this->last_seen_at->value(),
'metadata' => (array)($this->metadata_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
@@ -0,0 +1,75 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_relay_bindings_o extends db
{
use db_object_t;
public object_property $gateway_id;
public object_property $department_id;
public object_property $relay_id;
public object_property $device_id;
public object_property $local_ip;
public object_property $channel;
public object_property $binding_source;
public object_property $approved_by;
public object_property $approved_at;
public object_property $metadata_json;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_relay_bindings');
}
public function getObjectProperties(): void
{
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
$this->department_id = new object_property($this->table, $this->id, 'department_id', 'int', false);
$this->relay_id = new object_property($this->table, $this->id, 'relay_id', 'string', false);
$this->device_id = new object_property($this->table, $this->id, 'device_id', 'string', false);
$this->local_ip = new object_property($this->table, $this->id, 'local_ip', 'string', false);
$this->channel = new object_property($this->table, $this->id, 'channel', 'int', false);
$this->binding_source = new object_property($this->table, $this->id, 'binding_source', 'string', false);
$this->approved_by = new object_property($this->table, $this->id, 'approved_by', 'int', false);
$this->approved_at = new object_property($this->table, $this->id, 'approved_at', 'string', false);
$this->metadata_json = new object_property($this->table, $this->id, 'metadata_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'gateway_id' => (int)$this->gateway_id->value(),
'department_id' => (int)$this->department_id->value(),
'relay_id' => (string)$this->relay_id->value(),
'device_id' => (string)$this->device_id->value(),
'local_ip' => $this->local_ip->value() === null ? null : (string)$this->local_ip->value(),
'channel' => (int)$this->channel->value(),
'binding_source' => (string)$this->binding_source->value(),
'approved_by' => $this->approved_by->value() === null ? null : (int)$this->approved_by->value(),
'approved_at' => $this->approved_at->value() === null ? null : (string)$this->approved_at->value(),
'metadata' => (array)($this->metadata_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
@@ -0,0 +1,80 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_shell_sessions_o extends db
{
use db_object_t;
public object_property $gateway_id;
public object_property $reason;
public object_property $approval_status;
public object_property $session_token_hash;
public object_property $requested_by;
public object_property $approved_by;
public object_property $approved_at;
public object_property $expires_at;
public object_property $opened_at;
public object_property $closed_at;
public object_property $transcript_text;
public object_property $metadata_json;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_shell_sessions');
}
public function getObjectProperties(): void
{
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
$this->reason = new object_property($this->table, $this->id, 'reason', 'text', false);
$this->approval_status = new object_property($this->table, $this->id, 'approval_status', 'string', false);
$this->session_token_hash = new object_property($this->table, $this->id, 'session_token_hash', 'string', false);
$this->requested_by = new object_property($this->table, $this->id, 'requested_by', 'int', false);
$this->approved_by = new object_property($this->table, $this->id, 'approved_by', 'int', false);
$this->approved_at = new object_property($this->table, $this->id, 'approved_at', 'string', false);
$this->expires_at = new object_property($this->table, $this->id, 'expires_at', 'string', false);
$this->opened_at = new object_property($this->table, $this->id, 'opened_at', 'string', false);
$this->closed_at = new object_property($this->table, $this->id, 'closed_at', 'string', false);
$this->transcript_text = new object_property($this->table, $this->id, 'transcript_text', 'text', false);
$this->metadata_json = new object_property($this->table, $this->id, 'metadata_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'gateway_id' => (int)$this->gateway_id->value(),
'reason' => (string)$this->reason->value(),
'approval_status' => (string)$this->approval_status->value(),
'requested_by' => $this->requested_by->value() === null ? null : (int)$this->requested_by->value(),
'approved_by' => $this->approved_by->value() === null ? null : (int)$this->approved_by->value(),
'approved_at' => $this->approved_at->value() === null ? null : (string)$this->approved_at->value(),
'expires_at' => (string)$this->expires_at->value(),
'opened_at' => $this->opened_at->value() === null ? null : (string)$this->opened_at->value(),
'closed_at' => $this->closed_at->value() === null ? null : (string)$this->closed_at->value(),
'transcript_text' => $this->transcript_text->value() === null ? null : (string)$this->transcript_text->value(),
'metadata' => (array)($this->metadata_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
@@ -0,0 +1,72 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateway_update_jobs_o extends db
{
use db_object_t;
public object_property $gateway_id;
public object_property $target_version;
public object_property $release_channel;
public object_property $status;
public object_property $requested_by;
public object_property $requested_at;
public object_property $started_at;
public object_property $completed_at;
public object_property $result_json;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateway_update_jobs');
}
public function getObjectProperties(): void
{
$this->gateway_id = new object_property($this->table, $this->id, 'gateway_id', 'int', false);
$this->target_version = new object_property($this->table, $this->id, 'target_version', 'string', false);
$this->release_channel = new object_property($this->table, $this->id, 'release_channel', 'string', false);
$this->status = new object_property($this->table, $this->id, 'status', 'string', false);
$this->requested_by = new object_property($this->table, $this->id, 'requested_by', 'int', false);
$this->requested_at = new object_property($this->table, $this->id, 'requested_at', 'string', false);
$this->started_at = new object_property($this->table, $this->id, 'started_at', 'string', false);
$this->completed_at = new object_property($this->table, $this->id, 'completed_at', 'string', false);
$this->result_json = new object_property($this->table, $this->id, 'result_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'gateway_id' => (int)$this->gateway_id->value(),
'target_version' => (string)$this->target_version->value(),
'release_channel' => (string)$this->release_channel->value(),
'status' => (string)$this->status->value(),
'requested_by' => $this->requested_by->value() === null ? null : (int)$this->requested_by->value(),
'requested_at' => (string)$this->requested_at->value(),
'started_at' => $this->started_at->value() === null ? null : (string)$this->started_at->value(),
'completed_at' => $this->completed_at->value() === null ? null : (string)$this->completed_at->value(),
'result' => (array)($this->result_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
@@ -0,0 +1,86 @@
<?php
namespace objects;
use classes\db;
use classes\edge_gateway_schema_bootstrap;
use classes\object_property;
use traits\db_object_t;
class edge_gateways_o extends db
{
use db_object_t;
public object_property $department_id;
public object_property $label;
public object_property $hostname;
public object_property $agent_token_hash;
public object_property $status;
public object_property $transport_mode;
public object_property $release_channel;
public object_property $installed_version;
public object_property $target_version;
public object_property $last_heartbeat_at;
public object_property $last_seen_ip;
public object_property $discovery_status;
public object_property $is_primary;
public object_property $metadata_json;
public object_property $created_at;
public object_property $updated_at;
public object_property $deleted_at;
public function structure(): void
{
edge_gateway_schema_bootstrap::ensureTables();
$this->setTable('edge_gateways');
}
public function getObjectProperties(): void
{
$this->department_id = new object_property($this->table, $this->id, 'department_id', 'int', false);
$this->label = new object_property($this->table, $this->id, 'label', 'string', false);
$this->hostname = new object_property($this->table, $this->id, 'hostname', 'string', false);
$this->agent_token_hash = new object_property($this->table, $this->id, 'agent_token_hash', 'string', false);
$this->status = new object_property($this->table, $this->id, 'status', 'string', false);
$this->transport_mode = new object_property($this->table, $this->id, 'transport_mode', 'string', false);
$this->release_channel = new object_property($this->table, $this->id, 'release_channel', 'string', false);
$this->installed_version = new object_property($this->table, $this->id, 'installed_version', 'string', false);
$this->target_version = new object_property($this->table, $this->id, 'target_version', 'string', false);
$this->last_heartbeat_at = new object_property($this->table, $this->id, 'last_heartbeat_at', 'string', false);
$this->last_seen_ip = new object_property($this->table, $this->id, 'last_seen_ip', 'string', false);
$this->discovery_status = new object_property($this->table, $this->id, 'discovery_status', 'string', false);
$this->is_primary = new object_property($this->table, $this->id, 'is_primary', 'bool', false);
$this->metadata_json = new object_property($this->table, $this->id, 'metadata_json', 'json', false);
$this->created_at = new object_property($this->table, $this->id, 'created_at', 'timestamp', false);
$this->updated_at = new object_property($this->table, $this->id, 'updated_at', 'timestamp', false);
$this->deleted_at = new object_property($this->table, $this->id, 'deleted_at', 'timestamp', false);
}
public function objectChanged(): void
{
}
public function asArray(): array
{
$this->requireSelected();
return [
'id' => (int)$this->id,
'department_id' => (int)$this->department_id->value(),
'label' => (string)$this->label->value(),
'hostname' => $this->hostname->value() === null ? null : (string)$this->hostname->value(),
'status' => (string)$this->status->value(),
'transport_mode' => (string)$this->transport_mode->value(),
'release_channel' => (string)$this->release_channel->value(),
'installed_version' => $this->installed_version->value() === null ? null : (string)$this->installed_version->value(),
'target_version' => $this->target_version->value() === null ? null : (string)$this->target_version->value(),
'last_heartbeat_at' => $this->last_heartbeat_at->value() === null ? null : (string)$this->last_heartbeat_at->value(),
'last_seen_ip' => $this->last_seen_ip->value() === null ? null : (string)$this->last_seen_ip->value(),
'discovery_status' => (string)$this->discovery_status->value(),
'is_primary' => (bool)$this->is_primary->value(),
'metadata' => (array)($this->metadata_json->value() ?? []),
'created_at' => (string)$this->created_at->value(),
'updated_at' => $this->updated_at->value() === null ? null : (string)$this->updated_at->value(),
];
}
}
+512 -1
View File
@@ -9878,6 +9878,33 @@ paths:
'403':
$ref: '#/components/responses/Forbidden'
/superuser/system/status:
get:
tags:
- Superuser
summary: Aggregated system status snapshot
description: Returns a read-only snapshot of runtime health, dependency connectivity, module configuration/probe status, and active user session activity for the superuser dashboard.
operationId: getSuperuserSystemStatus
parameters:
- in: query
name: force
required: false
schema:
type: boolean
default: false
description: Bypass cached external module probes for this request.
responses:
'200':
description: System status snapshot returned successfully
content:
application/json:
schema:
$ref: '#/components/schemas/SuperuserSystemStatusResponse'
'401':
$ref: '#/components/responses/Unauthorized'
'403':
$ref: '#/components/responses/Forbidden'
# Configuration Endpoints
/economic/config:
get:
@@ -10888,6 +10915,34 @@ paths:
application/json:
schema: {}
/departments/daily-reports/overview:
get:
tags:
- Departments
summary: Get daily report overview
operationId: getDailyReportOverview
parameters:
- name: date
in: query
required: true
schema: {type: string}
- name: date_to
in: query
required: false
schema: {type: string}
- name: department_ids
in: query
required: true
schema:
type: string
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/DepartmentDailyReportOverviewResponse'
/departments/daily-reports/get:
get:
tags:
@@ -10910,6 +10965,26 @@ paths:
application/json:
schema: {}
/departments/daily-reports/complaints:
post:
tags:
- Departments
summary: Create daily report customer complaint
operationId: createDailyReportComplaint
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/DepartmentDailyReportComplaintCreateRequest'
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/DepartmentDailyReportComplaintResponse'
/departments/daily-reports/product-count:
get:
tags:
@@ -10964,7 +11039,36 @@ paths:
description: Success
content:
application/json:
schema: {}
schema:
$ref: '#/components/schemas/DepartmentDailyReportTransactionCountResponse'
/departments/daily-reports/outside-hours-trend:
get:
tags:
- Departments
summary: Get outside-hours trend for daily reports
operationId: getDailyReportOutsideHoursTrend
parameters:
- name: date
in: query
required: true
schema: {type: string}
- name: date_to
in: query
required: true
schema: {type: string}
- name: department_ids
in: query
required: true
schema:
type: string
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursTrendResponse'
/departments/daily-reports/bookings-count:
get:
@@ -11205,6 +11309,245 @@ components:
type: integer
description: HTTP status code
SuperuserSystemStatusResponse:
type: object
properties:
success:
type: boolean
data:
$ref: '#/components/schemas/SuperuserSystemStatusPayload'
meta:
type: object
additionalProperties: true
includes:
type: object
additionalProperties: true
required:
- success
- data
- meta
- includes
SuperuserSystemStatusPayload:
type: object
properties:
overall_status:
$ref: '#/components/schemas/SuperuserSystemStatusEnum'
generated_at:
type: string
format: date-time
refresh_after_seconds:
type: integer
runtime:
type: object
properties:
cpu:
$ref: '#/components/schemas/SuperuserRuntimeMetric'
memory:
$ref: '#/components/schemas/SuperuserRuntimeMetric'
disk:
$ref: '#/components/schemas/SuperuserRuntimeMetric'
dependencies:
type: object
properties:
database:
$ref: '#/components/schemas/SuperuserDependencyStatus'
redis:
$ref: '#/components/schemas/SuperuserDependencyStatus'
minio:
$ref: '#/components/schemas/SuperuserMinioDependencyStatus'
modules:
type: array
items:
$ref: '#/components/schemas/SuperuserModuleStatus'
sessions:
$ref: '#/components/schemas/SuperuserSessionStatus'
warnings:
type: array
items:
type: string
required:
- overall_status
- generated_at
- refresh_after_seconds
- runtime
- dependencies
- modules
- sessions
- warnings
SuperuserSystemStatusEnum:
type: string
enum: [ok, degraded, down]
SuperuserModuleStatusEnum:
type: string
enum: [disabled, not_configured, configured, ok, degraded, down]
SuperuserRuntimeMetric:
type: object
properties:
status:
$ref: '#/components/schemas/SuperuserSystemStatusEnum'
usage_percent:
type: number
format: float
nullable: true
used_bytes:
type: integer
nullable: true
free_bytes:
type: integer
nullable: true
total_bytes:
type: integer
nullable: true
path:
type: string
nullable: true
source:
type: string
nullable: true
checked_at:
type: string
format: date-time
SuperuserDependencyStatus:
type: object
properties:
status:
$ref: '#/components/schemas/SuperuserSystemStatusEnum'
latency_ms:
type: number
format: float
nullable: true
database:
oneOf:
- type: integer
- type: string
nullable: true
server_version:
type: string
nullable: true
http_status:
type: integer
nullable: true
checked_at:
type: string
format: date-time
error:
type: string
nullable: true
SuperuserMinioDependencyStatus:
type: object
properties:
status:
$ref: '#/components/schemas/SuperuserSystemStatusEnum'
latency_ms:
type: number
format: float
nullable: true
endpoint:
type: string
nullable: true
http_status:
type: integer
nullable: true
buckets:
type: array
items:
type: object
properties:
name:
type: string
status:
type: string
error:
type: string
nullable: true
checked_at:
type: string
format: date-time
error:
type: string
nullable: true
SuperuserModuleStatus:
type: object
properties:
key:
type: string
enabled:
type: boolean
configured:
type: boolean
probe_supported:
type: boolean
status:
$ref: '#/components/schemas/SuperuserModuleStatusEnum'
status_reason:
type: string
nullable: true
checked_at:
type: string
format: date-time
required:
- key
- enabled
- configured
- probe_supported
- status
- checked_at
SuperuserSessionStatus:
type: object
properties:
active_window_minutes:
type: integer
active_users:
type: integer
active_sessions:
type: integer
recent_sessions:
type: array
items:
type: object
properties:
session_kind:
type: string
principal_id:
type: integer
display_name:
type: string
context_label:
type: string
nullable: true
customer_number_context:
type: integer
nullable: true
device_type:
type: string
user_agent:
type: string
last_route:
type: string
first_seen_at:
type: string
format: date-time
nullable: true
last_seen_at:
type: string
format: date-time
nullable: true
active:
type: boolean
required:
- active_window_minutes
- active_users
- active_sessions
- recent_sessions
SystemSearchEntityType:
type: string
enum:
@@ -16516,4 +16859,172 @@ components:
additionalProperties: true
example: []
DepartmentDailyReportOutsideHoursBreakdown:
type: object
properties:
orders: { type: integer }
xlvask: { type: integer }
selfserve: { type: integer }
DepartmentDailyReportOutsideHoursSummary:
type: object
properties:
department_ids:
type: array
items: { type: integer }
date: { type: string }
date_to: { type: string }
total: { type: integer }
by_source:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursBreakdown'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportMetric:
type: object
properties:
state: { type: string }
value:
type: number
nullable: true
out_of:
type: number
nullable: true
message:
type: string
nullable: true
by_source:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursBreakdown'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportComplaintCreateRequest:
type: object
required: [department_id, description]
properties:
department_id: { type: integer }
customer_number:
type: integer
nullable: true
description:
type: string
minLength: 1
maxLength: 4000
DepartmentDailyReportComplaint:
type: object
properties:
id: { type: integer }
department_id: { type: integer }
customer_number:
type: integer
nullable: true
description: { type: string }
created_by: { type: integer }
created_at:
type: string
format: date-time
DepartmentDailyReportComplaintResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportComplaint'
DepartmentDailyReportProductTile:
type: object
properties:
product_id: { type: integer }
slug: { type: string }
title: { type: string }
state: { type: string }
value: { type: integer }
out_of: { type: integer }
DepartmentDailyReportOverviewPayload:
type: object
properties:
department_ids:
type: array
items: { type: integer }
date: { type: string }
date_to: { type: string }
metrics:
type: object
additionalProperties:
$ref: '#/components/schemas/DepartmentDailyReportMetric'
products:
type: array
items:
$ref: '#/components/schemas/DepartmentDailyReportProductTile'
DepartmentDailyReportOverviewResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportOverviewPayload'
DepartmentDailyReportTransactionCountPayload:
type: object
properties:
quantity: { type: integer }
products: { type: integer }
earnings: { type: integer }
washes: { type: integer }
water_usage: { type: integer }
date: { type: string }
date_to: { type: string }
department_id: { type: integer }
outside_hours:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursSummary'
DepartmentDailyReportTransactionCountResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportTransactionCountPayload'
DepartmentDailyReportOutsideHoursTrendPoint:
type: object
properties:
date: { type: string }
total: { type: integer }
by_source:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursBreakdown'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportOutsideHoursTrendPayload:
type: object
properties:
department_ids:
type: array
items: { type: integer }
date: { type: string }
date_to: { type: string }
points:
type: array
items:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursTrendPoint'
has_missing_opening_hours: { type: boolean }
missing_department_ids:
type: array
items: { type: integer }
DepartmentDailyReportOutsideHoursTrendResponse:
type: object
properties:
success: { type: boolean, example: true }
data:
$ref: '#/components/schemas/DepartmentDailyReportOutsideHoursTrendPayload'
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,295 @@
<?php
namespace routes;
use classes\authentication;
use classes\edge_gateway_manager;
use classes\response;
use objects\logs_o;
use traits\route_t;
class edgeGatewaysRoute
{
use route_t;
public function run(): void
{
$this->get('/edge-gateways', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
$departmentId = self::isParametersSet(['department_id']) ? (int)self::getParameter('department_id') : null;
if ($departmentId !== null && $departmentId > 0) {
$this->requireDepartmentAccess((int)$departmentId);
}
$response->success((new edge_gateway_manager())->listGateways($departmentId));
}, [
'modules_shelly_config' => 'Manage department edge gateways for local Shelly control',
]);
$this->get('/edge-gateways/{id}', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$gateway = (new edge_gateway_manager())->getGateway($gatewayId);
$this->requireDepartmentAccess((int)$gateway['department_id']);
$response->success($gateway);
}, [
'modules_shelly_config' => 'View department edge gateway detail',
]);
$this->post('/edge-gateways/install-token', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
self::requireParameters(['department_id']);
$departmentId = (int)self::getParameter('department_id');
self::requireParameterIntPositive($departmentId, 'department_id');
$this->requireDepartmentAccess($departmentId);
$user = (new authentication())->get_user();
$response->success(
(new edge_gateway_manager())->createInstallToken(
$departmentId,
self::isParametersSet(['label']) ? (string)self::getParameter('label') : null,
$user ? (int)$user->id : null
),
201
);
}, [
'modules_shelly_config' => 'Create a one-time Raspberry Pi edge gateway installer token',
]);
$this->post('/edge-gateways/{id}/discovery', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$manager = new edge_gateway_manager();
$gateway = $manager->getGateway($gatewayId);
$this->requireDepartmentAccess((int)$gateway['department_id']);
$user = (new authentication())->get_user();
$response->success($manager->queueDiscovery($gatewayId, $user ? (int)$user->id : null));
}, [
'modules_shelly_config' => 'Trigger a Shelly LAN discovery job on an edge gateway',
]);
$this->put('/edge-gateways/{id}/bindings', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
self::requireParameters(['bindings']);
self::requireType(self::getParameter('bindings'), self::TYPE_ARRAY());
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$manager = new edge_gateway_manager();
$gateway = $manager->getGateway($gatewayId);
$this->requireDepartmentAccess((int)$gateway['department_id']);
$user = (new authentication())->get_user();
$response->success($manager->setRelayBindings(
$gatewayId,
(array)self::getParameter('bindings'),
$user ? (int)$user->id : null
));
}, [
'modules_shelly_config' => 'Approve or override relay bindings for an edge gateway',
]);
$this->post('/edge-gateways/{id}/update-jobs', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
self::requireParameters(['target_version']);
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$manager = new edge_gateway_manager();
$gateway = $manager->getGateway($gatewayId);
$this->requireDepartmentAccess((int)$gateway['department_id']);
$user = (new authentication())->get_user();
$response->success($manager->queueUpdate(
$gatewayId,
(string)self::getParameter('target_version'),
self::isParametersSet(['release_channel']) ? (string)self::getParameter('release_channel') : edge_gateway_manager::DEFAULT_RELEASE_CHANNEL,
$user ? (int)$user->id : null
), 201);
}, [
'modules_shelly_config' => 'Queue an automatic edge gateway update',
]);
$this->post('/edge-gateways/{id}/shell-sessions', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
self::requireParameters(['reason']);
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$manager = new edge_gateway_manager();
$gateway = $manager->getGateway($gatewayId);
$this->requireDepartmentAccess((int)$gateway['department_id']);
self::requireMinLength('reason', 5);
$user = (new authentication())->get_user();
$response->success($manager->createShellSession(
$gatewayId,
(string)self::getParameter('reason'),
$user ? (int)$user->id : null
), 201);
}, [
'modules_shelly_config' => 'Approve a break-glass root shell on an edge gateway',
]);
$this->post('/edge-gateways/{id}/rotate-credentials', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$manager = new edge_gateway_manager();
$gateway = $manager->getGateway($gatewayId);
$this->requireDepartmentAccess((int)$gateway['department_id']);
$user = (new authentication())->get_user();
$response->success($manager->rotateGatewayCredentials($gatewayId, $user ? (int)$user->id : null));
}, [
'modules_shelly_config' => 'Rotate edge gateway agent credentials',
]);
$this->post('/departments/{id}/gateway-cutover', function () {
global /** @var response $response */ $response;
$this->requirePermission('modules_shelly_config');
$departmentId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($departmentId, 'id');
$this->requireDepartmentAccess($departmentId);
self::requireParameters(['transport_mode']);
$user = (new authentication())->get_user();
$response->success((new edge_gateway_manager())->setDepartmentTransportMode(
$departmentId,
(string)self::getParameter('transport_mode'),
$user ? (int)$user->id : null
));
}, [
'modules_shelly_config' => 'Cut a department over from Shelly cloud to local edge gateways',
]);
$this->get('/edge-agent/install.sh', fn() => $this->renderInstallScript());
$this->get('/edge-agent/artifacts/agent.mjs', fn() => $this->renderAgentArtifact('agent.mjs', 'application/javascript; charset=utf-8'));
$this->get('/edge-agent/artifacts/package.json', fn() => $this->renderAgentArtifact('package.json', 'application/json; charset=utf-8'));
$this->post('/edge-agent/claim', fn() => $this->handleAgentClaim());
$this->post('/edge-agent/gateways/{id}/heartbeat', fn() => $this->handleAgentHeartbeat());
$this->post('/edge-agent/internal/agent/auth', fn() => $this->handleInternalAgentAuth());
$this->post('/edge-agent/internal/shell/auth', fn() => $this->handleInternalShellAuth());
$this->post('/edge-agent/internal/shell-sessions/{id}/close', fn() => $this->handleInternalShellClose());
}
private function renderInstallScript(): void
{
$manager = new edge_gateway_manager();
$token = trim((string)$this->fromQuery('token'));
if ($token === '') {
http_response_code(400);
echo 'Missing token';
exit;
}
header('Content-Type: text/x-shellscript; charset=utf-8');
echo $manager->buildInstallScript($token);
exit;
}
private function renderAgentArtifact(string $fileName, string $contentType): void
{
$artifactPath = dirname(WD, 3) . '/services/edge-agent/dist/' . $fileName;
if (!is_file($artifactPath)) {
http_response_code(404);
echo 'Missing edge agent artifact';
exit;
}
header('Content-Type: ' . $contentType);
echo file_get_contents($artifactPath);
exit;
}
private function handleAgentClaim(): void
{
global /** @var response $response */ $response;
self::requireParameters(['token']);
$payload = self::getParametersAsArray();
$response->success((new edge_gateway_manager())->claimGateway(
(string)$payload['token'],
trim((string)($payload['hostname'] ?? gethostname() ?: 'unknown-gateway')),
isset($payload['installed_version']) ? (string)$payload['installed_version'] : null,
(array)($payload['metadata'] ?? [])
), 201);
}
private function handleAgentHeartbeat(): void
{
global /** @var response $response */ $response;
$gatewayId = (int)$this->fromRoute('id');
self::requireParameterIntPositive($gatewayId, 'id');
$payload = self::getParametersAsArray();
$token = trim((string)($payload['agent_token'] ?? $this->fromRequest('agent_token')));
if ($token === '') {
$response->error('Missing edge gateway agent token', 401);
}
$response->success((new edge_gateway_manager())->recordHeartbeat($gatewayId, $token, $payload));
}
private function handleInternalAgentAuth(): void
{
global /** @var response $response */ $response;
$this->requireInternalSecret();
self::requireParameters(['gatewayId', 'agentToken']);
$gateway = (new edge_gateway_manager())->authenticateGateway(
(int)self::getParameter('gatewayId'),
(string)self::getParameter('agentToken')
);
$response->success($gateway->asArray());
}
private function handleInternalShellAuth(): void
{
global /** @var response $response */ $response;
$this->requireInternalSecret();
self::requireParameters(['sessionToken']);
$response->success((new edge_gateway_manager())->validateShellSessionToken((string)self::getParameter('sessionToken')));
}
private function handleInternalShellClose(): void
{
global /** @var response $response */ $response;
$this->requireInternalSecret();
self::requireParameters(['sessionToken']);
$payload = self::getParametersAsArray();
$response->success((new edge_gateway_manager())->closeShellSession(
(string)$payload['sessionToken'],
(string)($payload['transcript'] ?? ''),
(string)($payload['closedReason'] ?? 'closed')
));
}
private function requireInternalSecret(): void
{
global /** @var response $response */ $response;
$expected = trim((string)(getenv('EDGE_INTERNAL_SECRET') ?: getenv('EDGE_BROKER_SHARED_SECRET') ?: ''));
if ($expected === '') {
return;
}
$headers = function_exists('getallheaders') ? getallheaders() : [];
$provided = trim((string)($headers['X-Edge-Internal-Secret'] ?? $headers['X-Edge-Broker-Secret'] ?? $this->fromRequest('internal_secret') ?? ''));
if ($provided === '' || !hash_equals($expected, $provided)) {
$response->error('Forbidden', 403);
}
}
}
@@ -0,0 +1,58 @@
<?php
namespace routes;
use classes\superuser_system_status_service;
use traits\route_t;
class superuserSystemStatusRoute
{
use route_t;
public function run(): void
{
$this->get('/superuser/system/status', function () {
global $response;
$this->requirePermission('superuser_system_status_view');
$force = $this->toBool($this->getParameter('force'), false);
$snapshot = (new superuser_system_status_service())->getSnapshot($force);
$response->success($snapshot);
}, [
'superuser_system_status_view' => 'View the aggregated superuser system status snapshot',
]);
$this->get('/superuser/system/database/status', function () {
global $response;
$this->requirePermission('superuser_system_status_view');
$snapshot = (new superuser_system_status_service())->getSnapshot(false);
$response->success([
'status' => $snapshot['dependencies']['database'] ?? null,
]);
}, [
'superuser_system_status_view' => 'View the aggregated superuser system status snapshot',
]);
}
private function toBool(mixed $value, bool $default): bool
{
if (is_bool($value)) {
return $value;
}
if ($value === null) {
return $default;
}
$normalized = strtolower(trim((string)$value));
if (in_array($normalized, ['1', 'true', 'yes', 'on'], true)) {
return true;
}
if (in_array($normalized, ['0', 'false', 'no', 'off'], true)) {
return false;
}
return $default;
}
}
@@ -0,0 +1,103 @@
<?php
use classes\db;
use classes\department_daily_report_complaints_schema_bootstrap;
use objects\department_daily_report_complaints_o;
function department_daily_report_complaints_integration_db(): db
{
if (!integration_enabled()) {
test()->markTestSkipped('Set RUN_INTEGRATION_TESTS=1 to run DB integration tests.');
}
$host = getenv('CONFIG_DB_HOST') ?: null;
$user = getenv('CONFIG_DB_USER') ?: null;
$password = getenv('CONFIG_DB_PASSWORD') ?: '';
$database = getenv('CONFIG_DB_DATABASE') ?: null;
$port = getenv('CONFIG_DB_PORT');
if (!$host || !$user || !$database) {
test()->markTestSkipped('Missing DB env vars: CONFIG_DB_HOST/CONFIG_DB_USER/CONFIG_DB_DATABASE.');
}
app_require('classes/db.php');
app_require('classes/department_daily_report_complaints_schema_bootstrap.php');
app_require('objects/department_daily_report_complaints_o.php');
$GLOBALS['response'] = new class {
public function error(string $message): void
{
throw new RuntimeException($message);
}
public function internal_server_error(string $message): void
{
throw new RuntimeException($message);
}
};
$db = new db([
'host' => $host,
'user' => $user,
'password' => $password,
'database' => $database,
'port' => $port !== false && $port !== null ? (int)$port : 3306,
]);
$db->connect();
$GLOBALS['db'] = $db;
department_daily_report_complaints_schema_bootstrap::ensureTables();
return $db;
}
it('counts complaint rows by department and created_at reporting range', function (): void {
$db = department_daily_report_complaints_integration_db();
$repository = new department_daily_report_complaints_o();
$suffix = (string)random_int(10000, 99999);
$department_ids = [];
$complaint_ids = [];
try {
$db->query("INSERT INTO departments (name, description) VALUES ('" . $db->escape_string('Complaints A ' . $suffix) . "', 'Integration A')");
$department_a_id = (int)$db->insert_id();
$department_ids[] = $department_a_id;
$db->query("INSERT INTO departments (name, description) VALUES ('" . $db->escape_string('Complaints B ' . $suffix) . "', 'Integration B')");
$department_b_id = (int)$db->insert_id();
$department_ids[] = $department_b_id;
$complaint_one = $repository->addComplaint($department_a_id, null, 'Complaint one', 1);
$complaint_two = (new department_daily_report_complaints_o())->addComplaint($department_a_id, 12345, 'Complaint two', 2);
$complaint_three = (new department_daily_report_complaints_o())->addComplaint($department_b_id, null, 'Complaint three', 3);
$complaint_ids = [
(int)$complaint_one->id,
(int)$complaint_two->id,
(int)$complaint_three->id,
];
$db->query("UPDATE department_daily_report_complaints SET created_at = '2026-03-23 08:00:00' WHERE id = " . (int)$complaint_one->id);
$db->query("UPDATE department_daily_report_complaints SET created_at = '2026-03-24 09:15:00' WHERE id = " . (int)$complaint_two->id);
$db->query("UPDATE department_daily_report_complaints SET created_at = '2026-03-24 10:30:00' WHERE id = " . (int)$complaint_three->id);
$single_department_day_count = $repository->countForDepartmentsInRange([$department_a_id], '2026-03-23', '2026-03-23');
$combined_range_count = $repository->countForDepartmentsInRange([$department_a_id, $department_b_id], '2026-03-23', '2026-03-24');
$second_day_count = $repository->countForDepartmentsInRange([$department_a_id, $department_b_id], '2026-03-24', '2026-03-24');
expect($single_department_day_count)->toBe(1);
expect($combined_range_count)->toBe(3);
expect($second_day_count)->toBe(2);
expect($complaint_two->asArray())->toMatchObject([
'department_id' => $department_a_id,
'customer_number' => 12345,
'description' => 'Complaint two',
'created_by' => 2,
]);
} finally {
if ($complaint_ids !== []) {
$db->query('DELETE FROM department_daily_report_complaints WHERE id IN (' . implode(',', array_map('intval', $complaint_ids)) . ')');
}
if ($department_ids !== []) {
$db->query('DELETE FROM departments WHERE id IN (' . implode(',', array_map('intval', $department_ids)) . ')');
}
$db->close();
}
});
@@ -0,0 +1,295 @@
<?php
use classes\db;
use classes\department_outside_hours_statistics_service;
function department_outside_hours_integration_db(): db
{
if (!integration_enabled()) {
test()->markTestSkipped('Set RUN_INTEGRATION_TESTS=1 to run DB integration tests.');
}
$host = getenv('CONFIG_DB_HOST') ?: null;
$user = getenv('CONFIG_DB_USER') ?: null;
$password = getenv('CONFIG_DB_PASSWORD') ?: '';
$database = getenv('CONFIG_DB_DATABASE') ?: null;
if (!$host || !$user || !$database) {
test()->markTestSkipped('Missing DB env vars: CONFIG_DB_HOST/CONFIG_DB_USER/CONFIG_DB_DATABASE.');
}
app_require('classes/db.php');
app_require('classes/department_outside_hours_statistics_service.php');
$GLOBALS['response'] = new class {
public function error(string $message): void
{
throw new RuntimeException($message);
}
public function internal_server_error(string $message): void
{
throw new RuntimeException($message);
}
};
$db = new db([
'host' => $host,
'user' => $user,
'password' => $password,
'database' => $database,
'port' => (int)(getenv('CONFIG_DB_PORT') ?: 3306),
]);
$db->connect();
$GLOBALS['db'] = $db;
department_outside_hours_prepare_tables($db);
return $db;
}
function department_outside_hours_prepare_tables(db $db): void
{
$db->query(
'CREATE TABLE IF NOT EXISTS departments (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT NULL
)'
);
$db->query(
'CREATE TABLE IF NOT EXISTS department_time_bookings_opening_hours (
id INT AUTO_INCREMENT PRIMARY KEY,
department INT NOT NULL,
monday_start TIME NULL,
monday_end TIME NULL,
tuesday_start TIME NULL,
tuesday_end TIME NULL
)'
);
$db->query(
'CREATE TABLE IF NOT EXISTS products (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
is_wash TINYINT(1) NOT NULL DEFAULT 0
)'
);
$db->query(
'CREATE TABLE IF NOT EXISTS orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
cashier_id INT NOT NULL,
reference VARCHAR(255) NULL,
notes TEXT NULL,
department_id INT NOT NULL,
reg_1 VARCHAR(64) NULL,
reg_2 VARCHAR(64) NULL,
reg_3 VARCHAR(64) NULL,
created_at DATETIME NOT NULL,
wash_id VARCHAR(255) NULL,
deleted_at DATETIME NULL
)'
);
$db->query(
'CREATE TABLE IF NOT EXISTS order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
reference VARCHAR(255) NULL,
notes TEXT NULL,
cashier_id INT NOT NULL,
price DECIMAL(10,2) NOT NULL DEFAULT 0,
quantity INT NOT NULL DEFAULT 1,
deleted_at DATETIME NULL
)'
);
$db->query(
'CREATE TABLE IF NOT EXISTS selfserve_wash_sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
lane_id INT NOT NULL,
department_id INT NOT NULL,
reg VARCHAR(64) NOT NULL,
status VARCHAR(64) NOT NULL,
allowed TINYINT(1) NOT NULL DEFAULT 0,
wash_started_at DATETIME NULL,
machine_start_triggered_at DATETIME NULL,
order_id INT NULL,
completed_at DATETIME NULL,
created_at DATETIME NULL,
deleted_at DATETIME NULL
)'
);
$db->query(
'CREATE TABLE IF NOT EXISTS xlvask_usage_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
WashId VARCHAR(255) NOT NULL,
CustomerId VARCHAR(255) NULL,
Customer VARCHAR(255) NULL,
VatNumber VARCHAR(255) NULL,
Location VARCHAR(255) NULL,
Hall VARCHAR(255) NULL,
HallId VARCHAR(255) NULL,
StartTime VARCHAR(64) NULL,
FinishTime VARCHAR(64) NULL,
RegistrationNumber VARCHAR(255) NULL,
VehicleType VARCHAR(255) NULL,
IdentificationType VARCHAR(255) NULL,
IdentificationId VARCHAR(255) NULL,
Info TEXT NULL,
Updated VARCHAR(64) NULL,
Prepaid VARCHAR(64) NULL,
FinishStatus VARCHAR(16) NULL,
CustomerGuid VARCHAR(255) NULL,
VehicleId VARCHAR(255) NULL,
WashItems TEXT NULL
)'
);
}
it('integrates orders, xlvask, and self-serve into one outside-hours summary with missing-hours diagnostics', function (): void {
$db = department_outside_hours_integration_db();
$service = new department_outside_hours_statistics_service();
$suffix = (string)random_int(10000, 99999);
$departmentIds = [];
$orderIds = [];
$sessionIds = [];
$washIds = [];
$productId = null;
$createWashOrder = function (int $departmentId, int $productId, string $reference, string $createdAt, ?string $washId = null) use ($db, &$orderIds): int {
$escapedReference = $db->escape_string($reference);
$escapedCreatedAt = $db->escape_string($createdAt);
$escapedWashId = $washId === null ? 'NULL' : "'" . $db->escape_string($washId) . "'";
$db->query(
"INSERT INTO orders (customer_id, cashier_id, reference, notes, department_id, reg_1, reg_2, reg_3, created_at, wash_id)
VALUES (1, 1, '$escapedReference', 'Integration test', $departmentId, 'ZZ$departmentId', '', '', '$escapedCreatedAt', $escapedWashId)"
);
$orderId = (int)$db->insert_id();
$orderIds[] = $orderId;
$db->query(
"INSERT INTO order_items (order_id, product_id, reference, notes, cashier_id, price, quantity)
VALUES ($orderId, $productId, '$escapedReference', 'Integration test', 1, 100, 1)"
);
return $orderId;
};
$insertSelfserveSession = function (int $departmentId, string $reg, string $startedAt, ?int $orderId = null) use ($db, &$sessionIds): int {
$escapedReg = $db->escape_string($reg);
$escapedStartedAt = $db->escape_string($startedAt);
$orderIdSql = $orderId === null ? 'NULL' : (string)$orderId;
$db->query(
"INSERT INTO selfserve_wash_sessions (lane_id, department_id, reg, status, allowed, wash_started_at, machine_start_triggered_at, order_id, completed_at, created_at)
VALUES (1, $departmentId, '$escapedReg', 'COMPLETED', 1, '$escapedStartedAt', '$escapedStartedAt', $orderIdSql, '$escapedStartedAt', '$escapedStartedAt')"
);
$sessionId = (int)$db->insert_id();
$sessionIds[] = $sessionId;
return $sessionId;
};
$insertXlvaskLog = function (int $departmentId, string $departmentName, string $washId, string $startTime) use ($db, &$washIds): void {
$escapedDepartmentName = $db->escape_string($departmentName);
$escapedWashId = $db->escape_string($washId);
$escapedStartTime = $db->escape_string($startTime);
$escapedFinishTime = $db->escape_string(substr($startTime, 0, 19) . '.000');
$hall = $db->escape_string($departmentName . '_1');
$washIds[] = $washId;
$db->query(
"INSERT INTO xlvask_usage_logs
(`WashId`, `CustomerId`, `Customer`, `VatNumber`, `Location`, `Hall`, `HallId`, `StartTime`, `FinishTime`,
`RegistrationNumber`, `VehicleType`, `IdentificationType`, `IdentificationId`, `Info`, `Updated`, `Prepaid`,
`FinishStatus`, `CustomerGuid`, `VehicleId`, `WashItems`)
VALUES
('$escapedWashId', '123456', 'Integration Customer', '12345678', '$escapedDepartmentName', '$hall', 'hall-$departmentId',
'$escapedStartTime', '$escapedFinishTime', 'ZZ$departmentId', 'Truck', 'LPR', 'ZZ$departmentId', 'ZZ$departmentId',
NULL, '', '1', 'guid-$departmentId', 'vehicle-$departmentId', '[]')"
);
};
try {
$departmentAName = 'DognDeptA' . $suffix;
$departmentBName = 'DognDeptB' . $suffix;
$db->query("INSERT INTO departments (name, description) VALUES ('" . $db->escape_string($departmentAName) . "', 'Integration A')");
$departmentAId = (int)$db->insert_id();
$departmentIds[] = $departmentAId;
$db->query("INSERT INTO departments (name, description) VALUES ('" . $db->escape_string($departmentBName) . "', 'Integration B')");
$departmentBId = (int)$db->insert_id();
$departmentIds[] = $departmentBId;
$db->query(
"INSERT INTO department_time_bookings_opening_hours
(department, monday_start, monday_end, tuesday_start, tuesday_end)
VALUES
($departmentAId, '08:00:00', '17:00:00', '08:00:00', '17:00:00')"
);
$db->query(
"INSERT INTO department_time_bookings_opening_hours
(department, tuesday_start, tuesday_end)
VALUES
($departmentBId, '08:00:00', '17:00:00')"
);
$db->query("INSERT INTO products (title, is_wash) VALUES ('Outside hours test wash $suffix', 1)");
$productId = (int)$db->insert_id();
$linkedXlvaskWashId = 'wash-linked-' . $suffix;
$unmatchedXlvaskWashId = 'wash-unmatched-' . $suffix;
$createWashOrder($departmentAId, $productId, 'plain-order-' . $suffix, '2026-03-23 05:30:00');
$linkedSelfserveOrderId = $createWashOrder($departmentAId, $productId, 'linked-selfserve-' . $suffix, '2026-03-23 06:00:00');
$createWashOrder($departmentAId, $productId, 'linked-xlvask-' . $suffix, '2026-03-23 06:10:00', $linkedXlvaskWashId);
$createWashOrder($departmentBId, $productId, 'missing-hours-' . $suffix, '2026-03-23 05:00:00');
$createWashOrder($departmentAId, $productId, 'inside-hours-' . $suffix, '2026-03-23 10:00:00');
$insertSelfserveSession($departmentAId, 'SELF' . $suffix, '2026-03-23 06:05:00', $linkedSelfserveOrderId);
$insertSelfserveSession($departmentAId, 'FREE' . $suffix, '2026-03-23 22:15:00');
$insertXlvaskLog($departmentAId, $departmentAName, $linkedXlvaskWashId, '2026-03-23T06:15:00.000');
$insertXlvaskLog($departmentAId, $departmentAName, $unmatchedXlvaskWashId, '2026-03-23T23:05:00.000');
$summary = $service->getSummary('2026-03-23', [$departmentAId, $departmentBId], '2026-03-23');
expect($summary['total'])->toBe(5);
expect($summary['by_source'])->toBe([
'orders' => 1,
'xlvask' => 2,
'selfserve' => 2,
]);
expect($summary['has_missing_opening_hours'])->toBeTrue();
expect($summary['missing_department_ids'])->toBe([$departmentBId]);
} finally {
if ($sessionIds !== []) {
$db->query('DELETE FROM selfserve_wash_sessions WHERE id IN (' . implode(',', array_map('intval', $sessionIds)) . ')');
}
if ($washIds !== []) {
$escapedWashIds = implode(',', array_map(static fn(string $washId): string => "'" . $db->escape_string($washId) . "'", $washIds));
$db->query("DELETE FROM xlvask_usage_logs WHERE WashId IN ($escapedWashIds)");
}
if ($orderIds !== []) {
$orderIdsSql = implode(',', array_map('intval', $orderIds));
$db->query("DELETE FROM order_items WHERE order_id IN ($orderIdsSql)");
$db->query("DELETE FROM orders WHERE id IN ($orderIdsSql)");
}
if ($productId !== null) {
$db->query('DELETE FROM products WHERE id = ' . (int)$productId);
}
if ($departmentIds !== []) {
$departmentIdsSql = implode(',', array_map('intval', $departmentIds));
$db->query("DELETE FROM department_time_bookings_opening_hours WHERE department IN ($departmentIdsSql)");
$db->query("DELETE FROM departments WHERE id IN ($departmentIdsSql)");
}
$db->close();
}
});
@@ -0,0 +1,70 @@
<?php
app_require('config.php');
app_require('classes/db.php');
app_require('classes/redis.php');
app_require('classes/superuser_system_status_service.php');
use classes\db;
use classes\redis;
use classes\superuser_system_status_service;
beforeEach(function (): void {
if (!integration_enabled()) {
test()->markTestSkipped('Set RUN_INTEGRATION_TESTS=1 to run system status integration tests.');
}
$GLOBALS['response'] = new class {
public function internal_server_error(string $message): void
{
throw new RuntimeException($message);
}
};
$GLOBALS['db'] = new db($GLOBALS['CONFIG_DB']);
$GLOBALS['db']->connect();
if (!defined('redis') && isset($GLOBALS['REDIS_CONFIG']) && is_array($GLOBALS['REDIS_CONFIG'])) {
try {
define('redis', (new redis())->connect());
} catch (Throwable) {
// Redis-specific expectations are skipped below when the client is unavailable.
}
}
});
afterEach(function (): void {
if (isset($GLOBALS['db']) && $GLOBALS['db'] instanceof db) {
$GLOBALS['db']->close();
}
});
it('can probe the configured database in integration mode', function (): void {
$probe = (new superuser_system_status_service())->probeDatabase();
expect($probe['status'])->toBe('ok');
expect($probe['database'])->not->toBe('');
expect($probe)->toHaveKey('server_version');
});
it('can probe redis in integration mode when configured', function (): void {
if (!isset($GLOBALS['REDIS_CONFIG']) || !defined('redis')) {
test()->markTestSkipped('Redis is not configured in this integration environment.');
}
$probe = (new superuser_system_status_service())->probeRedis();
expect(in_array($probe['status'], ['ok', 'degraded', 'down'], true))->toBeTrue();
expect($probe)->toHaveKey('checked_at');
});
it('can probe minio in integration mode when configured', function (): void {
if (!isset($GLOBALS['MINIO']) || !is_array($GLOBALS['MINIO']) || empty($GLOBALS['MINIO']['endpoint'])) {
test()->markTestSkipped('MinIO is not configured in this integration environment.');
}
$probe = (new superuser_system_status_service())->probeMinio();
expect(in_array($probe['status'], ['ok', 'degraded', 'down'], true))->toBeTrue();
expect($probe)->toHaveKey('buckets');
});
@@ -0,0 +1,38 @@
<?php
function department_daily_reports_complaints_openapi_content_or_skip(): string
{
$candidates = [WD . '/openapi.yaml'];
for ($depth = 1; $depth <= 8; $depth++) {
$candidates[] = dirname(WD, $depth) . DIRECTORY_SEPARATOR . 'openapi.yaml';
}
$cwd = getcwd();
if (is_string($cwd) && $cwd !== '') {
$candidates[] = $cwd . DIRECTORY_SEPARATOR . 'openapi.yaml';
$candidates[] = dirname($cwd) . DIRECTORY_SEPARATOR . 'openapi.yaml';
}
foreach (array_values(array_unique($candidates)) as $candidate) {
if (!is_file($candidate)) {
continue;
}
$content = file_get_contents($candidate);
if ($content !== false) {
return $content;
}
}
test()->markTestSkipped('openapi.yaml is not mounted in this test container.');
}
it('documents the daily report complaints create endpoint and complaint schemas in openapi', function (): void {
$content = department_daily_reports_complaints_openapi_content_or_skip();
expect($content)->toContain('/departments/daily-reports/complaints:');
expect($content)->toContain('operationId: createDailyReportComplaint');
expect($content)->toContain('DepartmentDailyReportComplaintCreateRequest:');
expect($content)->toContain('DepartmentDailyReportComplaint:');
expect($content)->toContain('customer_number:');
});
@@ -0,0 +1,13 @@
<?php
it('wires complaint creation through a dedicated route with validation and customer checks', function (): void {
$content = (string)file_get_contents(app_path('routes/departmentDailyReportsRoute.php'));
expect($content)->toContain('/departments/daily-reports/complaints');
expect($content)->toContain("requirePermission('create_department_daily_report_complaints')");
expect($content)->toContain("requireDepartmentAccess((int)self::getParameter('department_id'))");
expect($content)->toContain("getOrImportCustomerByCustomerNumber");
expect($content)->toContain("Description is required");
expect($content)->toContain("dailyReportComplaintsRepository()->addComplaint");
expect($content)->toContain("countForDepartmentsInRange");
});
@@ -0,0 +1,14 @@
<?php
it('documents outside-hours summary and trend schemas in openapi', function (): void {
$content = department_daily_reports_openapi_content_or_skip();
expect($content)->toContain('/departments/daily-reports/transaction-count:');
expect($content)->toContain('/departments/daily-reports/outside-hours-trend:');
expect($content)->toContain('DepartmentDailyReportTransactionCountResponse:');
expect($content)->toContain('DepartmentDailyReportOutsideHoursSummary:');
expect($content)->toContain('DepartmentDailyReportOutsideHoursTrendResponse:');
expect($content)->toContain('DepartmentDailyReportOutsideHoursBreakdown:');
expect($content)->toContain('outside_hours:');
expect($content)->toContain('missing_department_ids:');
});
@@ -0,0 +1,25 @@
<?php
it('wires outside-hours summary and trend endpoints through the dedicated statistics service', function (): void {
$routeFile = app_path('routes/departmentDailyReportsRoute.php');
$content = file_get_contents($routeFile);
expect($content)->not->toBeFalse();
expect($content)->toContain('use classes\department_outside_hours_statistics_service;');
expect($content)->toContain('/departments/daily-reports/transaction-count');
expect($content)->toContain("'outside_hours' => \$outside_hours_service->getSummary(");
expect($content)->toContain("/departments/daily-reports/outside-hours-trend");
expect($content)->toContain("outsideHoursStatisticsService()->getTrend(");
expect($content)->toContain("normalizeDepartmentIdsParameter(self::getParameter('department_ids'))");
expect($content)->toContain('protected function outsideHoursStatisticsService(): department_outside_hours_statistics_service');
});
it('initializes the outside-hours statistics service before building the transaction-count summary payload', function (): void {
$routeFile = app_path('routes/departmentDailyReportsRoute.php');
$content = file_get_contents($routeFile);
expect($content)->not->toBeFalse();
expect($content)->toMatch(
"/\\/departments\\/daily-reports\\/transaction-count'.*?\\\$outside_hours_service = \\\$this->outsideHoursStatisticsService\\(\\);.*?'outside_hours' => \\\$outside_hours_service->getSummary\\(/s"
);
});
@@ -0,0 +1,39 @@
<?php
function department_daily_reports_openapi_content_or_skip(): string
{
$candidates = [WD . '/openapi.yaml'];
for ($depth = 1; $depth <= 8; $depth++) {
$candidates[] = dirname(WD, $depth) . DIRECTORY_SEPARATOR . 'openapi.yaml';
}
$cwd = getcwd();
if (is_string($cwd) && $cwd !== '') {
$candidates[] = $cwd . DIRECTORY_SEPARATOR . 'openapi.yaml';
$candidates[] = dirname($cwd) . DIRECTORY_SEPARATOR . 'openapi.yaml';
}
foreach (array_values(array_unique($candidates)) as $candidate) {
if (!is_file($candidate)) {
continue;
}
$content = file_get_contents($candidate);
if ($content !== false) {
return $content;
}
}
test()->markTestSkipped('openapi.yaml is not mounted in this test container.');
}
it('documents the daily report overview endpoint and reusable schemas in openapi', function (): void {
$content = department_daily_reports_openapi_content_or_skip();
expect($content)->toContain('/departments/daily-reports/overview:');
expect($content)->toContain('operationId: getDailyReportOverview');
expect($content)->toContain('DepartmentDailyReportOverviewResponse:');
expect($content)->toContain('DepartmentDailyReportMetric:');
expect($content)->toContain('DepartmentDailyReportProductTile:');
expect($content)->toContain('- name: department_ids');
});
@@ -0,0 +1,321 @@
<?php
app_require('classes/department_outside_hours_statistics_service.php');
app_require('routes/departmentDailyReportsRoute.php');
use classes\department_outside_hours_statistics_service;
use routes\departmentDailyReportsRoute;
function department_daily_reports_route_invoke_private(object $route, string $method, array $args = []): mixed
{
$reflection = new ReflectionClass(departmentDailyReportsRoute::class);
$target = $reflection->getMethod($method);
$target->setAccessible(true);
return $target->invokeArgs($route, $args);
}
final class FakeDailyReportValue
{
public function __construct(private readonly mixed $current)
{
}
public function value(): mixed
{
return $this->current;
}
}
final class FakeDailyReportVariables
{
public function __construct(private readonly array $values = [])
{
}
public function getVariable(string $key): mixed
{
return $this->values[$key] ?? null;
}
}
final class FakeDailyReportRepository
{
public array $transaction_summary = [
'quantity' => 0,
'products' => 0,
'earnings' => 0,
'washes' => 0,
'water_usage' => 0,
];
public array $booking_summary = [
'completed' => 0,
'total' => 0,
];
public array $product_overview = [];
public array $wash_transactions = [];
public function getTransactionSummaryForDepartments(string $date, array $department_ids, string $date_to = null): array
{
return $this->transaction_summary;
}
public function getBookingSummaryForDepartments(string $date, array $department_ids, string $date_to = null): array
{
return $this->booking_summary;
}
public function getProductOverviewForDepartments(string $date, array $department_ids, array $product_ids, string $date_to = null): array
{
return $this->product_overview;
}
public function getWashTransactionsForDepartments(string $date, array $department_ids, string $date_to = null): array
{
return $this->wash_transactions;
}
}
final class FakeDailyReportComplaintsRepository
{
public int $count = 0;
public function countForDepartmentsInRange(array $department_ids, string $date, ?string $date_to = null): int
{
return $this->count;
}
}
final class FakeOutsideHoursStatisticsService extends department_outside_hours_statistics_service
{
public array $summary = [
'total' => 0,
'by_source' => [
'orders' => 0,
'xlvask' => 0,
'selfserve' => 0,
],
'has_missing_opening_hours' => false,
'missing_department_ids' => [],
];
public function __construct()
{
}
public function getSummary(string $date, array|int|string $department_ids, ?string $date_to = null): array
{
return [
'department_ids' => is_array($department_ids) ? array_values(array_map('intval', $department_ids)) : [(int)$department_ids],
'date' => $date,
'date_to' => $date_to ?? $date,
...$this->summary,
];
}
}
final class DepartmentDailyReportsOverviewRouteDouble extends departmentDailyReportsRoute
{
public object $repository;
public object $complaints_repository;
public array $opening_hours = [];
public array $departments = [];
public array $workfeed_departments = [];
public array $workfeed_shifts = [];
public department_outside_hours_statistics_service $outside_hours_service;
protected function dailyReportRepository(): object
{
return $this->repository;
}
protected function dailyReportComplaintsRepository(): object
{
return $this->complaints_repository;
}
protected function fetchOpeningHoursByDepartmentId(array $department_ids): array
{
return $this->opening_hours;
}
protected function fetchDepartmentsByIds(array $department_ids): array
{
return $this->departments;
}
protected function fetchWorkfeedDepartments(): array
{
return $this->workfeed_departments;
}
protected function fetchWorkfeedShifts(\DateTime $query_start, \DateTime $range_end_exclusive): array
{
return $this->workfeed_shifts;
}
protected function outsideHoursStatisticsService(): department_outside_hours_statistics_service
{
return $this->outside_hours_service;
}
}
function fake_daily_report_department(int $id, string $name, array $variables = []): object
{
return (object)[
'id' => $id,
'name' => new FakeDailyReportValue($name),
'variables' => new FakeDailyReportVariables($variables),
];
}
beforeEach(function (): void {
$_SERVER['REQUEST_URI'] = '/departments/daily-reports/overview';
});
it('builds the overview payload from batched repository data with deterministic tile states', function (): void {
$repository = new FakeDailyReportRepository();
$complaints_repository = new FakeDailyReportComplaintsRepository();
$repository->transaction_summary = [
'quantity' => 12,
'products' => 37,
'earnings' => 4900,
'washes' => 14,
'water_usage' => 56,
];
$repository->booking_summary = [
'completed' => 9,
'total' => 11,
];
$repository->product_overview = [
24 => ['product_id' => 24, 'quantity' => 3, 'out_of' => 14],
25 => ['product_id' => 25, 'quantity' => 2, 'out_of' => 14],
];
$complaints_repository->count = 4;
$route = new DepartmentDailyReportsOverviewRouteDouble();
$route->repository = $repository;
$route->complaints_repository = $complaints_repository;
$route->outside_hours_service = new FakeOutsideHoursStatisticsService();
$route->outside_hours_service->summary = [
'total' => 1,
'by_source' => [
'orders' => 0,
'xlvask' => 1,
'selfserve' => 0,
],
'has_missing_opening_hours' => false,
'missing_department_ids' => [],
];
$route->departments = [
fake_daily_report_department(1, 'North', ['workfeed_department_id' => 'dep_1']),
fake_daily_report_department(2, 'South', ['workfeed_department_id' => 'dep_2']),
];
$route->workfeed_shifts = [
(object)[
'departmentID' => 'dep_1',
'start' => '2026-03-23T09:00:00+00:00',
'end' => '2026-03-23T17:00:00+00:00',
'approval' => (object)['originalEnd' => '2026-03-23T17:30:00+00:00'],
],
(object)[
'departmentID' => 'dep_2',
'start' => '2026-03-23T10:00:00+00:00',
'end' => '2026-03-23T18:00:00+00:00',
'approval' => null,
'updateTime' => '2026-03-23T18:15:00+00:00',
],
];
$overview = department_daily_reports_route_invoke_private($route, 'buildDailyReportOverview', [[1, 2], '2026-03-23', '2026-03-23']);
expect($overview['department_ids'])->toBe([1, 2]);
expect($overview['metrics']['transactions']['value'])->toBe(12);
expect($overview['metrics']['bookings']['value'])->toBe(9);
expect($overview['metrics']['bookings']['out_of'])->toBe(11);
expect($overview['metrics']['night_washes']['state'])->toBe('ready');
expect($overview['metrics']['night_washes']['value'])->toBe(1);
expect($overview['metrics']['night_washes']['by_source'])->toBe([
'orders' => 0,
'xlvask' => 1,
'selfserve' => 0,
]);
expect($overview['metrics']['overtime']['state'])->toBe('ready');
expect($overview['metrics']['overtime']['value'])->toBe(0.75);
expect($overview['metrics']['complaints']['state'])->toBe('ready');
expect($overview['metrics']['complaints']['value'])->toBe(4);
expect(count($overview['products']))->toBe(6);
expect($overview['products'][0]['slug'])->toBe('spot-free-lastbil');
expect($overview['products'][0]['title'])->toBe('Spot Free (Lastbil)');
expect($overview['products'][0]['value'])->toBe(3);
expect($overview['products'][1]['title'])->toBe('Fælg flex pr. enhed');
expect($overview['products'][1]['value'])->toBe(2);
expect(array_column($overview['products'], 'title'))->toBe([
'Spot Free (Lastbil)',
'Fælg flex pr. enhed',
'Ekstraordinær pr. 10 min inkl. kemi',
'Højglans - Voksforsegling pr. enhed',
'Undervognsskyl pr. enhed',
'Tillæg for Specialsæbe - DD',
]);
});
it('marks overtime unavailable when not every selected department can be mapped to workfeed', function (): void {
$repository = new FakeDailyReportRepository();
$route = new DepartmentDailyReportsOverviewRouteDouble();
$route->repository = $repository;
$route->complaints_repository = new FakeDailyReportComplaintsRepository();
$route->outside_hours_service = new FakeOutsideHoursStatisticsService();
$route->departments = [
fake_daily_report_department(1, 'North', ['workfeed_department_id' => 'dep_1']),
fake_daily_report_department(2, 'South'),
];
$overview = department_daily_reports_route_invoke_private($route, 'buildDailyReportOverview', [[1, 2], '2026-03-23', '2026-03-23']);
expect($overview['metrics']['overtime']['state'])->toBe('unavailable');
expect($overview['metrics']['overtime']['message'])->toContain('Workfeed');
});
it('normalizes department id input from csv strings and nested values', function (): void {
$route = new DepartmentDailyReportsOverviewRouteDouble();
$route->repository = new FakeDailyReportRepository();
$route->complaints_repository = new FakeDailyReportComplaintsRepository();
$route->outside_hours_service = new FakeOutsideHoursStatisticsService();
$normalized = department_daily_reports_route_invoke_private($route, 'normalizeDepartmentIdsParameter', [['1, 2', [3, '4'], 2]]);
expect($normalized)->toBe([1, 2, 3, 4]);
});
it('limits overtime counting to the selected reporting range', function (): void {
$route = new DepartmentDailyReportsOverviewRouteDouble();
$route->repository = new FakeDailyReportRepository();
$route->complaints_repository = new FakeDailyReportComplaintsRepository();
$route->outside_hours_service = new FakeOutsideHoursStatisticsService();
$hours = department_daily_reports_route_invoke_private($route, 'calculateShiftOvertimeHoursInRange', [[
'start' => '2026-03-22T20:00:00+00:00',
'end' => '2026-03-22T23:45:00+00:00',
'approval' => (object)['originalEnd' => '2026-03-23T00:30:00+00:00'],
], new \DateTime('2026-03-23T00:00:00+00:00'), new \DateTime('2026-03-24T00:00:00+00:00')]);
expect($hours)->toBe(0.5);
});
it('wires the overview route to batched repository methods and overview path', function (): void {
$routeContent = (string)file_get_contents(app_path('routes/departmentDailyReportsRoute.php'));
$objectContent = (string)file_get_contents(app_path('objects/department_daily_reports_o.php'));
expect($routeContent)->toContain('/departments/daily-reports/overview');
expect($routeContent)->toContain('/departments/daily-reports/complaints');
expect($routeContent)->toContain('outsideHoursStatisticsService');
expect($routeContent)->toContain('dailyReportComplaintsRepository');
expect($routeContent)->toContain('/departments/daily-reports/outside-hours-trend');
expect($routeContent)->toContain('getTransactionSummaryForDepartments');
expect($routeContent)->toContain('normalizeDepartmentIdsParameter');
expect($objectContent)->toContain('public function getBookingSummaryForDepartments');
});
@@ -0,0 +1,182 @@
<?php
app_require('classes/department_outside_hours_statistics_service.php');
use classes\department_outside_hours_statistics_service;
function outside_hours_weekday_hours(int $department_id, array $overrides = []): array
{
return array_merge([
'department' => $department_id,
'monday_start' => '08:00:00',
'monday_end' => '17:00:00',
'tuesday_start' => '08:00:00',
'tuesday_end' => '17:00:00',
'wednesday_start' => '08:00:00',
'wednesday_end' => '17:00:00',
'thursday_start' => '08:00:00',
'thursday_end' => '17:00:00',
'friday_start' => '08:00:00',
'friday_end' => '17:00:00',
'saturday_start' => '08:00:00',
'saturday_end' => '17:00:00',
'sunday_start' => '08:00:00',
'sunday_end' => '17:00:00',
], $overrides);
}
it('counts only outside-hours washes and flags missing opening hours without counting them as closed', function (): void {
$service = new department_outside_hours_statistics_service();
$summary = $service->summarizeCandidates(
[
[
'source' => 'orders',
'dedupe_key' => 'order:100',
'department_id' => 1,
'start_at' => '2026-03-23 06:45:00',
],
[
'source' => 'orders',
'dedupe_key' => 'order:101',
'department_id' => 1,
'start_at' => '2026-03-23 10:15:00',
],
[
'source' => 'orders',
'dedupe_key' => 'order:102',
'department_id' => 2,
'start_at' => '2026-03-23 05:30:00',
],
],
[
1 => outside_hours_weekday_hours(1),
2 => outside_hours_weekday_hours(2, [
'monday_start' => null,
'monday_end' => null,
]),
],
[1, 2],
'2026-03-23',
'2026-03-23'
);
expect($summary['total'])->toBe(1);
expect($summary['by_source'])->toBe([
'orders' => 1,
'xlvask' => 0,
'selfserve' => 0,
]);
expect($summary['has_missing_opening_hours'])->toBeTrue();
expect($summary['missing_department_ids'])->toBe([2]);
});
it('deduplicates linked washes with self-serve first, then xlvask, then orders', function (): void {
$service = new department_outside_hours_statistics_service();
$deduplicated = $service->deduplicateCandidates([
[
'source' => 'orders',
'dedupe_key' => 'order:200',
'department_id' => 1,
'start_at' => '2026-03-23 06:00:00',
],
[
'source' => 'xlvask',
'dedupe_key' => 'order:200',
'department_id' => 1,
'start_at' => '2026-03-23 06:05:00',
],
[
'source' => 'selfserve',
'dedupe_key' => 'order:200',
'department_id' => 1,
'start_at' => '2026-03-23 06:10:00',
],
[
'source' => 'xlvask',
'dedupe_key' => 'xlvask:wash-standalone',
'department_id' => 1,
'start_at' => '2026-03-23 23:00:00',
],
[
'source' => 'selfserve',
'dedupe_key' => 'selfserve:501',
'department_id' => 1,
'start_at' => '2026-03-23 23:30:00',
],
]);
expect($deduplicated)->toHaveCount(3);
expect($deduplicated[0]['source'])->toBe('selfserve');
expect($deduplicated[0]['dedupe_key'])->toBe('order:200');
expect(array_column($deduplicated, 'source'))->toBe([
'selfserve',
'xlvask',
'selfserve',
]);
});
it('builds daily trend points with per-day missing-hours diagnostics', function (): void {
$service = new department_outside_hours_statistics_service();
$trend = $service->buildTrendFromCandidates(
[
[
'source' => 'orders',
'dedupe_key' => 'order:301',
'department_id' => 1,
'start_at' => '2026-03-23 06:00:00',
],
[
'source' => 'orders',
'dedupe_key' => 'order:302',
'department_id' => 2,
'start_at' => '2026-03-23 05:00:00',
],
[
'source' => 'selfserve',
'dedupe_key' => 'selfserve:701',
'department_id' => 2,
'start_at' => '2026-03-24 05:15:00',
],
],
[
1 => outside_hours_weekday_hours(1),
2 => outside_hours_weekday_hours(2, [
'monday_start' => null,
'monday_end' => null,
]),
],
[1, 2],
'2026-03-23',
'2026-03-24'
);
expect($trend['has_missing_opening_hours'])->toBeTrue();
expect($trend['missing_department_ids'])->toBe([2]);
expect($trend['points'])->toBe([
[
'date' => '2026-03-23',
'total' => 1,
'by_source' => [
'orders' => 1,
'xlvask' => 0,
'selfserve' => 0,
],
'has_missing_opening_hours' => true,
'missing_department_ids' => [2],
],
[
'date' => '2026-03-24',
'total' => 1,
'by_source' => [
'orders' => 0,
'xlvask' => 0,
'selfserve' => 1,
],
'has_missing_opening_hours' => false,
'missing_department_ids' => [],
],
]);
});
@@ -0,0 +1,91 @@
<?php
app_require('classes/edge_gateway_manager.php');
use classes\edge_gateway_manager;
class EdgeGatewayManagerUrlHarness extends edge_gateway_manager
{
public function __construct()
{
}
}
function with_edge_gateway_server_state(array $server, callable $callback): void
{
$originalServer = $_SERVER;
$originalPublicApiUrl = getenv('EDGE_PUBLIC_API_URL');
$_SERVER = $server;
try {
$callback();
} finally {
$_SERVER = $originalServer;
if ($originalPublicApiUrl === false) {
putenv('EDGE_PUBLIC_API_URL');
} else {
putenv('EDGE_PUBLIC_API_URL=' . $originalPublicApiUrl);
}
}
}
it('builds install script urls with forwarded https scheme when proxied', function (): void {
with_edge_gateway_server_state([
'HTTP_HOST' => 'api.truckwash.io:4433',
'HTTP_X_FORWARDED_PROTO' => 'https',
], function (): void {
$manager = new EdgeGatewayManagerUrlHarness();
$script = $manager->buildInstallScript('abc123');
expect($manager->getApiBaseUrl())->toBe('https://api.truckwash.io:4433');
expect($manager->buildInstallScriptUrl('abc123'))->toBe('https://api.truckwash.io:4433/edge-agent/install.sh?token=abc123');
expect($manager->buildInstallCommand('abc123'))->toContain("https://api.truckwash.io:4433/edge-agent/install.sh?token=abc123");
expect($script)->toContain('mkdir -p "$INSTALL_DIR"');
expect($script)->toContain('curl -fsSL "https://api.truckwash.io:4433/edge-agent/artifacts/package.json" -o "$INSTALL_DIR/package.json"');
expect($script)->toContain('curl -fsSL "https://api.truckwash.io:4433/edge-agent/artifacts/agent.mjs" -o "$INSTALL_DIR/agent.mjs"');
expect($script)->toContain('"apiUrl":"https://api.truckwash.io:4433"');
expect($script)->toContain('"brokerUrl":"https://api.truckwash.io:4300"');
expect($script)->not->toContain('Undefined variable $INSTALL_DIR');
});
});
it('appends forwarded ports when the forwarded host omits them', function (): void {
with_edge_gateway_server_state([
'HTTP_X_FORWARDED_PROTO' => 'https',
'HTTP_X_FORWARDED_HOST' => 'api.truckwash.io',
'HTTP_X_FORWARDED_PORT' => '4433',
], function (): void {
$manager = new EdgeGatewayManagerUrlHarness();
expect($manager->getApiBaseUrl())->toBe('https://api.truckwash.io:4433');
});
});
it('infers https for the staging api host when only the https port is present', function (): void {
with_edge_gateway_server_state([
'HTTP_HOST' => 'api.truckwash.io:4433',
'SERVER_PORT' => '4433',
], function (): void {
$manager = new EdgeGatewayManagerUrlHarness();
$script = $manager->buildInstallScript('port-only');
expect($manager->getApiBaseUrl())->toBe('https://api.truckwash.io:4433');
expect($script)->toContain('"apiUrl":"https://api.truckwash.io:4433"');
expect($script)->toContain('"brokerUrl":"https://api.truckwash.io:4300"');
});
});
it('prefers EDGE_PUBLIC_API_URL when explicitly configured', function (): void {
with_edge_gateway_server_state([
'HTTP_HOST' => 'localhost',
'HTTP_X_FORWARDED_PROTO' => 'http',
], function (): void {
putenv('EDGE_PUBLIC_API_URL=https://edge.example.test/api');
$manager = new EdgeGatewayManagerUrlHarness();
expect($manager->getApiBaseUrl())->toBe('https://edge.example.test/api');
expect($manager->buildInstallScriptUrl('token-1'))->toBe('https://edge.example.test/api/edge-agent/install.sh?token=token-1');
});
});
@@ -0,0 +1,29 @@
<?php
it('registers the edge gateway management REST endpoints', function (): void {
$route = file_get_contents(app_path('routes/edgeGatewaysRoute.php'));
expect($route)->not->toBeFalse();
expect($route)->toContain("'/edge-gateways'");
expect($route)->toContain("'/edge-gateways/{id}'");
expect($route)->toContain("'/edge-gateways/install-token'");
expect($route)->toContain("'/edge-gateways/{id}/discovery'");
expect($route)->toContain("'/edge-gateways/{id}/bindings'");
expect($route)->toContain("'/edge-gateways/{id}/update-jobs'");
expect($route)->toContain("'/edge-gateways/{id}/shell-sessions'");
expect($route)->toContain("'/edge-gateways/{id}/rotate-credentials'");
expect($route)->toContain("'/departments/{id}/gateway-cutover'");
});
it('registers public installer, claim, heartbeat, and internal broker auth endpoints', function (): void {
$route = file_get_contents(app_path('routes/edgeGatewaysRoute.php'));
expect($route)->toContain("'/edge-agent/install.sh'");
expect($route)->toContain("'/edge-agent/artifacts/agent.mjs'");
expect($route)->toContain("'/edge-agent/artifacts/package.json'");
expect($route)->toContain("'/edge-agent/claim'");
expect($route)->toContain("'/edge-agent/gateways/{id}/heartbeat'");
expect($route)->toContain("'/edge-agent/internal/agent/auth'");
expect($route)->toContain("'/edge-agent/internal/shell/auth'");
expect($route)->toContain("'/edge-agent/internal/shell-sessions/{id}/close'");
});
@@ -0,0 +1,24 @@
<?php
it('defines the edge gateway runtime schema bootstrap tables', function (): void {
$bootstrapContent = file_get_contents(app_path('classes/edge_gateway_schema_bootstrap.php'));
expect($bootstrapContent)->not->toBeFalse();
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateways');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_claim_tokens');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_device_inventory');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_relay_bindings');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_command_jobs');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_update_jobs');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_shell_sessions');
expect($bootstrapContent)->toContain('CREATE TABLE IF NOT EXISTS edge_gateway_audit_logs');
});
it('stores edge gateway heartbeats, bindings, and shell transcript data', function (): void {
$bootstrapContent = file_get_contents(app_path('classes/edge_gateway_schema_bootstrap.php'));
expect($bootstrapContent)->toContain('last_heartbeat_at DATETIME NULL');
expect($bootstrapContent)->toContain('channel INT NOT NULL DEFAULT 0');
expect($bootstrapContent)->toContain('transcript_text LONGTEXT NULL');
expect($bootstrapContent)->toContain('context_json JSON NULL');
});
@@ -0,0 +1,83 @@
<?php
app_require('classes/edge_gateway_manager.php');
app_require('classes/gateway_shelly_transport.php');
use classes\edge_gateway_manager;
use classes\gateway_shelly_transport;
class GatewayShellyTransportManagerFake extends edge_gateway_manager
{
/** @var array<int,array<string,mixed>> */
public array $statusCalls = [];
/** @var array<int,array<string,mixed>> */
public array $switchCalls = [];
public function __construct()
{
}
public function dispatchRelayStatus(int $departmentId, string $logicalRelayId): array
{
$this->statusCalls[] = [
'department_id' => $departmentId,
'relay_id' => $logicalRelayId,
];
return [
'online' => true,
'on' => $logicalRelayId === 'relay-machine',
'raw' => ['source' => 'status'],
];
}
public function dispatchRelaySwitch(int $departmentId, string $logicalRelayId, bool $on): array
{
$this->switchCalls[] = [
'department_id' => $departmentId,
'relay_id' => $logicalRelayId,
'on' => $on,
];
return [
'online' => true,
'on' => $on,
'raw' => ['source' => 'switch'],
];
}
}
it('maps gateway relay status responses into the Shelly cloud payload shape', function (): void {
$manager = new GatewayShellyTransportManagerFake();
$transport = new gateway_shelly_transport($manager);
$result = $transport->sendPostRequest('/v2/devices/api/get', [
'ids' => ['relay-machine', 'relay-cleaner'],
], 17);
expect($manager->statusCalls)->toBe([
['department_id' => 17, 'relay_id' => 'relay-machine'],
['department_id' => 17, 'relay_id' => 'relay-cleaner'],
]);
expect($result)->toBeArray();
expect($result[0]['id'])->toBe('relay-machine');
expect($result[0]['status']['switch:0']['output'])->toBeTrue();
expect($result[1]['status']['switch:0']['output'])->toBeFalse();
});
it('maps gateway relay switch responses into the Shelly cloud payload shape', function (): void {
$manager = new GatewayShellyTransportManagerFake();
$transport = new gateway_shelly_transport($manager);
$result = $transport->sendPostRequest('/v2/devices/api/set/switch', [
'id' => 'relay-machine',
'on' => false,
], 17);
expect($manager->switchCalls)->toBe([
['department_id' => 17, 'relay_id' => 'relay-machine', 'on' => false],
]);
expect($result)->toBeArray();
expect($result[0]['id'])->toBe('relay-machine');
expect($result[0]['status']['switch:0']['output'])->toBeFalse();
});
@@ -0,0 +1,43 @@
<?php
$candidates = [WD . '/openapi.yaml'];
for ($depth = 1; $depth <= 6; $depth++) {
$candidates[] = dirname(WD, $depth) . DIRECTORY_SEPARATOR . 'openapi.yaml';
}
$cwd = getcwd() ?: '';
if ($cwd !== '') {
$candidates[] = $cwd . DIRECTORY_SEPARATOR . 'openapi.yaml';
$candidates[] = dirname($cwd) . DIRECTORY_SEPARATOR . 'openapi.yaml';
}
$openApiPath = null;
foreach (array_unique($candidates) as $candidate) {
if (is_file($candidate)) {
$openApiPath = $candidate;
break;
}
}
if ($openApiPath === null) {
test()->markTestSkipped('openapi.yaml is not available in this runtime environment.');
}
it('documents the superuser system status snapshot endpoint in openapi', function () use ($openApiPath): void {
$content = file_get_contents($openApiPath);
expect($content)->toContain('/superuser/system/status:');
expect($content)->toContain('operationId: getSuperuserSystemStatus');
expect($content)->toContain('SuperuserSystemStatusResponse');
expect($content)->toContain('Bypass cached external module probes');
});
it('defines the reusable system status schemas and enums', function () use ($openApiPath): void {
$content = file_get_contents($openApiPath);
expect($content)->toContain('SuperuserSystemStatusPayload:');
expect($content)->toContain('SuperuserSystemStatusEnum:');
expect($content)->toContain('enum: [ok, degraded, down]');
expect($content)->toContain('SuperuserModuleStatusEnum:');
expect($content)->toContain('enum: [disabled, not_configured, configured, ok, degraded, down]');
expect($content)->toContain('SuperuserSessionStatus:');
});
@@ -0,0 +1,19 @@
<?php
it('registers the aggregated superuser system status endpoint and permission', function (): void {
$content = file_get_contents(app_path('routes/superuserSystemStatusRoute.php'));
expect($content)->not->toBeFalse();
expect($content)->toContain('/superuser/system/status');
expect($content)->toContain("requirePermission('superuser_system_status_view')");
expect($content)->toContain('new superuser_system_status_service()');
expect($content)->toContain("'force'");
});
it('keeps the legacy database status endpoint wired through the shared snapshot service', function (): void {
$content = file_get_contents(app_path('routes/superuserSystemStatusRoute.php'));
expect($content)->not->toBeFalse();
expect($content)->toContain('/superuser/system/database/status');
expect($content)->toContain("dependencies']['database'");
});
@@ -0,0 +1,680 @@
<?php
app_require('classes/superuser_system_status_service.php');
use classes\superuser_system_status_service;
function system_status_module_value(mixed $value, string $type = 'string'): array
{
return [
'raw' => $value,
'parsed' => $value,
'type' => $type,
];
}
class SuperuserSystemStatusServiceProbeDouble extends superuser_system_status_service
{
public array $httpProbeCalls = [];
public array $nextHttpProbeResult = [
'status' => 'ok',
'status_reason' => 'Probe connectivity confirmed.',
'checked_at' => '2026-04-08T17:00:00+00:00',
'latency_ms' => 12.34,
'http_status' => 200,
];
public ?array $moduleConfigRowsOverride = null;
public bool $backupStoreValidationShouldFail = false;
public string $backupStoreFailureMessage = 'Backup bucket is missing.';
public bool $selfserveBootstrapShouldFail = false;
public string $selfserveBootstrapFailureMessage = 'Schema bootstrap failed.';
public bool $selfserveMinuteProductExistsValue = true;
public ?int $selfserveMinuteProductCheckedId = null;
public ?string $shellyProbeDeviceId = null;
public function collectModulesPublic(bool $force, array &$warnings): array
{
return $this->collectModules($force, $warnings);
}
public function classifyHttpProbeResultPublic(array $httpResponse, string $label): array
{
return $this->classifyHttpProbeResult($httpResponse, $label);
}
public function evaluateRecaptchaProbeResponsePublic(array $httpResponse, string $label): array
{
return $this->evaluateRecaptchaProbeResponse($httpResponse, $label);
}
public function probeEconomicModulePublic(array $config): array
{
return $this->probeEconomicModule($config);
}
public function probeRecaptchaModulePublic(array $config): array
{
return $this->probeRecaptchaModule($config);
}
public function probeEmailModulePublic(array $config): array
{
return $this->probeEmailModule($config);
}
public function probeBackupsModulePublic(array $config): array
{
return $this->probeBackupsModule($config);
}
public function probeMotorApiModulePublic(array $config): array
{
return $this->probeMotorApiModule($config);
}
public function probeFxRatesApiModulePublic(array $config): array
{
return $this->probeFxRatesApiModule($config);
}
public function probeWeatherApiModulePublic(array $config): array
{
return $this->probeWeatherApiModule($config);
}
public function probeWorkfeedModulePublic(array $config): array
{
return $this->probeWorkfeedModule($config);
}
public function probeGatewayApiModulePublic(array $config): array
{
return $this->probeGatewayApiModule($config);
}
public function probeXlVaskModulePublic(array $config): array
{
return $this->probeXlVaskModule($config);
}
public function probeLimbleModulePublic(array $config): array
{
return $this->probeLimbleModule($config);
}
public function probeLicensePlateRecognizerModulePublic(array $config): array
{
return $this->probeLicensePlateRecognizerModule($config);
}
public function probeShellyModulePublic(array $config): array
{
return $this->probeShellyModule($config);
}
public function probeSelfserveModulePublic(array $config): array
{
return $this->probeSelfserveModule($config);
}
public function probeBirdModulePublic(array $config): array
{
return $this->probeBirdModule($config);
}
protected function performHttpProbe(
string $url,
array $headers,
string $label,
?string $basicAuth = null,
string $method = 'GET',
?string $body = null,
?callable $responseEvaluator = null
): array {
$this->httpProbeCalls[] = [
'url' => $url,
'headers' => $headers,
'label' => $label,
'basic_auth' => $basicAuth,
'method' => $method,
'body' => $body,
'has_evaluator' => $responseEvaluator !== null,
];
return $this->nextHttpProbeResult;
}
protected function loadModuleConfigRows(array $moduleNames): array
{
if ($this->moduleConfigRowsOverride !== null) {
return $this->moduleConfigRowsOverride;
}
return parent::loadModuleConfigRows($moduleNames);
}
protected function validateBackupsStore(): void
{
if ($this->backupStoreValidationShouldFail) {
throw new RuntimeException($this->backupStoreFailureMessage);
}
}
protected function bootstrapSelfserveSchema(): void
{
if ($this->selfserveBootstrapShouldFail) {
throw new RuntimeException($this->selfserveBootstrapFailureMessage);
}
}
protected function selfserveMinuteProductExists(int $productId): bool
{
$this->selfserveMinuteProductCheckedId = $productId;
return $this->selfserveMinuteProductExistsValue;
}
protected function findShellyProbeDeviceId(): ?string
{
return $this->shellyProbeDeviceId;
}
}
beforeEach(function (): void {
$this->previousEconomicApi = $GLOBALS['ECONOMIC_API'] ?? null;
});
afterEach(function (): void {
if ($this->previousEconomicApi === null) {
unset($GLOBALS['ECONOMIC_API']);
return;
}
$GLOBALS['ECONOMIC_API'] = $this->previousEconomicApi;
});
it('reduces overall status using down and degraded precedence', function (): void {
expect(superuser_system_status_service::reduceOverallStatus(['ok', 'configured']))->toBe('ok');
expect(superuser_system_status_service::reduceOverallStatus(['ok', 'not_configured']))->toBe('degraded');
expect(superuser_system_status_service::reduceOverallStatus(['configured', 'down']))->toBe('down');
});
it('classifies runtime usage percentages consistently', function (): void {
expect(superuser_system_status_service::statusFromUsagePercent(42.5))->toBe('ok');
expect(superuser_system_status_service::statusFromUsagePercent(91.0, 90, 99))->toBe('degraded');
expect(superuser_system_status_service::statusFromUsagePercent(99.1, 90, 99))->toBe('down');
expect(superuser_system_status_service::statusFromUsagePercent(null))->toBe('down');
});
it('reuses cached module probes only when the ttl is still valid and force is false', function (): void {
$freshCachedProbe = ['checked_at' => date('c', time() - 15)];
$expiredCachedProbe = ['checked_at' => date('c', time() - 120)];
expect(superuser_system_status_service::shouldReuseCachedModuleProbe($freshCachedProbe, false, time(), 60))->toBeTrue();
expect(superuser_system_status_service::shouldReuseCachedModuleProbe($freshCachedProbe, true, time(), 60))->toBeFalse();
expect(superuser_system_status_service::shouldReuseCachedModuleProbe($expiredCachedProbe, false, time(), 60))->toBeFalse();
});
it('classifies authenticated http probe responses conservatively', function (int $httpStatus, string $expectedStatus, string $reasonFragment): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$result = $service->classifyHttpProbeResultPublic([
'checked_at' => '2026-04-08T17:10:00+00:00',
'latency_ms' => 23.5,
'http_status' => $httpStatus,
'error' => '',
], 'Example API');
expect($result['status'])->toBe($expectedStatus);
expect($result['status_reason'])->toContain($reasonFragment);
})->with([
'success' => [200, 'ok', 'connectivity confirmed'],
'unauthorized' => [401, 'down', 'HTTP 401'],
'forbidden' => [403, 'down', 'HTTP 403'],
'rate limited' => [429, 'degraded', 'rate limited'],
'server error' => [503, 'degraded', 'HTTP 503'],
'no response' => [0, 'down', 'did not return an HTTP response'],
]);
it('classifies transport errors as down', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$result = $service->classifyHttpProbeResultPublic([
'checked_at' => '2026-04-08T17:10:00+00:00',
'latency_ms' => 7.5,
'http_status' => 0,
'error' => 'Connection refused',
], 'Example API');
expect($result['status'])->toBe('down');
expect($result['status_reason'])->toContain('Connection refused');
});
it('interprets recaptcha probe payloads safely', function (array $payload, string $expectedStatus, string $reasonFragment): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$result = $service->evaluateRecaptchaProbeResponsePublic([
'checked_at' => '2026-04-08T17:10:00+00:00',
'latency_ms' => 11.4,
'http_status' => 200,
'body' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'error' => '',
], 'reCAPTCHA');
expect($result['status'])->toBe($expectedStatus);
expect($result['status_reason'])->toContain($reasonFragment);
})->with([
'dummy token rejected but credentials valid' => [
['success' => false, 'error-codes' => ['invalid-input-response']],
'ok',
'connectivity confirmed',
],
'invalid secret is down' => [
['success' => false, 'error-codes' => ['invalid-input-secret']],
'down',
'credentials were rejected',
],
'unexpected validation errors degrade' => [
['success' => false, 'error-codes' => ['bad-request']],
'degraded',
'unexpected validation errors',
],
]);
it('builds the expected http probe requests for newly supported modules', function (
string $methodName,
array $config,
string $expectedUrl,
array $expectedHeaders,
?string $expectedBasicAuth,
string $expectedMethod,
?string $expectedBodyFragment,
bool $expectsEvaluator
): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$service->{$methodName}($config);
expect($service->httpProbeCalls)->toHaveCount(1);
$call = $service->httpProbeCalls[0];
expect($call['url'])->toBe($expectedUrl);
expect($call['basic_auth'])->toBe($expectedBasicAuth);
expect($call['method'])->toBe($expectedMethod);
expect($call['has_evaluator'])->toBe($expectsEvaluator);
foreach ($expectedHeaders as $expectedHeader) {
expect($call['headers'])->toContain($expectedHeader);
}
if ($expectedBodyFragment !== null) {
expect((string)$call['body'])->toContain($expectedBodyFragment);
} else {
expect($call['body'])->toBeNull();
}
})->with([
'recaptcha' => [
'probeRecaptchaModulePublic',
['secret_key_v2' => system_status_module_value('recaptcha-secret')],
'https://www.google.com/recaptcha/api/siteverify',
['Content-Type: application/x-www-form-urlencoded'],
null,
'POST',
'secret=recaptcha-secret',
true,
],
'email' => [
'probeEmailModulePublic',
['mailersend_api_key' => system_status_module_value('mailersend-key')],
'https://api.mailersend.com/v1/api-quota',
['Authorization: Bearer mailersend-key', 'Accept: application/json'],
null,
'GET',
null,
false,
],
'motorapi' => [
'probeMotorApiModulePublic',
['secret_key' => system_status_module_value('motorapi-key')],
'https://v1.motorapi.dk/usage',
['X-AUTH-TOKEN: motorapi-key'],
null,
'GET',
null,
false,
],
'fxratesapi' => [
'probeFxRatesApiModulePublic',
['secret_key' => system_status_module_value('fxrates-key')],
'https://api.fxratesapi.com/latest?base=EUR&currencies=DKK',
['X-AUTH-TOKEN: fxrates-key'],
null,
'GET',
null,
false,
],
'weatherapi' => [
'probeWeatherApiModulePublic',
['secret_key' => system_status_module_value('weather-key')],
'https://api.weatherapi.com/v1/current.json?key=weather-key&q=Copenhagen',
['Accept: application/json'],
null,
'GET',
null,
false,
],
'workfeed' => [
'probeWorkfeedModulePublic',
[
'api_url' => system_status_module_value('https://api.workfeed.test'),
'CompanyID' => system_status_module_value('company-123'),
'api_key' => system_status_module_value('workfeed-token'),
],
'https://api.workfeed.test/companies/company-123/departments',
['Accept: application/json', 'Authorization: workfeed-token'],
null,
'GET',
null,
false,
],
'gatewayapi' => [
'probeGatewayApiModulePublic',
['api_token' => system_status_module_value('gateway-token')],
'https://gatewayapi.eu/rest/me',
['Authorization: Token gateway-token', 'Accept: application/json'],
null,
'GET',
null,
false,
],
'xlvask' => [
'probeXlVaskModulePublic',
[
'username' => system_status_module_value('xl-user'),
'password' => system_status_module_value('xl-pass'),
],
'https://api.xlwash.com/customers',
['Accept: application/json'],
'xl-user:xl-pass',
'GET',
null,
false,
],
'limble' => [
'probeLimbleModulePublic',
[
'client_id' => system_status_module_value('limble-id'),
'client_secret' => system_status_module_value('limble-secret'),
],
'https://api.limblecmms.com:443/v2/tasks?limit=1&page=1',
['Accept: application/json', 'Content-Type: application/json'],
'limble-id:limble-secret',
'GET',
null,
false,
],
'license plate recognizer' => [
'probeLicensePlateRecognizerModulePublic',
['api_key' => system_status_module_value('lpr-key')],
'https://vs4sws0kg4sog4ssw8kwowk4.coolify.truckwash.dk/info/',
['Authorization: Token lpr-key', 'Accept: application/json'],
null,
'GET',
null,
false,
],
'bird' => [
'probeBirdModulePublic',
[
'server_url' => system_status_module_value('https://api.bird.com'),
'api_key' => system_status_module_value('bird-key'),
'channelId' => system_status_module_value('channel-123'),
'workplaceId' => system_status_module_value('workspace-456'),
],
'https://api.bird.com/workspaces/workspace-456/channels/channel-123/calls?limit=1',
['Authorization: AccessKey bird-key', 'Accept: application/json'],
null,
'GET',
null,
false,
],
]);
it('uses runtime economic credentials for the economic probe', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$GLOBALS['ECONOMIC_API'] = [
'app_secret_token' => 'economic-secret',
'app_access_grant' => 'economic-grant',
];
$service->probeEconomicModulePublic([]);
expect($service->httpProbeCalls)->toHaveCount(1);
$call = $service->httpProbeCalls[0];
expect($call['url'])->toBe('https://restapi.e-conomic.com/layouts/');
expect($call['headers'])->toContain('X-AppSecretToken: economic-secret');
expect($call['headers'])->toContain('X-AgreementGrantToken: economic-grant');
});
it('returns down without attempting economic http calls when runtime credentials are missing', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
unset($GLOBALS['ECONOMIC_API']);
$result = $service->probeEconomicModulePublic([]);
expect($result['status'])->toBe('down');
expect($result['status_reason'])->toContain('credentials are missing');
expect($service->httpProbeCalls)->toBeEmpty();
});
it('reports backup probe failures from local validation', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$service->backupStoreValidationShouldFail = true;
$service->backupStoreFailureMessage = 'Backups bucket is unavailable.';
$result = $service->probeBackupsModulePublic([]);
expect($result['status'])->toBe('down');
expect($result['status_reason'])->toContain('Backups bucket is unavailable');
});
it('returns configured for shelly when no known device id is available for probing', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$result = $service->probeShellyModulePublic([
'server_url' => system_status_module_value('https://shelly.example'),
'secret_key' => system_status_module_value('shelly-secret'),
]);
expect($result['status'])->toBe('configured');
expect($result['status_reason'])->toContain('no known device id');
expect($service->httpProbeCalls)->toBeEmpty();
});
it('builds an authenticated shelly status probe when a known device id exists', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$service->shellyProbeDeviceId = 'device-123';
$service->probeShellyModulePublic([
'server_url' => system_status_module_value('https://shelly.example'),
'secret_key' => system_status_module_value('shelly-secret'),
]);
expect($service->httpProbeCalls)->toHaveCount(1);
$call = $service->httpProbeCalls[0];
expect($call['url'])->toBe('https://shelly.example/device/status?id=device-123&auth_key=shelly-secret');
expect($call['headers'])->toContain('Accept: application/json');
expect($call['method'])->toBe('GET');
});
it('validates selfserve schema and minute product configuration', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$result = $service->probeSelfserveModulePublic([
'machine_wash_minutes_included' => system_status_module_value('15'),
'minute_product' => system_status_module_value('77'),
]);
expect($result['status'])->toBe('ok');
expect($service->selfserveMinuteProductCheckedId)->toBe(77);
});
it('reports invalid selfserve minute configuration before touching the schema', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$result = $service->probeSelfserveModulePublic([
'machine_wash_minutes_included' => system_status_module_value('abc'),
'minute_product' => system_status_module_value('77'),
]);
expect($result['status'])->toBe('down');
expect($result['status_reason'])->toContain('minutes configuration is invalid');
expect($service->selfserveMinuteProductCheckedId)->toBeNull();
});
it('reports missing selfserve minute products', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$service->selfserveMinuteProductExistsValue = false;
$result = $service->probeSelfserveModulePublic([
'machine_wash_minutes_included' => system_status_module_value('15'),
'minute_product' => system_status_module_value('88'),
]);
expect($result['status'])->toBe('down');
expect($result['status_reason'])->toContain('does not exist');
expect($service->selfserveMinuteProductCheckedId)->toBe(88);
});
it('surfaces selfserve bootstrap failures', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$service->selfserveBootstrapShouldFail = true;
$service->selfserveBootstrapFailureMessage = 'Migration failed.';
$result = $service->probeSelfserveModulePublic([
'machine_wash_minutes_included' => system_status_module_value('15'),
'minute_product' => system_status_module_value('88'),
]);
expect($result['status'])->toBe('down');
expect($result['status_reason'])->toContain('Migration failed');
});
it('marks newly supported modules as probe backed and leaves only truly unsupported modules as configuration only', function (): void {
$service = new SuperuserSystemStatusServiceProbeDouble();
$GLOBALS['ECONOMIC_API'] = [
'app_secret_token' => 'economic-secret',
'app_access_grant' => 'economic-grant',
];
$service->moduleConfigRowsOverride = [
'economic' => [
'invoiceLayoutNumber' => system_status_module_value('1'),
'paymentTermsNumber' => system_status_module_value('2'),
'adminFeeMonthly' => system_status_module_value('3'),
'adminFeeOrder' => system_status_module_value('4'),
'feeProductId' => system_status_module_value('5'),
],
'Email' => [
'enabled' => system_status_module_value(true, 'bool'),
'mailersend_enabled' => system_status_module_value(true, 'bool'),
'mailersend_api_key' => system_status_module_value('mailersend-key'),
'smtp_from' => system_status_module_value('from@example.com'),
'smtp_from_name' => system_status_module_value('Truck Wash'),
'smtp_reply_to' => system_status_module_value('reply@example.com'),
'smtp_reply_to_name' => system_status_module_value('Reply'),
],
'Backups' => [
'enabled' => system_status_module_value(true, 'bool'),
],
'motorapi' => [
'enabled' => system_status_module_value(true, 'bool'),
'secret_key' => system_status_module_value('motorapi-key'),
],
'fxratesapi' => [
'enabled' => system_status_module_value(true, 'bool'),
'secret_key' => system_status_module_value('fxrates-key'),
],
'weatherapi' => [
'enabled' => system_status_module_value(true, 'bool'),
'secret_key' => system_status_module_value('weather-key'),
],
'workfeed' => [
'enabled' => system_status_module_value(true, 'bool'),
'api_url' => system_status_module_value('https://api.workfeed.test'),
'api_key' => system_status_module_value('workfeed-token'),
'CompanyID' => system_status_module_value('company-123'),
],
'GatewayAPI' => [
'enabled' => system_status_module_value(true, 'bool'),
'api_secret' => system_status_module_value('gateway-secret'),
'api_token' => system_status_module_value('gateway-token'),
'sender' => system_status_module_value('TruckWash'),
],
'xlvask' => [
'enabled' => system_status_module_value(true, 'bool'),
'username' => system_status_module_value('xl-user'),
'password' => system_status_module_value('xl-pass'),
],
'limble' => [
'enabled' => system_status_module_value(true, 'bool'),
'client_id' => system_status_module_value('limble-id'),
'client_secret' => system_status_module_value('limble-secret'),
],
'licenseplaterecognizer' => [
'enabled' => system_status_module_value(true, 'bool'),
'api_key' => system_status_module_value('lpr-key'),
],
'shelly' => [
'enabled' => system_status_module_value(true, 'bool'),
'server_url' => system_status_module_value('https://shelly.example'),
'secret_key' => system_status_module_value('shelly-secret'),
],
'selfserve' => [
'enabled' => system_status_module_value(true, 'bool'),
'machine_wash_minutes_included' => system_status_module_value('15'),
'minute_product' => system_status_module_value('88'),
],
'bird' => [
'enabled' => system_status_module_value(true, 'bool'),
'server_url' => system_status_module_value('https://api.bird.com'),
'api_key' => system_status_module_value('bird-key'),
'channelId' => system_status_module_value('channel-123'),
'workplaceId' => system_status_module_value('workspace-456'),
],
'ocrSpace' => [
'enabled' => system_status_module_value(true, 'bool'),
'api_key' => system_status_module_value('ocr-key'),
],
'virkdata' => [
'enabled' => system_status_module_value(true, 'bool'),
'secret_key' => system_status_module_value('virk-key'),
],
];
$warnings = [];
$modules = $service->collectModulesPublic(false, $warnings);
$moduleMap = [];
foreach ($modules as $module) {
$moduleMap[$module['key']] = $module;
}
expect($moduleMap['email']['probe_supported'])->toBeTrue();
expect($moduleMap['email']['status'])->toBe('ok');
expect($moduleMap['backups']['probe_supported'])->toBeTrue();
expect($moduleMap['backups']['status'])->toBe('ok');
expect($moduleMap['motorapi']['probe_supported'])->toBeTrue();
expect($moduleMap['motorapi']['status'])->toBe('ok');
expect($moduleMap['bird']['probe_supported'])->toBeTrue();
expect($moduleMap['bird']['status'])->toBe('ok');
expect($moduleMap['shelly']['probe_supported'])->toBeTrue();
expect($moduleMap['shelly']['status'])->toBe('configured');
expect($moduleMap['selfserve']['probe_supported'])->toBeTrue();
expect($moduleMap['selfserve']['status'])->toBe('ok');
expect($moduleMap['ocrspace']['probe_supported'])->toBeFalse();
expect($moduleMap['ocrspace']['status'])->toBe('configured');
expect($moduleMap['virkdata']['probe_supported'])->toBeFalse();
expect($moduleMap['virkdata']['status'])->toBe('configured');
expect($warnings)->toHaveCount(1);
expect($warnings[0])->toContain('ocrspace, virkdata');
});
@@ -0,0 +1,21 @@
<?php
app_require('classes/system_session_activity_schema_bootstrap.php');
app_require('classes/system_session_activity_tracker.php');
use classes\system_session_activity_tracker;
it('detects device types from common user agents', function (): void {
expect(system_session_activity_tracker::detectDeviceType('Mozilla/5.0 (Windows NT 10.0; Win64; x64)'))->toBe('desktop');
expect(system_session_activity_tracker::detectDeviceType('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)'))->toBe('mobile');
expect(system_session_activity_tracker::detectDeviceType('Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X)'))->toBe('tablet');
expect(system_session_activity_tracker::detectDeviceType('curl/8.4.0'))->toBe('bot');
});
it('treats recent sessions as active within the configured activity window', function (): void {
$now = time();
expect(system_session_activity_tracker::isActive(date('Y-m-d H:i:s', $now - 60), 15, $now))->toBeTrue();
expect(system_session_activity_tracker::isActive(date('Y-m-d H:i:s', $now - 1200), 15, $now))->toBeFalse();
expect(system_session_activity_tracker::isActive(null, 15, $now))->toBeFalse();
});
+2
View File
@@ -3,6 +3,8 @@ entryPoints:
address: ":80"
websecure:
address: ":443"
edge-broker:
address: ":4300"
certificatesResolvers:
le:

Some files were not shown because too many files have changed in this diff Show More