@reqray/server 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/dist/cli.js +257 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +249 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +223 -0
- package/dist/index.js.map +1 -0
- package/package.json +67 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ruslan Kryklyvyi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @reqray/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Reqray collector: a separate process that receives request records from
|
|
4
|
+
your applications, stores them, and serves the panel. This is how Reqray runs
|
|
5
|
+
anywhere the application is reachable from outside — the application only
|
|
6
|
+
ships batches, and the data and the panel live here.
|
|
7
|
+
|
|
8
|
+
Part of [Reqray](https://github.com/reqray/reqray) — a dev panel and request inspector for Node.js. It
|
|
9
|
+
instruments HTTP, SQL, outgoing calls and cache on its own, shows every
|
|
10
|
+
request as a waterfall, and finds N+1 down to the file and the line.
|
|
11
|
+
|
|
12
|
+
## Run
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
REQRAY_TOKEN=change-me HOST=0.0.0.0 npx @reqray/server
|
|
16
|
+
# panel: http://<host>:4300/auth?token=change-me
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
| Variable | Default | |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| `PORT` | `4300` | |
|
|
22
|
+
| `HOST` | `127.0.0.1` | Anything else requires a token |
|
|
23
|
+
| `REQRAY_TOKEN` | none | Applications send it with their batches; people sign in at `/auth?token=…` |
|
|
24
|
+
| `REQRAY_DB` | none (memory) | Path to a SQLite file — a history that survives a restart |
|
|
25
|
+
| `REQRAY_LOG` | none | Directory for a log on disk, one JSON line per request, a file per day |
|
|
26
|
+
| `REQRAY_DAYS` | none | How many days the store and the log keep |
|
|
27
|
+
| `BUFFER_SIZE` | `2000` | Requests kept in memory when there is no `REQRAY_DB` |
|
|
28
|
+
|
|
29
|
+
Without a token the collector refuses to listen on anything but loopback: the
|
|
30
|
+
panel shows request bodies and SQL.
|
|
31
|
+
|
|
32
|
+
Node 22.5 or newer — SQLite is built in from there, and nothing is compiled at
|
|
33
|
+
install time.
|
|
34
|
+
|
|
35
|
+
## Point an application at it
|
|
36
|
+
|
|
37
|
+
```js
|
|
38
|
+
import { httpTransport } from '@reqray/transport-http';
|
|
39
|
+
|
|
40
|
+
await app.register(reqray, {
|
|
41
|
+
enabled: true,
|
|
42
|
+
mode: 'production',
|
|
43
|
+
panel: false, // the panel lives on the collector
|
|
44
|
+
transport: httpTransport({
|
|
45
|
+
url: 'http://reqray-collector:4300',
|
|
46
|
+
token: process.env.REQRAY_TOKEN,
|
|
47
|
+
}),
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Under load the collector answers `429` with `Retry-After` rather than queueing
|
|
52
|
+
without bound, and the transport backs off.
|
|
53
|
+
|
|
54
|
+
## From code
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
import { createReqrayServer } from '@reqray/server';
|
|
58
|
+
|
|
59
|
+
const server = await createReqrayServer({ port: 4300, token: process.env.REQRAY_TOKEN });
|
|
60
|
+
console.log(server.url);
|
|
61
|
+
await server.close();
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## More
|
|
65
|
+
|
|
66
|
+
Everything else — the detectors, security defaults, measured overhead and a
|
|
67
|
+
demo that runs with one command — is in the
|
|
68
|
+
[main README](https://github.com/reqray/reqray#readme).
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
[MIT](https://github.com/reqray/reqray/blob/main/LICENSE)
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { randomBytes, timingSafeEqual } from "crypto";
|
|
5
|
+
import { once } from "events";
|
|
6
|
+
import { createServer } from "http";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
import { dirname, join } from "path";
|
|
9
|
+
import {
|
|
10
|
+
isLocalRequest,
|
|
11
|
+
resolveOptions,
|
|
12
|
+
retentionPolicy,
|
|
13
|
+
warnOnce
|
|
14
|
+
} from "@reqray/core";
|
|
15
|
+
import { createPanelHandler } from "@reqray/core/panel";
|
|
16
|
+
import { memoryTransport } from "@reqray/store-memory";
|
|
17
|
+
import { sqliteTransport } from "@reqray/store-sqlite";
|
|
18
|
+
import { fileTransport } from "@reqray/transport-file";
|
|
19
|
+
var COOKIE_NAME = "reqray_token";
|
|
20
|
+
var MAX_INGEST_BYTES = 32 * 1024 * 1024;
|
|
21
|
+
var MAX_CONCURRENT_INGESTS = 8;
|
|
22
|
+
function dashboardAssets() {
|
|
23
|
+
try {
|
|
24
|
+
const manifest = createRequire(import.meta.url).resolve("@reqray/dashboard/package.json");
|
|
25
|
+
return join(dirname(manifest), "dist");
|
|
26
|
+
} catch {
|
|
27
|
+
return void 0;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function tokenMatches(expected, presented) {
|
|
31
|
+
if (!presented) return false;
|
|
32
|
+
const a = Buffer.from(expected);
|
|
33
|
+
const b = Buffer.from(presented);
|
|
34
|
+
if (a.length !== b.length) return false;
|
|
35
|
+
return timingSafeEqual(a, b);
|
|
36
|
+
}
|
|
37
|
+
function cookieValue(header, name) {
|
|
38
|
+
if (!header) return void 0;
|
|
39
|
+
for (const part of header.split(";")) {
|
|
40
|
+
const eq = part.indexOf("=");
|
|
41
|
+
if (eq === -1) continue;
|
|
42
|
+
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
|
|
43
|
+
}
|
|
44
|
+
return void 0;
|
|
45
|
+
}
|
|
46
|
+
function bearerToken(header) {
|
|
47
|
+
if (!header) return void 0;
|
|
48
|
+
return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : void 0;
|
|
49
|
+
}
|
|
50
|
+
function issueSession() {
|
|
51
|
+
return randomBytes(24).toString("base64url");
|
|
52
|
+
}
|
|
53
|
+
function sendJson(response, status, payload) {
|
|
54
|
+
const body = JSON.stringify(payload);
|
|
55
|
+
response.writeHead(status, {
|
|
56
|
+
"content-type": "application/json; charset=utf-8",
|
|
57
|
+
"content-length": Buffer.byteLength(body)
|
|
58
|
+
});
|
|
59
|
+
response.end(body);
|
|
60
|
+
}
|
|
61
|
+
function isIngestible(value) {
|
|
62
|
+
const record = value;
|
|
63
|
+
return typeof record === "object" && record !== null && typeof record.id === "string" && typeof record.method === "string" && typeof record.path === "string" && typeof record.status === "number" && typeof record.durationMs === "number" && typeof record.startedAt === "number" && Array.isArray(record.spans) && Array.isArray(record.findings) && Array.isArray(record.logs);
|
|
64
|
+
}
|
|
65
|
+
async function readBody(request) {
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let size = 0;
|
|
68
|
+
for await (const chunk of request) {
|
|
69
|
+
const buffer = chunk;
|
|
70
|
+
size += buffer.length;
|
|
71
|
+
if (size > MAX_INGEST_BYTES) throw new Error("batch larger than 32 MB");
|
|
72
|
+
chunks.push(buffer);
|
|
73
|
+
}
|
|
74
|
+
return Buffer.concat(chunks);
|
|
75
|
+
}
|
|
76
|
+
async function createReqrayServer(options = {}) {
|
|
77
|
+
const token2 = options.token;
|
|
78
|
+
const host = options.host ?? "127.0.0.1";
|
|
79
|
+
if (!token2 && host !== "127.0.0.1" && host !== "localhost") {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`reqray-server: listening on ${host} without a token is not allowed \u2014 the panel exposes request bodies and SQL. Set a token or keep 127.0.0.1.`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
const remembered = options.db ? `${options.db}.retention.json` : options.logDir ? join(options.logDir, "retention.json") : void 0;
|
|
85
|
+
const retention = options.retentionDays || remembered ? retentionPolicy({
|
|
86
|
+
...options.retentionDays ? { days: options.retentionDays } : {},
|
|
87
|
+
...options.bufferSize ? { maxRequests: options.bufferSize } : {},
|
|
88
|
+
...options.maxBytes ? { maxBytes: options.maxBytes } : {},
|
|
89
|
+
...remembered ? { file: remembered } : {}
|
|
90
|
+
}) : null;
|
|
91
|
+
const store = options.db ? sqliteTransport({
|
|
92
|
+
file: options.db,
|
|
93
|
+
...options.bufferSize ? { maxRequests: options.bufferSize } : {},
|
|
94
|
+
...options.maxBytes ? { maxBytes: options.maxBytes } : {},
|
|
95
|
+
...retention ? { retention } : {}
|
|
96
|
+
}) : memoryTransport({ capacity: options.bufferSize ?? 2e3 });
|
|
97
|
+
const log = options.logDir ? fileTransport({ dir: options.logDir, ...retention ? { retention } : {} }) : null;
|
|
98
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
99
|
+
let ingesting = 0;
|
|
100
|
+
const gate = token2 ? (context) => {
|
|
101
|
+
const cookie = cookieValue(
|
|
102
|
+
typeof context.headers.cookie === "string" ? context.headers.cookie : void 0,
|
|
103
|
+
COOKIE_NAME
|
|
104
|
+
);
|
|
105
|
+
if (cookie && sessions.has(cookie)) return true;
|
|
106
|
+
const header = context.headers["x-reqray-token"];
|
|
107
|
+
return typeof header === "string" && tokenMatches(token2, header);
|
|
108
|
+
} : void 0;
|
|
109
|
+
const panel = createPanelHandler({
|
|
110
|
+
source: store,
|
|
111
|
+
// The collector itself is not the application: nothing is sampled here
|
|
112
|
+
// and replay is impossible — the process the request lived in is remote.
|
|
113
|
+
options: resolveOptions({
|
|
114
|
+
enabled: true,
|
|
115
|
+
mode: "production",
|
|
116
|
+
replay: false,
|
|
117
|
+
panel: gate ? { gate } : {},
|
|
118
|
+
...retention ? { retention } : {},
|
|
119
|
+
...log ? { requestLog: log } : {}
|
|
120
|
+
}),
|
|
121
|
+
assetsDir: dashboardAssets()
|
|
122
|
+
});
|
|
123
|
+
const server2 = createServer((request, response) => {
|
|
124
|
+
void handle(request, response).catch((error) => {
|
|
125
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
126
|
+
warnOnce("server.handle", `collector failed to handle a request: ${reason}`);
|
|
127
|
+
if (!response.headersSent) sendJson(response, 500, { error: reason });
|
|
128
|
+
else response.end();
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
async function handle(request, response) {
|
|
132
|
+
const url = new URL(request.url ?? "/", "http://reqray.local");
|
|
133
|
+
if (url.pathname === "/healthz") {
|
|
134
|
+
sendJson(response, 200, { ok: true, size: store.stats().size });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (!token2 && !isLocalRequest({ headers: request.headers, ip: request.socket.remoteAddress ?? null })) {
|
|
138
|
+
sendJson(response, 403, {
|
|
139
|
+
error: "without a token the collector answers only to this machine, at a local address"
|
|
140
|
+
});
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (url.pathname === "/ingest" && request.method === "POST") {
|
|
144
|
+
if (token2 && !tokenMatches(token2, bearerToken(request.headers.authorization))) {
|
|
145
|
+
sendJson(response, 401, { error: "token required: authorization: Bearer <token>" });
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (!/^application\/json\b/i.test(request.headers["content-type"] ?? "")) {
|
|
149
|
+
sendJson(response, 415, { error: "a batch is sent as application/json" });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (ingesting >= MAX_CONCURRENT_INGESTS) {
|
|
153
|
+
response.writeHead(429, { "retry-after": "1", connection: "close" });
|
|
154
|
+
response.end();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
let payload;
|
|
158
|
+
ingesting++;
|
|
159
|
+
try {
|
|
160
|
+
payload = JSON.parse((await readBody(request)).toString("utf8"));
|
|
161
|
+
} catch (error) {
|
|
162
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
163
|
+
sendJson(response, 400, { error: `batch not parsed: ${reason}` });
|
|
164
|
+
return;
|
|
165
|
+
} finally {
|
|
166
|
+
ingesting--;
|
|
167
|
+
}
|
|
168
|
+
const items = Array.isArray(payload.requests) ? payload.requests : [];
|
|
169
|
+
let accepted = 0;
|
|
170
|
+
for (const item of items) {
|
|
171
|
+
if (!isIngestible(item)) continue;
|
|
172
|
+
store.send(item);
|
|
173
|
+
log?.send(item);
|
|
174
|
+
accepted++;
|
|
175
|
+
}
|
|
176
|
+
if (accepted < items.length) {
|
|
177
|
+
warnOnce(
|
|
178
|
+
"server.ingest",
|
|
179
|
+
`malformed records dropped from the batch: ${items.length - accepted}`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
sendJson(response, 200, { accepted });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (url.pathname === "/auth" && token2) {
|
|
186
|
+
if (!tokenMatches(token2, url.searchParams.get("token") ?? void 0)) {
|
|
187
|
+
sendJson(response, 403, { error: "invalid token" });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const session = issueSession();
|
|
191
|
+
sessions.add(session);
|
|
192
|
+
response.writeHead(302, {
|
|
193
|
+
"set-cookie": `${COOKIE_NAME}=${session}; HttpOnly; Path=/; SameSite=Strict`,
|
|
194
|
+
location: "/_reqray/"
|
|
195
|
+
});
|
|
196
|
+
response.end();
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (panel?.(request, response)) return;
|
|
200
|
+
if (url.pathname === "/") {
|
|
201
|
+
response.writeHead(302, { location: "/_reqray/" });
|
|
202
|
+
response.end();
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
sendJson(response, 404, { error: "no such path. Panel: /_reqray/, ingest: POST /ingest" });
|
|
206
|
+
}
|
|
207
|
+
server2.listen(options.port ?? 4300, host);
|
|
208
|
+
await once(server2, "listening");
|
|
209
|
+
const address = server2.address();
|
|
210
|
+
return {
|
|
211
|
+
url: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${address.port}`,
|
|
212
|
+
store,
|
|
213
|
+
close: async () => {
|
|
214
|
+
await new Promise((resolve) => {
|
|
215
|
+
server2.closeAllConnections();
|
|
216
|
+
server2.close(() => resolve());
|
|
217
|
+
});
|
|
218
|
+
await store.close?.();
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// src/cli.ts
|
|
224
|
+
var token = process.env["REQRAY_TOKEN"];
|
|
225
|
+
var db = process.env["REQRAY_DB"];
|
|
226
|
+
var bufferSize = Number(process.env["BUFFER_SIZE"]);
|
|
227
|
+
var maxBytes = Number(process.env["MAX_BYTES"]);
|
|
228
|
+
var logDir = process.env["REQRAY_LOG"];
|
|
229
|
+
var retentionDays = Number(process.env["REQRAY_DAYS"]);
|
|
230
|
+
var server = await createReqrayServer({
|
|
231
|
+
port: Number(process.env["PORT"] ?? 4300),
|
|
232
|
+
host: process.env["HOST"] ?? "127.0.0.1",
|
|
233
|
+
...token ? { token } : {},
|
|
234
|
+
// Left unset the store picks its own: the ring keeps 2000, the history
|
|
235
|
+
// keeps far more, and neither should inherit the other's number.
|
|
236
|
+
...Number.isFinite(bufferSize) && bufferSize > 0 ? { bufferSize } : {},
|
|
237
|
+
...db ? { db } : {},
|
|
238
|
+
...Number.isFinite(maxBytes) && maxBytes > 0 ? { maxBytes } : {},
|
|
239
|
+
...logDir ? { logDir } : {},
|
|
240
|
+
...Number.isFinite(retentionDays) && retentionDays > 0 ? { retentionDays } : {}
|
|
241
|
+
});
|
|
242
|
+
console.log(`
|
|
243
|
+
reqray-server is accepting batches
|
|
244
|
+
|
|
245
|
+
storage ${db ? `SQLite at ${db} \u2014 the history outlives this process` : "in memory \u2014 gone when this process is"}${logDir ? `
|
|
246
|
+
log ${logDir} \u2014 one JSON line per request, a file per day` : ""}${Number.isFinite(retentionDays) && retentionDays > 0 ? `
|
|
247
|
+
keeping ${retentionDays} days, changeable from the panel` : ""}
|
|
248
|
+
panel ${server.url}/_reqray/${token ? ` (sign in: ${server.url}/auth?token=\u2026)` : ""}
|
|
249
|
+
ingest POST ${server.url}/ingest${token ? " (authorization: Bearer \u2026)" : ""}
|
|
250
|
+
health ${server.url}/healthz
|
|
251
|
+
${token ? "" : "\n No token set \u2014 the server listens on 127.0.0.1 only.\n"}`);
|
|
252
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
253
|
+
process.on(signal, () => {
|
|
254
|
+
void server.close().then(() => process.exit(0));
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/cli.ts"],"sourcesContent":["/**\n * `@reqray/server` — the collector.\n *\n * A separate process: applications ship batches over HTTP (see\n * `@reqray/transport-http`), the collector stores them and serves the same\n * panel the in-process adapters do. Bare `node:http` on purpose — a collector\n * needs no router or plugins, and every dependency is somebody else's risk.\n *\n * Security model: with no token the server listens on loopback only, exactly\n * like local development. A token makes it reachable from outside: ingest\n * requires it in the `authorization` header, and the panel is opened in a\n * browser through `/auth?token=…`, which sets an HttpOnly cookie.\n */\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { once } from 'node:events';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport {\n isLocalRequest,\n type PanelGate,\n type RecordedRequest,\n resolveOptions,\n retentionPolicy,\n type Transport,\n warnOnce,\n} from '@reqray/core';\nimport { createPanelHandler, type PanelSource } from '@reqray/core/panel';\nimport { memoryTransport } from '@reqray/store-memory';\nimport { sqliteTransport } from '@reqray/store-sqlite';\nimport { fileTransport } from '@reqray/transport-file';\n\n/** Options for {@link createReqrayServer}. */\nexport interface ReqrayServerOptions {\n /** Port. `0` picks a free one. */\n readonly port?: number;\n /**\n * Address to bind. Defaults to loopback; anything wider requires a token —\n * the collector shows request bodies and SQL to whoever reaches it.\n */\n readonly host?: string;\n /** Shared secret: required in ingest headers and for panel access. */\n readonly token?: string;\n /** How many requests the collector keeps. */\n readonly bufferSize?: number;\n /**\n * Path to a SQLite file. Given one, the collector keeps a history that\n * outlives it; without one, requests live in memory and die with the\n * process.\n */\n readonly db?: string;\n /** With `db`: how much disk the stored requests may take, bytes. */\n readonly maxBytes?: number;\n /**\n * Directory for the request log: one line of JSON per request, a file per\n * day. Without it the collector keeps requests only in its store.\n */\n readonly logDir?: string;\n /**\n * How many days anything is kept for — the store and the log alike.\n *\n * Changeable from the panel, and remembered next to the database so the\n * change survives a restart.\n */\n readonly retentionDays?: number;\n}\n\n/**\n * What the collector needs from a store, whichever one it is.\n *\n * Structural rather than a named union: the memory ring and the SQLite\n * history have nothing in common but this, and the collector uses nothing\n * else.\n */\nexport type CollectorStore = PanelSource &\n Transport & {\n stats(): { size: number };\n close?(): Promise<void>;\n };\n\n/** A running collector. */\nexport interface ReqrayServer {\n /** Address the server actually listens on. */\n readonly url: string;\n /** The store — exposed for tests and embedding. */\n readonly store: CollectorStore;\n close(): Promise<void>;\n}\n\nconst COOKIE_NAME = 'reqray_token';\nconst MAX_INGEST_BYTES = 32 * 1024 * 1024;\n/**\n * How many batches may be on their way in at once.\n *\n * Each is held whole in memory until it is parsed, so this is the collector's\n * memory bound — eight of the largest is 256 MB. Past it the answer is 429\n * with `Retry-After`, which the transport honours: a collector that can only\n * fall over takes the agents' queues down with it.\n */\nconst MAX_CONCURRENT_INGESTS = 8;\n\n/** Directory with the built dashboard, when it is installed. */\nfunction dashboardAssets(): string | undefined {\n try {\n const manifest = createRequire(import.meta.url).resolve('@reqray/dashboard/package.json');\n return join(dirname(manifest), 'dist');\n } catch {\n return undefined;\n }\n}\n\n/** Constant-time comparison: a token check must not leak length or prefix. */\nfunction tokenMatches(expected: string, presented: string | undefined): boolean {\n if (!presented) return false;\n const a = Buffer.from(expected);\n const b = Buffer.from(presented);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\nfunction cookieValue(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\nfunction bearerToken(header: string | undefined): string | undefined {\n if (!header) return undefined;\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined;\n}\n\n/**\n * The token in the cookie is not the token itself but a per-process session\n * value issued by `/auth`: cookies leak far more easily than the secret\n * should.\n */\nfunction issueSession(): string {\n return randomBytes(24).toString('base64url');\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/** Light shape check: one malformed record must not poison the panel. */\nfunction isIngestible(value: unknown): value is RecordedRequest {\n const record = value as Partial<RecordedRequest> | null;\n return (\n typeof record === 'object' &&\n record !== null &&\n typeof record.id === 'string' &&\n typeof record.method === 'string' &&\n typeof record.path === 'string' &&\n typeof record.status === 'number' &&\n typeof record.durationMs === 'number' &&\n typeof record.startedAt === 'number' &&\n Array.isArray(record.spans) &&\n Array.isArray(record.findings) &&\n Array.isArray(record.logs)\n );\n}\n\nasync function readBody(request: IncomingMessage): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > MAX_INGEST_BYTES) throw new Error('batch larger than 32 MB');\n chunks.push(buffer);\n }\n return Buffer.concat(chunks);\n}\n\n/** Starts the collector. Resolves once it is listening. */\nexport async function createReqrayServer(options: ReqrayServerOptions = {}): Promise<ReqrayServer> {\n const token = options.token;\n const host = options.host ?? '127.0.0.1';\n\n if (!token && host !== '127.0.0.1' && host !== 'localhost') {\n throw new Error(\n `reqray-server: listening on ${host} without a token is not allowed — the panel exposes request bodies and SQL. ` +\n 'Set a token or keep 127.0.0.1.',\n );\n }\n\n // One policy for the store and the log, remembered beside whichever of them\n // is on disk: a collector restarted by an orchestrator must come back with\n // the setting somebody chose, not the one that was compiled in.\n const remembered = options.db\n ? `${options.db}.retention.json`\n : options.logDir\n ? join(options.logDir, 'retention.json')\n : undefined;\n const retention =\n options.retentionDays || remembered\n ? retentionPolicy({\n ...(options.retentionDays ? { days: options.retentionDays } : {}),\n ...(options.bufferSize ? { maxRequests: options.bufferSize } : {}),\n ...(options.maxBytes ? { maxBytes: options.maxBytes } : {}),\n ...(remembered ? { file: remembered } : {}),\n })\n : null;\n\n // A file means a history; no file means the ring, which is what a\n // throwaway staging stand wants and what the collector has always been.\n const store: CollectorStore = options.db\n ? sqliteTransport({\n file: options.db,\n ...(options.bufferSize ? { maxRequests: options.bufferSize } : {}),\n ...(options.maxBytes ? { maxBytes: options.maxBytes } : {}),\n ...(retention ? { retention } : {}),\n })\n : memoryTransport({ capacity: options.bufferSize ?? 2_000 });\n\n // The log is beside the store, not instead of it: one is what the panel\n // reads, the other is what a log shipper picks up and an operator keeps.\n const log = options.logDir\n ? fileTransport({ dir: options.logDir, ...(retention ? { retention } : {}) })\n : null;\n const sessions = new Set<string>();\n /** Batches being read right now. */\n let ingesting = 0;\n\n // The panel is authorized either by the cookie session issued at /auth or\n // by the raw token in a header — the latter for curl and healthchecks.\n //\n // Without a token there is no gate at all, and core then lets in only what\n // comes from this machine addressed to this machine — `'open'` here used to\n // let a hostile page re-pointed at 127.0.0.1 read every recorded body.\n const gate: PanelGate | undefined = token\n ? (context) => {\n const cookie = cookieValue(\n typeof context.headers.cookie === 'string' ? context.headers.cookie : undefined,\n COOKIE_NAME,\n );\n if (cookie && sessions.has(cookie)) return true;\n const header = context.headers['x-reqray-token'];\n return typeof header === 'string' && tokenMatches(token, header);\n }\n : undefined;\n\n const panel = createPanelHandler({\n source: store,\n // The collector itself is not the application: nothing is sampled here\n // and replay is impossible — the process the request lived in is remote.\n options: resolveOptions({\n enabled: true,\n mode: 'production',\n replay: false,\n panel: gate ? { gate } : {},\n ...(retention ? { retention } : {}),\n ...(log ? { requestLog: log } : {}),\n }),\n assetsDir: dashboardAssets(),\n });\n\n const server: Server = createServer((request, response) => {\n void handle(request, response).catch((error) => {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('server.handle', `collector failed to handle a request: ${reason}`);\n if (!response.headersSent) sendJson(response, 500, { error: reason });\n else response.end();\n });\n });\n\n async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {\n const url = new URL(request.url ?? '/', 'http://reqray.local');\n\n if (url.pathname === '/healthz') {\n sendJson(response, 200, { ok: true, size: store.stats().size });\n return;\n }\n\n // No token: the whole collector is for this machine only, the same rule\n // the panel follows without a gate.\n if (\n !token &&\n !isLocalRequest({ headers: request.headers, ip: request.socket.remoteAddress ?? null })\n ) {\n sendJson(response, 403, {\n error: 'without a token the collector answers only to this machine, at a local address',\n });\n return;\n }\n\n if (url.pathname === '/ingest' && request.method === 'POST') {\n if (token && !tokenMatches(token, bearerToken(request.headers.authorization))) {\n sendJson(response, 401, { error: 'token required: authorization: Bearer <token>' });\n return;\n }\n // A page in a browser can POST text to a local port without asking;\n // it cannot send JSON without a preflight, which nothing here answers.\n if (!/^application\\/json\\b/i.test(request.headers['content-type'] ?? '')) {\n sendJson(response, 415, { error: 'a batch is sent as application/json' });\n return;\n }\n\n if (ingesting >= MAX_CONCURRENT_INGESTS) {\n // The body is not read, so the connection cannot be reused.\n response.writeHead(429, { 'retry-after': '1', connection: 'close' });\n response.end();\n return;\n }\n\n let payload: { requests?: unknown };\n ingesting++;\n try {\n payload = JSON.parse((await readBody(request)).toString('utf8')) as { requests?: unknown };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `batch not parsed: ${reason}` });\n return;\n } finally {\n ingesting--;\n }\n\n const items = Array.isArray(payload.requests) ? payload.requests : [];\n let accepted = 0;\n for (const item of items) {\n if (!isIngestible(item)) continue;\n store.send(item);\n log?.send(item);\n accepted++;\n }\n if (accepted < items.length) {\n warnOnce(\n 'server.ingest',\n `malformed records dropped from the batch: ${items.length - accepted}`,\n );\n }\n sendJson(response, 200, { accepted });\n return;\n }\n\n if (url.pathname === '/auth' && token) {\n if (!tokenMatches(token, url.searchParams.get('token') ?? undefined)) {\n sendJson(response, 403, { error: 'invalid token' });\n return;\n }\n const session = issueSession();\n sessions.add(session);\n response.writeHead(302, {\n 'set-cookie': `${COOKIE_NAME}=${session}; HttpOnly; Path=/; SameSite=Strict`,\n location: '/_reqray/',\n });\n response.end();\n return;\n }\n\n if (panel?.(request, response)) return;\n\n if (url.pathname === '/') {\n response.writeHead(302, { location: '/_reqray/' });\n response.end();\n return;\n }\n\n sendJson(response, 404, { error: 'no such path. Panel: /_reqray/, ingest: POST /ingest' });\n }\n\n server.listen(options.port ?? 4300, host);\n await once(server, 'listening');\n const address = server.address() as AddressInfo;\n\n return {\n url: `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${address.port}`,\n store,\n close: async () => {\n await new Promise<void>((resolve) => {\n server.closeAllConnections();\n server.close(() => resolve());\n });\n // A history holds a file open; the ring has nothing to release.\n await store.close?.();\n },\n };\n}\n","#!/usr/bin/env node\n/**\n * `npx @reqray/server` — start the collector from the command line.\n *\n * Configured by environment variables, because that is what compose files and\n * process managers speak:\n *\n * PORT port, default 4300\n * HOST bind address; anything but loopback requires REQRAY_TOKEN\n * REQRAY_TOKEN shared secret for ingest and the panel\n * BUFFER_SIZE how many requests to keep: 2000 in memory, 20000 with a file\n * REQRAY_DB path to a SQLite file; without it requests live in memory\n * and are gone when this process is\n * MAX_BYTES with REQRAY_DB: how much disk the history may take\n * REQRAY_LOG directory for the request log: one JSON line per request,\n * a file per day, swept by the same retention policy\n * REQRAY_DAYS how many days to keep — store and log alike. Changeable\n * from the panel, and remembered on disk\n */\n\nimport { createReqrayServer } from './index.js';\n\nconst token = process.env['REQRAY_TOKEN'];\nconst db = process.env['REQRAY_DB'];\nconst bufferSize = Number(process.env['BUFFER_SIZE']);\nconst maxBytes = Number(process.env['MAX_BYTES']);\nconst logDir = process.env['REQRAY_LOG'];\nconst retentionDays = Number(process.env['REQRAY_DAYS']);\n\nconst server = await createReqrayServer({\n port: Number(process.env['PORT'] ?? 4300),\n host: process.env['HOST'] ?? '127.0.0.1',\n ...(token ? { token } : {}),\n // Left unset the store picks its own: the ring keeps 2000, the history\n // keeps far more, and neither should inherit the other's number.\n ...(Number.isFinite(bufferSize) && bufferSize > 0 ? { bufferSize } : {}),\n ...(db ? { db } : {}),\n ...(Number.isFinite(maxBytes) && maxBytes > 0 ? { maxBytes } : {}),\n ...(logDir ? { logDir } : {}),\n ...(Number.isFinite(retentionDays) && retentionDays > 0 ? { retentionDays } : {}),\n});\n\nconsole.log(`\nreqray-server is accepting batches\n\n storage ${db ? `SQLite at ${db} — the history outlives this process` : 'in memory — gone when this process is'}${logDir ? `\\n log ${logDir} — one JSON line per request, a file per day` : ''}${Number.isFinite(retentionDays) && retentionDays > 0 ? `\\n keeping ${retentionDays} days, changeable from the panel` : ''}\n panel ${server.url}/_reqray/${token ? ` (sign in: ${server.url}/auth?token=…)` : ''}\n ingest POST ${server.url}/ingest${token ? ' (authorization: Bearer …)' : ''}\n health ${server.url}/healthz\n${token ? '' : '\\n No token set — the server listens on 127.0.0.1 only.\\n'}`);\n\nfor (const signal of ['SIGINT', 'SIGTERM'] as const) {\n process.on(signal, () => {\n void server.close().then(() => process.exit(0));\n });\n}\n"],"mappings":";;;AAcA,SAAS,aAAa,uBAAuB;AAC7C,SAAS,YAAY;AACrB,SAAS,oBAA4E;AACrF,SAAS,qBAAqB;AAE9B,SAAS,SAAS,YAAY;AAC9B;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,0BAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AA2D9B,IAAM,cAAc;AACpB,IAAM,mBAAmB,KAAK,OAAO;AASrC,IAAM,yBAAyB;AAG/B,SAAS,kBAAsC;AAC7C,MAAI;AACF,UAAM,WAAW,cAAc,YAAY,GAAG,EAAE,QAAQ,gCAAgC;AACxF,WAAO,KAAK,QAAQ,QAAQ,GAAG,MAAM;AAAA,EACvC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,aAAa,UAAkB,WAAwC;AAC9E,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,IAAI,OAAO,KAAK,QAAQ;AAC9B,QAAM,IAAI,OAAO,KAAK,SAAS;AAC/B,MAAI,EAAE,WAAW,EAAE,OAAQ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
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
createReqrayServer: () => createReqrayServer
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
|
|
27
|
+
// ../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_supports-color@7.2.0_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js
|
|
28
|
+
var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
|
|
29
|
+
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
30
|
+
|
|
31
|
+
// src/index.ts
|
|
32
|
+
var import_node_crypto = require("crypto");
|
|
33
|
+
var import_node_events = require("events");
|
|
34
|
+
var import_node_http = require("http");
|
|
35
|
+
var import_node_module = require("module");
|
|
36
|
+
var import_node_path = require("path");
|
|
37
|
+
var import_core = require("@reqray/core");
|
|
38
|
+
var import_panel = require("@reqray/core/panel");
|
|
39
|
+
var import_store_memory = require("@reqray/store-memory");
|
|
40
|
+
var import_store_sqlite = require("@reqray/store-sqlite");
|
|
41
|
+
var import_transport_file = require("@reqray/transport-file");
|
|
42
|
+
var COOKIE_NAME = "reqray_token";
|
|
43
|
+
var MAX_INGEST_BYTES = 32 * 1024 * 1024;
|
|
44
|
+
var MAX_CONCURRENT_INGESTS = 8;
|
|
45
|
+
function dashboardAssets() {
|
|
46
|
+
try {
|
|
47
|
+
const manifest = (0, import_node_module.createRequire)(importMetaUrl).resolve("@reqray/dashboard/package.json");
|
|
48
|
+
return (0, import_node_path.join)((0, import_node_path.dirname)(manifest), "dist");
|
|
49
|
+
} catch {
|
|
50
|
+
return void 0;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function tokenMatches(expected, presented) {
|
|
54
|
+
if (!presented) return false;
|
|
55
|
+
const a = Buffer.from(expected);
|
|
56
|
+
const b = Buffer.from(presented);
|
|
57
|
+
if (a.length !== b.length) return false;
|
|
58
|
+
return (0, import_node_crypto.timingSafeEqual)(a, b);
|
|
59
|
+
}
|
|
60
|
+
function cookieValue(header, name) {
|
|
61
|
+
if (!header) return void 0;
|
|
62
|
+
for (const part of header.split(";")) {
|
|
63
|
+
const eq = part.indexOf("=");
|
|
64
|
+
if (eq === -1) continue;
|
|
65
|
+
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
|
|
66
|
+
}
|
|
67
|
+
return void 0;
|
|
68
|
+
}
|
|
69
|
+
function bearerToken(header) {
|
|
70
|
+
if (!header) return void 0;
|
|
71
|
+
return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : void 0;
|
|
72
|
+
}
|
|
73
|
+
function issueSession() {
|
|
74
|
+
return (0, import_node_crypto.randomBytes)(24).toString("base64url");
|
|
75
|
+
}
|
|
76
|
+
function sendJson(response, status, payload) {
|
|
77
|
+
const body = JSON.stringify(payload);
|
|
78
|
+
response.writeHead(status, {
|
|
79
|
+
"content-type": "application/json; charset=utf-8",
|
|
80
|
+
"content-length": Buffer.byteLength(body)
|
|
81
|
+
});
|
|
82
|
+
response.end(body);
|
|
83
|
+
}
|
|
84
|
+
function isIngestible(value) {
|
|
85
|
+
const record = value;
|
|
86
|
+
return typeof record === "object" && record !== null && typeof record.id === "string" && typeof record.method === "string" && typeof record.path === "string" && typeof record.status === "number" && typeof record.durationMs === "number" && typeof record.startedAt === "number" && Array.isArray(record.spans) && Array.isArray(record.findings) && Array.isArray(record.logs);
|
|
87
|
+
}
|
|
88
|
+
async function readBody(request) {
|
|
89
|
+
const chunks = [];
|
|
90
|
+
let size = 0;
|
|
91
|
+
for await (const chunk of request) {
|
|
92
|
+
const buffer = chunk;
|
|
93
|
+
size += buffer.length;
|
|
94
|
+
if (size > MAX_INGEST_BYTES) throw new Error("batch larger than 32 MB");
|
|
95
|
+
chunks.push(buffer);
|
|
96
|
+
}
|
|
97
|
+
return Buffer.concat(chunks);
|
|
98
|
+
}
|
|
99
|
+
async function createReqrayServer(options = {}) {
|
|
100
|
+
const token = options.token;
|
|
101
|
+
const host = options.host ?? "127.0.0.1";
|
|
102
|
+
if (!token && host !== "127.0.0.1" && host !== "localhost") {
|
|
103
|
+
throw new Error(
|
|
104
|
+
`reqray-server: listening on ${host} without a token is not allowed \u2014 the panel exposes request bodies and SQL. Set a token or keep 127.0.0.1.`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
const remembered = options.db ? `${options.db}.retention.json` : options.logDir ? (0, import_node_path.join)(options.logDir, "retention.json") : void 0;
|
|
108
|
+
const retention = options.retentionDays || remembered ? (0, import_core.retentionPolicy)({
|
|
109
|
+
...options.retentionDays ? { days: options.retentionDays } : {},
|
|
110
|
+
...options.bufferSize ? { maxRequests: options.bufferSize } : {},
|
|
111
|
+
...options.maxBytes ? { maxBytes: options.maxBytes } : {},
|
|
112
|
+
...remembered ? { file: remembered } : {}
|
|
113
|
+
}) : null;
|
|
114
|
+
const store = options.db ? (0, import_store_sqlite.sqliteTransport)({
|
|
115
|
+
file: options.db,
|
|
116
|
+
...options.bufferSize ? { maxRequests: options.bufferSize } : {},
|
|
117
|
+
...options.maxBytes ? { maxBytes: options.maxBytes } : {},
|
|
118
|
+
...retention ? { retention } : {}
|
|
119
|
+
}) : (0, import_store_memory.memoryTransport)({ capacity: options.bufferSize ?? 2e3 });
|
|
120
|
+
const log = options.logDir ? (0, import_transport_file.fileTransport)({ dir: options.logDir, ...retention ? { retention } : {} }) : null;
|
|
121
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
122
|
+
let ingesting = 0;
|
|
123
|
+
const gate = token ? (context) => {
|
|
124
|
+
const cookie = cookieValue(
|
|
125
|
+
typeof context.headers.cookie === "string" ? context.headers.cookie : void 0,
|
|
126
|
+
COOKIE_NAME
|
|
127
|
+
);
|
|
128
|
+
if (cookie && sessions.has(cookie)) return true;
|
|
129
|
+
const header = context.headers["x-reqray-token"];
|
|
130
|
+
return typeof header === "string" && tokenMatches(token, header);
|
|
131
|
+
} : void 0;
|
|
132
|
+
const panel = (0, import_panel.createPanelHandler)({
|
|
133
|
+
source: store,
|
|
134
|
+
// The collector itself is not the application: nothing is sampled here
|
|
135
|
+
// and replay is impossible — the process the request lived in is remote.
|
|
136
|
+
options: (0, import_core.resolveOptions)({
|
|
137
|
+
enabled: true,
|
|
138
|
+
mode: "production",
|
|
139
|
+
replay: false,
|
|
140
|
+
panel: gate ? { gate } : {},
|
|
141
|
+
...retention ? { retention } : {},
|
|
142
|
+
...log ? { requestLog: log } : {}
|
|
143
|
+
}),
|
|
144
|
+
assetsDir: dashboardAssets()
|
|
145
|
+
});
|
|
146
|
+
const server = (0, import_node_http.createServer)((request, response) => {
|
|
147
|
+
void handle(request, response).catch((error) => {
|
|
148
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
149
|
+
(0, import_core.warnOnce)("server.handle", `collector failed to handle a request: ${reason}`);
|
|
150
|
+
if (!response.headersSent) sendJson(response, 500, { error: reason });
|
|
151
|
+
else response.end();
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
async function handle(request, response) {
|
|
155
|
+
const url = new URL(request.url ?? "/", "http://reqray.local");
|
|
156
|
+
if (url.pathname === "/healthz") {
|
|
157
|
+
sendJson(response, 200, { ok: true, size: store.stats().size });
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (!token && !(0, import_core.isLocalRequest)({ headers: request.headers, ip: request.socket.remoteAddress ?? null })) {
|
|
161
|
+
sendJson(response, 403, {
|
|
162
|
+
error: "without a token the collector answers only to this machine, at a local address"
|
|
163
|
+
});
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (url.pathname === "/ingest" && request.method === "POST") {
|
|
167
|
+
if (token && !tokenMatches(token, bearerToken(request.headers.authorization))) {
|
|
168
|
+
sendJson(response, 401, { error: "token required: authorization: Bearer <token>" });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!/^application\/json\b/i.test(request.headers["content-type"] ?? "")) {
|
|
172
|
+
sendJson(response, 415, { error: "a batch is sent as application/json" });
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (ingesting >= MAX_CONCURRENT_INGESTS) {
|
|
176
|
+
response.writeHead(429, { "retry-after": "1", connection: "close" });
|
|
177
|
+
response.end();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
let payload;
|
|
181
|
+
ingesting++;
|
|
182
|
+
try {
|
|
183
|
+
payload = JSON.parse((await readBody(request)).toString("utf8"));
|
|
184
|
+
} catch (error) {
|
|
185
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
186
|
+
sendJson(response, 400, { error: `batch not parsed: ${reason}` });
|
|
187
|
+
return;
|
|
188
|
+
} finally {
|
|
189
|
+
ingesting--;
|
|
190
|
+
}
|
|
191
|
+
const items = Array.isArray(payload.requests) ? payload.requests : [];
|
|
192
|
+
let accepted = 0;
|
|
193
|
+
for (const item of items) {
|
|
194
|
+
if (!isIngestible(item)) continue;
|
|
195
|
+
store.send(item);
|
|
196
|
+
log?.send(item);
|
|
197
|
+
accepted++;
|
|
198
|
+
}
|
|
199
|
+
if (accepted < items.length) {
|
|
200
|
+
(0, import_core.warnOnce)(
|
|
201
|
+
"server.ingest",
|
|
202
|
+
`malformed records dropped from the batch: ${items.length - accepted}`
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
sendJson(response, 200, { accepted });
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (url.pathname === "/auth" && token) {
|
|
209
|
+
if (!tokenMatches(token, url.searchParams.get("token") ?? void 0)) {
|
|
210
|
+
sendJson(response, 403, { error: "invalid token" });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const session = issueSession();
|
|
214
|
+
sessions.add(session);
|
|
215
|
+
response.writeHead(302, {
|
|
216
|
+
"set-cookie": `${COOKIE_NAME}=${session}; HttpOnly; Path=/; SameSite=Strict`,
|
|
217
|
+
location: "/_reqray/"
|
|
218
|
+
});
|
|
219
|
+
response.end();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (panel?.(request, response)) return;
|
|
223
|
+
if (url.pathname === "/") {
|
|
224
|
+
response.writeHead(302, { location: "/_reqray/" });
|
|
225
|
+
response.end();
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
sendJson(response, 404, { error: "no such path. Panel: /_reqray/, ingest: POST /ingest" });
|
|
229
|
+
}
|
|
230
|
+
server.listen(options.port ?? 4300, host);
|
|
231
|
+
await (0, import_node_events.once)(server, "listening");
|
|
232
|
+
const address = server.address();
|
|
233
|
+
return {
|
|
234
|
+
url: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${address.port}`,
|
|
235
|
+
store,
|
|
236
|
+
close: async () => {
|
|
237
|
+
await new Promise((resolve) => {
|
|
238
|
+
server.closeAllConnections();
|
|
239
|
+
server.close(() => resolve());
|
|
240
|
+
});
|
|
241
|
+
await store.close?.();
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
246
|
+
0 && (module.exports = {
|
|
247
|
+
createReqrayServer
|
|
248
|
+
});
|
|
249
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_supports-color@7.2.0_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["/**\n * `@reqray/server` — the collector.\n *\n * A separate process: applications ship batches over HTTP (see\n * `@reqray/transport-http`), the collector stores them and serves the same\n * panel the in-process adapters do. Bare `node:http` on purpose — a collector\n * needs no router or plugins, and every dependency is somebody else's risk.\n *\n * Security model: with no token the server listens on loopback only, exactly\n * like local development. A token makes it reachable from outside: ingest\n * requires it in the `authorization` header, and the panel is opened in a\n * browser through `/auth?token=…`, which sets an HttpOnly cookie.\n */\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { once } from 'node:events';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport {\n isLocalRequest,\n type PanelGate,\n type RecordedRequest,\n resolveOptions,\n retentionPolicy,\n type Transport,\n warnOnce,\n} from '@reqray/core';\nimport { createPanelHandler, type PanelSource } from '@reqray/core/panel';\nimport { memoryTransport } from '@reqray/store-memory';\nimport { sqliteTransport } from '@reqray/store-sqlite';\nimport { fileTransport } from '@reqray/transport-file';\n\n/** Options for {@link createReqrayServer}. */\nexport interface ReqrayServerOptions {\n /** Port. `0` picks a free one. */\n readonly port?: number;\n /**\n * Address to bind. Defaults to loopback; anything wider requires a token —\n * the collector shows request bodies and SQL to whoever reaches it.\n */\n readonly host?: string;\n /** Shared secret: required in ingest headers and for panel access. */\n readonly token?: string;\n /** How many requests the collector keeps. */\n readonly bufferSize?: number;\n /**\n * Path to a SQLite file. Given one, the collector keeps a history that\n * outlives it; without one, requests live in memory and die with the\n * process.\n */\n readonly db?: string;\n /** With `db`: how much disk the stored requests may take, bytes. */\n readonly maxBytes?: number;\n /**\n * Directory for the request log: one line of JSON per request, a file per\n * day. Without it the collector keeps requests only in its store.\n */\n readonly logDir?: string;\n /**\n * How many days anything is kept for — the store and the log alike.\n *\n * Changeable from the panel, and remembered next to the database so the\n * change survives a restart.\n */\n readonly retentionDays?: number;\n}\n\n/**\n * What the collector needs from a store, whichever one it is.\n *\n * Structural rather than a named union: the memory ring and the SQLite\n * history have nothing in common but this, and the collector uses nothing\n * else.\n */\nexport type CollectorStore = PanelSource &\n Transport & {\n stats(): { size: number };\n close?(): Promise<void>;\n };\n\n/** A running collector. */\nexport interface ReqrayServer {\n /** Address the server actually listens on. */\n readonly url: string;\n /** The store — exposed for tests and embedding. */\n readonly store: CollectorStore;\n close(): Promise<void>;\n}\n\nconst COOKIE_NAME = 'reqray_token';\nconst MAX_INGEST_BYTES = 32 * 1024 * 1024;\n/**\n * How many batches may be on their way in at once.\n *\n * Each is held whole in memory until it is parsed, so this is the collector's\n * memory bound — eight of the largest is 256 MB. Past it the answer is 429\n * with `Retry-After`, which the transport honours: a collector that can only\n * fall over takes the agents' queues down with it.\n */\nconst MAX_CONCURRENT_INGESTS = 8;\n\n/** Directory with the built dashboard, when it is installed. */\nfunction dashboardAssets(): string | undefined {\n try {\n const manifest = createRequire(import.meta.url).resolve('@reqray/dashboard/package.json');\n return join(dirname(manifest), 'dist');\n } catch {\n return undefined;\n }\n}\n\n/** Constant-time comparison: a token check must not leak length or prefix. */\nfunction tokenMatches(expected: string, presented: string | undefined): boolean {\n if (!presented) return false;\n const a = Buffer.from(expected);\n const b = Buffer.from(presented);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\nfunction cookieValue(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\nfunction bearerToken(header: string | undefined): string | undefined {\n if (!header) return undefined;\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined;\n}\n\n/**\n * The token in the cookie is not the token itself but a per-process session\n * value issued by `/auth`: cookies leak far more easily than the secret\n * should.\n */\nfunction issueSession(): string {\n return randomBytes(24).toString('base64url');\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/** Light shape check: one malformed record must not poison the panel. */\nfunction isIngestible(value: unknown): value is RecordedRequest {\n const record = value as Partial<RecordedRequest> | null;\n return (\n typeof record === 'object' &&\n record !== null &&\n typeof record.id === 'string' &&\n typeof record.method === 'string' &&\n typeof record.path === 'string' &&\n typeof record.status === 'number' &&\n typeof record.durationMs === 'number' &&\n typeof record.startedAt === 'number' &&\n Array.isArray(record.spans) &&\n Array.isArray(record.findings) &&\n Array.isArray(record.logs)\n );\n}\n\nasync function readBody(request: IncomingMessage): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > MAX_INGEST_BYTES) throw new Error('batch larger than 32 MB');\n chunks.push(buffer);\n }\n return Buffer.concat(chunks);\n}\n\n/** Starts the collector. Resolves once it is listening. */\nexport async function createReqrayServer(options: ReqrayServerOptions = {}): Promise<ReqrayServer> {\n const token = options.token;\n const host = options.host ?? '127.0.0.1';\n\n if (!token && host !== '127.0.0.1' && host !== 'localhost') {\n throw new Error(\n `reqray-server: listening on ${host} without a token is not allowed — the panel exposes request bodies and SQL. ` +\n 'Set a token or keep 127.0.0.1.',\n );\n }\n\n // One policy for the store and the log, remembered beside whichever of them\n // is on disk: a collector restarted by an orchestrator must come back with\n // the setting somebody chose, not the one that was compiled in.\n const remembered = options.db\n ? `${options.db}.retention.json`\n : options.logDir\n ? join(options.logDir, 'retention.json')\n : undefined;\n const retention =\n options.retentionDays || remembered\n ? retentionPolicy({\n ...(options.retentionDays ? { days: options.retentionDays } : {}),\n ...(options.bufferSize ? { maxRequests: options.bufferSize } : {}),\n ...(options.maxBytes ? { maxBytes: options.maxBytes } : {}),\n ...(remembered ? { file: remembered } : {}),\n })\n : null;\n\n // A file means a history; no file means the ring, which is what a\n // throwaway staging stand wants and what the collector has always been.\n const store: CollectorStore = options.db\n ? sqliteTransport({\n file: options.db,\n ...(options.bufferSize ? { maxRequests: options.bufferSize } : {}),\n ...(options.maxBytes ? { maxBytes: options.maxBytes } : {}),\n ...(retention ? { retention } : {}),\n })\n : memoryTransport({ capacity: options.bufferSize ?? 2_000 });\n\n // The log is beside the store, not instead of it: one is what the panel\n // reads, the other is what a log shipper picks up and an operator keeps.\n const log = options.logDir\n ? fileTransport({ dir: options.logDir, ...(retention ? { retention } : {}) })\n : null;\n const sessions = new Set<string>();\n /** Batches being read right now. */\n let ingesting = 0;\n\n // The panel is authorized either by the cookie session issued at /auth or\n // by the raw token in a header — the latter for curl and healthchecks.\n //\n // Without a token there is no gate at all, and core then lets in only what\n // comes from this machine addressed to this machine — `'open'` here used to\n // let a hostile page re-pointed at 127.0.0.1 read every recorded body.\n const gate: PanelGate | undefined = token\n ? (context) => {\n const cookie = cookieValue(\n typeof context.headers.cookie === 'string' ? context.headers.cookie : undefined,\n COOKIE_NAME,\n );\n if (cookie && sessions.has(cookie)) return true;\n const header = context.headers['x-reqray-token'];\n return typeof header === 'string' && tokenMatches(token, header);\n }\n : undefined;\n\n const panel = createPanelHandler({\n source: store,\n // The collector itself is not the application: nothing is sampled here\n // and replay is impossible — the process the request lived in is remote.\n options: resolveOptions({\n enabled: true,\n mode: 'production',\n replay: false,\n panel: gate ? { gate } : {},\n ...(retention ? { retention } : {}),\n ...(log ? { requestLog: log } : {}),\n }),\n assetsDir: dashboardAssets(),\n });\n\n const server: Server = createServer((request, response) => {\n void handle(request, response).catch((error) => {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('server.handle', `collector failed to handle a request: ${reason}`);\n if (!response.headersSent) sendJson(response, 500, { error: reason });\n else response.end();\n });\n });\n\n async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {\n const url = new URL(request.url ?? '/', 'http://reqray.local');\n\n if (url.pathname === '/healthz') {\n sendJson(response, 200, { ok: true, size: store.stats().size });\n return;\n }\n\n // No token: the whole collector is for this machine only, the same rule\n // the panel follows without a gate.\n if (\n !token &&\n !isLocalRequest({ headers: request.headers, ip: request.socket.remoteAddress ?? null })\n ) {\n sendJson(response, 403, {\n error: 'without a token the collector answers only to this machine, at a local address',\n });\n return;\n }\n\n if (url.pathname === '/ingest' && request.method === 'POST') {\n if (token && !tokenMatches(token, bearerToken(request.headers.authorization))) {\n sendJson(response, 401, { error: 'token required: authorization: Bearer <token>' });\n return;\n }\n // A page in a browser can POST text to a local port without asking;\n // it cannot send JSON without a preflight, which nothing here answers.\n if (!/^application\\/json\\b/i.test(request.headers['content-type'] ?? '')) {\n sendJson(response, 415, { error: 'a batch is sent as application/json' });\n return;\n }\n\n if (ingesting >= MAX_CONCURRENT_INGESTS) {\n // The body is not read, so the connection cannot be reused.\n response.writeHead(429, { 'retry-after': '1', connection: 'close' });\n response.end();\n return;\n }\n\n let payload: { requests?: unknown };\n ingesting++;\n try {\n payload = JSON.parse((await readBody(request)).toString('utf8')) as { requests?: unknown };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `batch not parsed: ${reason}` });\n return;\n } finally {\n ingesting--;\n }\n\n const items = Array.isArray(payload.requests) ? payload.requests : [];\n let accepted = 0;\n for (const item of items) {\n if (!isIngestible(item)) continue;\n store.send(item);\n log?.send(item);\n accepted++;\n }\n if (accepted < items.length) {\n warnOnce(\n 'server.ingest',\n `malformed records dropped from the batch: ${items.length - accepted}`,\n );\n }\n sendJson(response, 200, { accepted });\n return;\n }\n\n if (url.pathname === '/auth' && token) {\n if (!tokenMatches(token, url.searchParams.get('token') ?? undefined)) {\n sendJson(response, 403, { error: 'invalid token' });\n return;\n }\n const session = issueSession();\n sessions.add(session);\n response.writeHead(302, {\n 'set-cookie': `${COOKIE_NAME}=${session}; HttpOnly; Path=/; SameSite=Strict`,\n location: '/_reqray/',\n });\n response.end();\n return;\n }\n\n if (panel?.(request, response)) return;\n\n if (url.pathname === '/') {\n response.writeHead(302, { location: '/_reqray/' });\n response.end();\n return;\n }\n\n sendJson(response, 404, { error: 'no such path. Panel: /_reqray/, ingest: POST /ingest' });\n }\n\n server.listen(options.port ?? 4300, host);\n await once(server, 'listening');\n const address = server.address() as AddressInfo;\n\n return {\n url: `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${address.port}`,\n store,\n close: async () => {\n await new Promise<void>((resolve) => {\n server.closeAllConnections();\n server.close(() => resolve());\n });\n // A history holds a file open; the ring has nothing to release.\n await store.close?.();\n },\n };\n}\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAA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UAAU,KAAK,EAAE,OAAO,uDAAuD,CAAC;AAAA,EAC3F;AAEA,SAAO,OAAO,QAAQ,QAAQ,MAAM,IAAI;AACxC,YAAM,yBAAK,QAAQ,WAAW;AAC9B,QAAM,UAAU,OAAO,QAAQ;AAE/B,SAAO;AAAA,IACL,KAAK,UAAU,SAAS,YAAY,cAAc,IAAI,IAAI,QAAQ,IAAI;AAAA,IACtE;AAAA,IACA,OAAO,YAAY;AACjB,YAAM,IAAI,QAAc,CAAC,YAAY;AACnC,eAAO,oBAAoB;AAC3B,eAAO,MAAM,MAAM,QAAQ,CAAC;AAAA,MAC9B,CAAC;AAED,YAAM,MAAM,QAAQ;AAAA,IACtB;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Transport } from '@reqray/core';
|
|
2
|
+
import { PanelSource } from '@reqray/core/panel';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `@reqray/server` — the collector.
|
|
6
|
+
*
|
|
7
|
+
* A separate process: applications ship batches over HTTP (see
|
|
8
|
+
* `@reqray/transport-http`), the collector stores them and serves the same
|
|
9
|
+
* panel the in-process adapters do. Bare `node:http` on purpose — a collector
|
|
10
|
+
* needs no router or plugins, and every dependency is somebody else's risk.
|
|
11
|
+
*
|
|
12
|
+
* Security model: with no token the server listens on loopback only, exactly
|
|
13
|
+
* like local development. A token makes it reachable from outside: ingest
|
|
14
|
+
* requires it in the `authorization` header, and the panel is opened in a
|
|
15
|
+
* browser through `/auth?token=…`, which sets an HttpOnly cookie.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Options for {@link createReqrayServer}. */
|
|
19
|
+
interface ReqrayServerOptions {
|
|
20
|
+
/** Port. `0` picks a free one. */
|
|
21
|
+
readonly port?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Address to bind. Defaults to loopback; anything wider requires a token —
|
|
24
|
+
* the collector shows request bodies and SQL to whoever reaches it.
|
|
25
|
+
*/
|
|
26
|
+
readonly host?: string;
|
|
27
|
+
/** Shared secret: required in ingest headers and for panel access. */
|
|
28
|
+
readonly token?: string;
|
|
29
|
+
/** How many requests the collector keeps. */
|
|
30
|
+
readonly bufferSize?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Path to a SQLite file. Given one, the collector keeps a history that
|
|
33
|
+
* outlives it; without one, requests live in memory and die with the
|
|
34
|
+
* process.
|
|
35
|
+
*/
|
|
36
|
+
readonly db?: string;
|
|
37
|
+
/** With `db`: how much disk the stored requests may take, bytes. */
|
|
38
|
+
readonly maxBytes?: number;
|
|
39
|
+
/**
|
|
40
|
+
* Directory for the request log: one line of JSON per request, a file per
|
|
41
|
+
* day. Without it the collector keeps requests only in its store.
|
|
42
|
+
*/
|
|
43
|
+
readonly logDir?: string;
|
|
44
|
+
/**
|
|
45
|
+
* How many days anything is kept for — the store and the log alike.
|
|
46
|
+
*
|
|
47
|
+
* Changeable from the panel, and remembered next to the database so the
|
|
48
|
+
* change survives a restart.
|
|
49
|
+
*/
|
|
50
|
+
readonly retentionDays?: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* What the collector needs from a store, whichever one it is.
|
|
54
|
+
*
|
|
55
|
+
* Structural rather than a named union: the memory ring and the SQLite
|
|
56
|
+
* history have nothing in common but this, and the collector uses nothing
|
|
57
|
+
* else.
|
|
58
|
+
*/
|
|
59
|
+
type CollectorStore = PanelSource & Transport & {
|
|
60
|
+
stats(): {
|
|
61
|
+
size: number;
|
|
62
|
+
};
|
|
63
|
+
close?(): Promise<void>;
|
|
64
|
+
};
|
|
65
|
+
/** A running collector. */
|
|
66
|
+
interface ReqrayServer {
|
|
67
|
+
/** Address the server actually listens on. */
|
|
68
|
+
readonly url: string;
|
|
69
|
+
/** The store — exposed for tests and embedding. */
|
|
70
|
+
readonly store: CollectorStore;
|
|
71
|
+
close(): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
/** Starts the collector. Resolves once it is listening. */
|
|
74
|
+
declare function createReqrayServer(options?: ReqrayServerOptions): Promise<ReqrayServer>;
|
|
75
|
+
|
|
76
|
+
export { type CollectorStore, type ReqrayServer, type ReqrayServerOptions, createReqrayServer };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { Transport } from '@reqray/core';
|
|
2
|
+
import { PanelSource } from '@reqray/core/panel';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `@reqray/server` — the collector.
|
|
6
|
+
*
|
|
7
|
+
* A separate process: applications ship batches over HTTP (see
|
|
8
|
+
* `@reqray/transport-http`), the collector stores them and serves the same
|
|
9
|
+
* panel the in-process adapters do. Bare `node:http` on purpose — a collector
|
|
10
|
+
* needs no router or plugins, and every dependency is somebody else's risk.
|
|
11
|
+
*
|
|
12
|
+
* Security model: with no token the server listens on loopback only, exactly
|
|
13
|
+
* like local development. A token makes it reachable from outside: ingest
|
|
14
|
+
* requires it in the `authorization` header, and the panel is opened in a
|
|
15
|
+
* browser through `/auth?token=…`, which sets an HttpOnly cookie.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Options for {@link createReqrayServer}. */
|
|
19
|
+
interface ReqrayServerOptions {
|
|
20
|
+
/** Port. `0` picks a free one. */
|
|
21
|
+
readonly port?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Address to bind. Defaults to loopback; anything wider requires a token —
|
|
24
|
+
* the collector shows request bodies and SQL to whoever reaches it.
|
|
25
|
+
*/
|
|
26
|
+
readonly host?: string;
|
|
27
|
+
/** Shared secret: required in ingest headers and for panel access. */
|
|
28
|
+
readonly token?: string;
|
|
29
|
+
/** How many requests the collector keeps. */
|
|
30
|
+
readonly bufferSize?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Path to a SQLite file. Given one, the collector keeps a history that
|
|
33
|
+
* outlives it; without one, requests live in memory and die with the
|
|
34
|
+
* process.
|
|
35
|
+
*/
|
|
36
|
+
readonly db?: string;
|
|
37
|
+
/** With `db`: how much disk the stored requests may take, bytes. */
|
|
38
|
+
readonly maxBytes?: number;
|
|
39
|
+
/**
|
|
40
|
+
* Directory for the request log: one line of JSON per request, a file per
|
|
41
|
+
* day. Without it the collector keeps requests only in its store.
|
|
42
|
+
*/
|
|
43
|
+
readonly logDir?: string;
|
|
44
|
+
/**
|
|
45
|
+
* How many days anything is kept for — the store and the log alike.
|
|
46
|
+
*
|
|
47
|
+
* Changeable from the panel, and remembered next to the database so the
|
|
48
|
+
* change survives a restart.
|
|
49
|
+
*/
|
|
50
|
+
readonly retentionDays?: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* What the collector needs from a store, whichever one it is.
|
|
54
|
+
*
|
|
55
|
+
* Structural rather than a named union: the memory ring and the SQLite
|
|
56
|
+
* history have nothing in common but this, and the collector uses nothing
|
|
57
|
+
* else.
|
|
58
|
+
*/
|
|
59
|
+
type CollectorStore = PanelSource & Transport & {
|
|
60
|
+
stats(): {
|
|
61
|
+
size: number;
|
|
62
|
+
};
|
|
63
|
+
close?(): Promise<void>;
|
|
64
|
+
};
|
|
65
|
+
/** A running collector. */
|
|
66
|
+
interface ReqrayServer {
|
|
67
|
+
/** Address the server actually listens on. */
|
|
68
|
+
readonly url: string;
|
|
69
|
+
/** The store — exposed for tests and embedding. */
|
|
70
|
+
readonly store: CollectorStore;
|
|
71
|
+
close(): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
/** Starts the collector. Resolves once it is listening. */
|
|
74
|
+
declare function createReqrayServer(options?: ReqrayServerOptions): Promise<ReqrayServer>;
|
|
75
|
+
|
|
76
|
+
export { type CollectorStore, type ReqrayServer, type ReqrayServerOptions, createReqrayServer };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { randomBytes, timingSafeEqual } from "crypto";
|
|
3
|
+
import { once } from "events";
|
|
4
|
+
import { createServer } from "http";
|
|
5
|
+
import { createRequire } from "module";
|
|
6
|
+
import { dirname, join } from "path";
|
|
7
|
+
import {
|
|
8
|
+
isLocalRequest,
|
|
9
|
+
resolveOptions,
|
|
10
|
+
retentionPolicy,
|
|
11
|
+
warnOnce
|
|
12
|
+
} from "@reqray/core";
|
|
13
|
+
import { createPanelHandler } from "@reqray/core/panel";
|
|
14
|
+
import { memoryTransport } from "@reqray/store-memory";
|
|
15
|
+
import { sqliteTransport } from "@reqray/store-sqlite";
|
|
16
|
+
import { fileTransport } from "@reqray/transport-file";
|
|
17
|
+
var COOKIE_NAME = "reqray_token";
|
|
18
|
+
var MAX_INGEST_BYTES = 32 * 1024 * 1024;
|
|
19
|
+
var MAX_CONCURRENT_INGESTS = 8;
|
|
20
|
+
function dashboardAssets() {
|
|
21
|
+
try {
|
|
22
|
+
const manifest = createRequire(import.meta.url).resolve("@reqray/dashboard/package.json");
|
|
23
|
+
return join(dirname(manifest), "dist");
|
|
24
|
+
} catch {
|
|
25
|
+
return void 0;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function tokenMatches(expected, presented) {
|
|
29
|
+
if (!presented) return false;
|
|
30
|
+
const a = Buffer.from(expected);
|
|
31
|
+
const b = Buffer.from(presented);
|
|
32
|
+
if (a.length !== b.length) return false;
|
|
33
|
+
return timingSafeEqual(a, b);
|
|
34
|
+
}
|
|
35
|
+
function cookieValue(header, name) {
|
|
36
|
+
if (!header) return void 0;
|
|
37
|
+
for (const part of header.split(";")) {
|
|
38
|
+
const eq = part.indexOf("=");
|
|
39
|
+
if (eq === -1) continue;
|
|
40
|
+
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
|
|
41
|
+
}
|
|
42
|
+
return void 0;
|
|
43
|
+
}
|
|
44
|
+
function bearerToken(header) {
|
|
45
|
+
if (!header) return void 0;
|
|
46
|
+
return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : void 0;
|
|
47
|
+
}
|
|
48
|
+
function issueSession() {
|
|
49
|
+
return randomBytes(24).toString("base64url");
|
|
50
|
+
}
|
|
51
|
+
function sendJson(response, status, payload) {
|
|
52
|
+
const body = JSON.stringify(payload);
|
|
53
|
+
response.writeHead(status, {
|
|
54
|
+
"content-type": "application/json; charset=utf-8",
|
|
55
|
+
"content-length": Buffer.byteLength(body)
|
|
56
|
+
});
|
|
57
|
+
response.end(body);
|
|
58
|
+
}
|
|
59
|
+
function isIngestible(value) {
|
|
60
|
+
const record = value;
|
|
61
|
+
return typeof record === "object" && record !== null && typeof record.id === "string" && typeof record.method === "string" && typeof record.path === "string" && typeof record.status === "number" && typeof record.durationMs === "number" && typeof record.startedAt === "number" && Array.isArray(record.spans) && Array.isArray(record.findings) && Array.isArray(record.logs);
|
|
62
|
+
}
|
|
63
|
+
async function readBody(request) {
|
|
64
|
+
const chunks = [];
|
|
65
|
+
let size = 0;
|
|
66
|
+
for await (const chunk of request) {
|
|
67
|
+
const buffer = chunk;
|
|
68
|
+
size += buffer.length;
|
|
69
|
+
if (size > MAX_INGEST_BYTES) throw new Error("batch larger than 32 MB");
|
|
70
|
+
chunks.push(buffer);
|
|
71
|
+
}
|
|
72
|
+
return Buffer.concat(chunks);
|
|
73
|
+
}
|
|
74
|
+
async function createReqrayServer(options = {}) {
|
|
75
|
+
const token = options.token;
|
|
76
|
+
const host = options.host ?? "127.0.0.1";
|
|
77
|
+
if (!token && host !== "127.0.0.1" && host !== "localhost") {
|
|
78
|
+
throw new Error(
|
|
79
|
+
`reqray-server: listening on ${host} without a token is not allowed \u2014 the panel exposes request bodies and SQL. Set a token or keep 127.0.0.1.`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
const remembered = options.db ? `${options.db}.retention.json` : options.logDir ? join(options.logDir, "retention.json") : void 0;
|
|
83
|
+
const retention = options.retentionDays || remembered ? retentionPolicy({
|
|
84
|
+
...options.retentionDays ? { days: options.retentionDays } : {},
|
|
85
|
+
...options.bufferSize ? { maxRequests: options.bufferSize } : {},
|
|
86
|
+
...options.maxBytes ? { maxBytes: options.maxBytes } : {},
|
|
87
|
+
...remembered ? { file: remembered } : {}
|
|
88
|
+
}) : null;
|
|
89
|
+
const store = options.db ? sqliteTransport({
|
|
90
|
+
file: options.db,
|
|
91
|
+
...options.bufferSize ? { maxRequests: options.bufferSize } : {},
|
|
92
|
+
...options.maxBytes ? { maxBytes: options.maxBytes } : {},
|
|
93
|
+
...retention ? { retention } : {}
|
|
94
|
+
}) : memoryTransport({ capacity: options.bufferSize ?? 2e3 });
|
|
95
|
+
const log = options.logDir ? fileTransport({ dir: options.logDir, ...retention ? { retention } : {} }) : null;
|
|
96
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
97
|
+
let ingesting = 0;
|
|
98
|
+
const gate = token ? (context) => {
|
|
99
|
+
const cookie = cookieValue(
|
|
100
|
+
typeof context.headers.cookie === "string" ? context.headers.cookie : void 0,
|
|
101
|
+
COOKIE_NAME
|
|
102
|
+
);
|
|
103
|
+
if (cookie && sessions.has(cookie)) return true;
|
|
104
|
+
const header = context.headers["x-reqray-token"];
|
|
105
|
+
return typeof header === "string" && tokenMatches(token, header);
|
|
106
|
+
} : void 0;
|
|
107
|
+
const panel = createPanelHandler({
|
|
108
|
+
source: store,
|
|
109
|
+
// The collector itself is not the application: nothing is sampled here
|
|
110
|
+
// and replay is impossible — the process the request lived in is remote.
|
|
111
|
+
options: resolveOptions({
|
|
112
|
+
enabled: true,
|
|
113
|
+
mode: "production",
|
|
114
|
+
replay: false,
|
|
115
|
+
panel: gate ? { gate } : {},
|
|
116
|
+
...retention ? { retention } : {},
|
|
117
|
+
...log ? { requestLog: log } : {}
|
|
118
|
+
}),
|
|
119
|
+
assetsDir: dashboardAssets()
|
|
120
|
+
});
|
|
121
|
+
const server = createServer((request, response) => {
|
|
122
|
+
void handle(request, response).catch((error) => {
|
|
123
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
124
|
+
warnOnce("server.handle", `collector failed to handle a request: ${reason}`);
|
|
125
|
+
if (!response.headersSent) sendJson(response, 500, { error: reason });
|
|
126
|
+
else response.end();
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
async function handle(request, response) {
|
|
130
|
+
const url = new URL(request.url ?? "/", "http://reqray.local");
|
|
131
|
+
if (url.pathname === "/healthz") {
|
|
132
|
+
sendJson(response, 200, { ok: true, size: store.stats().size });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (!token && !isLocalRequest({ headers: request.headers, ip: request.socket.remoteAddress ?? null })) {
|
|
136
|
+
sendJson(response, 403, {
|
|
137
|
+
error: "without a token the collector answers only to this machine, at a local address"
|
|
138
|
+
});
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (url.pathname === "/ingest" && request.method === "POST") {
|
|
142
|
+
if (token && !tokenMatches(token, bearerToken(request.headers.authorization))) {
|
|
143
|
+
sendJson(response, 401, { error: "token required: authorization: Bearer <token>" });
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (!/^application\/json\b/i.test(request.headers["content-type"] ?? "")) {
|
|
147
|
+
sendJson(response, 415, { error: "a batch is sent as application/json" });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (ingesting >= MAX_CONCURRENT_INGESTS) {
|
|
151
|
+
response.writeHead(429, { "retry-after": "1", connection: "close" });
|
|
152
|
+
response.end();
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
let payload;
|
|
156
|
+
ingesting++;
|
|
157
|
+
try {
|
|
158
|
+
payload = JSON.parse((await readBody(request)).toString("utf8"));
|
|
159
|
+
} catch (error) {
|
|
160
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
161
|
+
sendJson(response, 400, { error: `batch not parsed: ${reason}` });
|
|
162
|
+
return;
|
|
163
|
+
} finally {
|
|
164
|
+
ingesting--;
|
|
165
|
+
}
|
|
166
|
+
const items = Array.isArray(payload.requests) ? payload.requests : [];
|
|
167
|
+
let accepted = 0;
|
|
168
|
+
for (const item of items) {
|
|
169
|
+
if (!isIngestible(item)) continue;
|
|
170
|
+
store.send(item);
|
|
171
|
+
log?.send(item);
|
|
172
|
+
accepted++;
|
|
173
|
+
}
|
|
174
|
+
if (accepted < items.length) {
|
|
175
|
+
warnOnce(
|
|
176
|
+
"server.ingest",
|
|
177
|
+
`malformed records dropped from the batch: ${items.length - accepted}`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
sendJson(response, 200, { accepted });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (url.pathname === "/auth" && token) {
|
|
184
|
+
if (!tokenMatches(token, url.searchParams.get("token") ?? void 0)) {
|
|
185
|
+
sendJson(response, 403, { error: "invalid token" });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const session = issueSession();
|
|
189
|
+
sessions.add(session);
|
|
190
|
+
response.writeHead(302, {
|
|
191
|
+
"set-cookie": `${COOKIE_NAME}=${session}; HttpOnly; Path=/; SameSite=Strict`,
|
|
192
|
+
location: "/_reqray/"
|
|
193
|
+
});
|
|
194
|
+
response.end();
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (panel?.(request, response)) return;
|
|
198
|
+
if (url.pathname === "/") {
|
|
199
|
+
response.writeHead(302, { location: "/_reqray/" });
|
|
200
|
+
response.end();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
sendJson(response, 404, { error: "no such path. Panel: /_reqray/, ingest: POST /ingest" });
|
|
204
|
+
}
|
|
205
|
+
server.listen(options.port ?? 4300, host);
|
|
206
|
+
await once(server, "listening");
|
|
207
|
+
const address = server.address();
|
|
208
|
+
return {
|
|
209
|
+
url: `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${address.port}`,
|
|
210
|
+
store,
|
|
211
|
+
close: async () => {
|
|
212
|
+
await new Promise((resolve) => {
|
|
213
|
+
server.closeAllConnections();
|
|
214
|
+
server.close(() => resolve());
|
|
215
|
+
});
|
|
216
|
+
await store.close?.();
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
export {
|
|
221
|
+
createReqrayServer
|
|
222
|
+
};
|
|
223
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@reqray/server` — the collector.\n *\n * A separate process: applications ship batches over HTTP (see\n * `@reqray/transport-http`), the collector stores them and serves the same\n * panel the in-process adapters do. Bare `node:http` on purpose — a collector\n * needs no router or plugins, and every dependency is somebody else's risk.\n *\n * Security model: with no token the server listens on loopback only, exactly\n * like local development. A token makes it reachable from outside: ingest\n * requires it in the `authorization` header, and the panel is opened in a\n * browser through `/auth?token=…`, which sets an HttpOnly cookie.\n */\n\nimport { randomBytes, timingSafeEqual } from 'node:crypto';\nimport { once } from 'node:events';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport { createRequire } from 'node:module';\nimport type { AddressInfo } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport {\n isLocalRequest,\n type PanelGate,\n type RecordedRequest,\n resolveOptions,\n retentionPolicy,\n type Transport,\n warnOnce,\n} from '@reqray/core';\nimport { createPanelHandler, type PanelSource } from '@reqray/core/panel';\nimport { memoryTransport } from '@reqray/store-memory';\nimport { sqliteTransport } from '@reqray/store-sqlite';\nimport { fileTransport } from '@reqray/transport-file';\n\n/** Options for {@link createReqrayServer}. */\nexport interface ReqrayServerOptions {\n /** Port. `0` picks a free one. */\n readonly port?: number;\n /**\n * Address to bind. Defaults to loopback; anything wider requires a token —\n * the collector shows request bodies and SQL to whoever reaches it.\n */\n readonly host?: string;\n /** Shared secret: required in ingest headers and for panel access. */\n readonly token?: string;\n /** How many requests the collector keeps. */\n readonly bufferSize?: number;\n /**\n * Path to a SQLite file. Given one, the collector keeps a history that\n * outlives it; without one, requests live in memory and die with the\n * process.\n */\n readonly db?: string;\n /** With `db`: how much disk the stored requests may take, bytes. */\n readonly maxBytes?: number;\n /**\n * Directory for the request log: one line of JSON per request, a file per\n * day. Without it the collector keeps requests only in its store.\n */\n readonly logDir?: string;\n /**\n * How many days anything is kept for — the store and the log alike.\n *\n * Changeable from the panel, and remembered next to the database so the\n * change survives a restart.\n */\n readonly retentionDays?: number;\n}\n\n/**\n * What the collector needs from a store, whichever one it is.\n *\n * Structural rather than a named union: the memory ring and the SQLite\n * history have nothing in common but this, and the collector uses nothing\n * else.\n */\nexport type CollectorStore = PanelSource &\n Transport & {\n stats(): { size: number };\n close?(): Promise<void>;\n };\n\n/** A running collector. */\nexport interface ReqrayServer {\n /** Address the server actually listens on. */\n readonly url: string;\n /** The store — exposed for tests and embedding. */\n readonly store: CollectorStore;\n close(): Promise<void>;\n}\n\nconst COOKIE_NAME = 'reqray_token';\nconst MAX_INGEST_BYTES = 32 * 1024 * 1024;\n/**\n * How many batches may be on their way in at once.\n *\n * Each is held whole in memory until it is parsed, so this is the collector's\n * memory bound — eight of the largest is 256 MB. Past it the answer is 429\n * with `Retry-After`, which the transport honours: a collector that can only\n * fall over takes the agents' queues down with it.\n */\nconst MAX_CONCURRENT_INGESTS = 8;\n\n/** Directory with the built dashboard, when it is installed. */\nfunction dashboardAssets(): string | undefined {\n try {\n const manifest = createRequire(import.meta.url).resolve('@reqray/dashboard/package.json');\n return join(dirname(manifest), 'dist');\n } catch {\n return undefined;\n }\n}\n\n/** Constant-time comparison: a token check must not leak length or prefix. */\nfunction tokenMatches(expected: string, presented: string | undefined): boolean {\n if (!presented) return false;\n const a = Buffer.from(expected);\n const b = Buffer.from(presented);\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n\nfunction cookieValue(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\nfunction bearerToken(header: string | undefined): string | undefined {\n if (!header) return undefined;\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined;\n}\n\n/**\n * The token in the cookie is not the token itself but a per-process session\n * value issued by `/auth`: cookies leak far more easily than the secret\n * should.\n */\nfunction issueSession(): string {\n return randomBytes(24).toString('base64url');\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/** Light shape check: one malformed record must not poison the panel. */\nfunction isIngestible(value: unknown): value is RecordedRequest {\n const record = value as Partial<RecordedRequest> | null;\n return (\n typeof record === 'object' &&\n record !== null &&\n typeof record.id === 'string' &&\n typeof record.method === 'string' &&\n typeof record.path === 'string' &&\n typeof record.status === 'number' &&\n typeof record.durationMs === 'number' &&\n typeof record.startedAt === 'number' &&\n Array.isArray(record.spans) &&\n Array.isArray(record.findings) &&\n Array.isArray(record.logs)\n );\n}\n\nasync function readBody(request: IncomingMessage): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > MAX_INGEST_BYTES) throw new Error('batch larger than 32 MB');\n chunks.push(buffer);\n }\n return Buffer.concat(chunks);\n}\n\n/** Starts the collector. Resolves once it is listening. */\nexport async function createReqrayServer(options: ReqrayServerOptions = {}): Promise<ReqrayServer> {\n const token = options.token;\n const host = options.host ?? '127.0.0.1';\n\n if (!token && host !== '127.0.0.1' && host !== 'localhost') {\n throw new Error(\n `reqray-server: listening on ${host} without a token is not allowed — the panel exposes request bodies and SQL. ` +\n 'Set a token or keep 127.0.0.1.',\n );\n }\n\n // One policy for the store and the log, remembered beside whichever of them\n // is on disk: a collector restarted by an orchestrator must come back with\n // the setting somebody chose, not the one that was compiled in.\n const remembered = options.db\n ? `${options.db}.retention.json`\n : options.logDir\n ? join(options.logDir, 'retention.json')\n : undefined;\n const retention =\n options.retentionDays || remembered\n ? retentionPolicy({\n ...(options.retentionDays ? { days: options.retentionDays } : {}),\n ...(options.bufferSize ? { maxRequests: options.bufferSize } : {}),\n ...(options.maxBytes ? { maxBytes: options.maxBytes } : {}),\n ...(remembered ? { file: remembered } : {}),\n })\n : null;\n\n // A file means a history; no file means the ring, which is what a\n // throwaway staging stand wants and what the collector has always been.\n const store: CollectorStore = options.db\n ? sqliteTransport({\n file: options.db,\n ...(options.bufferSize ? { maxRequests: options.bufferSize } : {}),\n ...(options.maxBytes ? { maxBytes: options.maxBytes } : {}),\n ...(retention ? { retention } : {}),\n })\n : memoryTransport({ capacity: options.bufferSize ?? 2_000 });\n\n // The log is beside the store, not instead of it: one is what the panel\n // reads, the other is what a log shipper picks up and an operator keeps.\n const log = options.logDir\n ? fileTransport({ dir: options.logDir, ...(retention ? { retention } : {}) })\n : null;\n const sessions = new Set<string>();\n /** Batches being read right now. */\n let ingesting = 0;\n\n // The panel is authorized either by the cookie session issued at /auth or\n // by the raw token in a header — the latter for curl and healthchecks.\n //\n // Without a token there is no gate at all, and core then lets in only what\n // comes from this machine addressed to this machine — `'open'` here used to\n // let a hostile page re-pointed at 127.0.0.1 read every recorded body.\n const gate: PanelGate | undefined = token\n ? (context) => {\n const cookie = cookieValue(\n typeof context.headers.cookie === 'string' ? context.headers.cookie : undefined,\n COOKIE_NAME,\n );\n if (cookie && sessions.has(cookie)) return true;\n const header = context.headers['x-reqray-token'];\n return typeof header === 'string' && tokenMatches(token, header);\n }\n : undefined;\n\n const panel = createPanelHandler({\n source: store,\n // The collector itself is not the application: nothing is sampled here\n // and replay is impossible — the process the request lived in is remote.\n options: resolveOptions({\n enabled: true,\n mode: 'production',\n replay: false,\n panel: gate ? { gate } : {},\n ...(retention ? { retention } : {}),\n ...(log ? { requestLog: log } : {}),\n }),\n assetsDir: dashboardAssets(),\n });\n\n const server: Server = createServer((request, response) => {\n void handle(request, response).catch((error) => {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('server.handle', `collector failed to handle a request: ${reason}`);\n if (!response.headersSent) sendJson(response, 500, { error: reason });\n else response.end();\n });\n });\n\n async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {\n const url = new URL(request.url ?? '/', 'http://reqray.local');\n\n if (url.pathname === '/healthz') {\n sendJson(response, 200, { ok: true, size: store.stats().size });\n return;\n }\n\n // No token: the whole collector is for this machine only, the same rule\n // the panel follows without a gate.\n if (\n !token &&\n !isLocalRequest({ headers: request.headers, ip: request.socket.remoteAddress ?? null })\n ) {\n sendJson(response, 403, {\n error: 'without a token the collector answers only to this machine, at a local address',\n });\n return;\n }\n\n if (url.pathname === '/ingest' && request.method === 'POST') {\n if (token && !tokenMatches(token, bearerToken(request.headers.authorization))) {\n sendJson(response, 401, { error: 'token required: authorization: Bearer <token>' });\n return;\n }\n // A page in a browser can POST text to a local port without asking;\n // it cannot send JSON without a preflight, which nothing here answers.\n if (!/^application\\/json\\b/i.test(request.headers['content-type'] ?? '')) {\n sendJson(response, 415, { error: 'a batch is sent as application/json' });\n return;\n }\n\n if (ingesting >= MAX_CONCURRENT_INGESTS) {\n // The body is not read, so the connection cannot be reused.\n response.writeHead(429, { 'retry-after': '1', connection: 'close' });\n response.end();\n return;\n }\n\n let payload: { requests?: unknown };\n ingesting++;\n try {\n payload = JSON.parse((await readBody(request)).toString('utf8')) as { requests?: unknown };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `batch not parsed: ${reason}` });\n return;\n } finally {\n ingesting--;\n }\n\n const items = Array.isArray(payload.requests) ? payload.requests : [];\n let accepted = 0;\n for (const item of items) {\n if (!isIngestible(item)) continue;\n store.send(item);\n log?.send(item);\n accepted++;\n }\n if (accepted < items.length) {\n warnOnce(\n 'server.ingest',\n `malformed records dropped from the batch: ${items.length - accepted}`,\n );\n }\n sendJson(response, 200, { accepted });\n return;\n }\n\n if (url.pathname === '/auth' && token) {\n if (!tokenMatches(token, url.searchParams.get('token') ?? undefined)) {\n sendJson(response, 403, { error: 'invalid token' });\n return;\n }\n const session = issueSession();\n sessions.add(session);\n response.writeHead(302, {\n 'set-cookie': `${COOKIE_NAME}=${session}; HttpOnly; Path=/; SameSite=Strict`,\n location: '/_reqray/',\n });\n response.end();\n return;\n }\n\n if (panel?.(request, response)) return;\n\n if (url.pathname === '/') {\n response.writeHead(302, { location: '/_reqray/' });\n response.end();\n return;\n }\n\n sendJson(response, 404, { error: 'no such path. Panel: /_reqray/, ingest: POST /ingest' });\n }\n\n server.listen(options.port ?? 4300, host);\n await once(server, 'listening');\n const address = server.address() as AddressInfo;\n\n return {\n url: `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${address.port}`,\n store,\n close: async () => {\n await new Promise<void>((resolve) => {\n server.closeAllConnections();\n server.close(() => resolve());\n });\n // A history holds a file open; the ring has nothing to release.\n await store.close?.();\n },\n };\n}\n"],"mappings":";AAcA,SAAS,aAAa,uBAAuB;AAC7C,SAAS,YAAY;AACrB,SAAS,oBAA4E;AACrF,SAAS,qBAAqB;AAE9B,SAAS,SAAS,YAAY;AAC9B;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,0BAA4C;AACrD,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AA2D9B,IAAM,cAAc;AACpB,IAAM,mBAAmB,KAAK,OAAO;AASrC,IAAM,yBAAyB;AAG/B,SAAS,kBAAsC;AAC7C,MAAI;AACF,UAAM,WAAW,cAAc,YAAY,GAAG,EAAE,QAAQ,gCAAgC;AACxF,WAAO,KAAK,QAAQ,QAAQ,GAAG,MAAM;AAAA,EACvC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,aAAa,UAAkB,WAAwC;AAC9E,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,IAAI,OAAO,KAAK,QAAQ;AAC9B,QAAM,IAAI,OAAO,KAAK,SAAS;AAC/B,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,SAAO,gBAAgB,GAAG,CAAC;AAC7B;AAEA,SAAS,YAAY,QAA4B,MAAkC;AACjF,MAAI,CAAC,O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C,aAAa,OAAO,IAAI,aAAa,IAAI,OAAO,KAAK,MAAS,GAAG;AACpE,iBAAS,UAAU,KAAK,EAAE,OAAO,gBAAgB,CAAC;AAClD;AAAA,MACF;AACA,YAAM,UAAU,aAAa;AAC7B,eAAS,IAAI,OAAO;AACpB,eAAS,UAAU,KAAK;AAAA,QACtB,cAAc,GAAG,WAAW,IAAI,OAAO;AAAA,QACvC,UAAU;AAAA,MACZ,CAAC;AACD,eAAS,IAAI;AACb;AAAA,IACF;AAEA,QAAI,QAAQ,SAAS,QAAQ,EAAG;AAEhC,QAAI,IAAI,aAAa,KAAK;AACxB,eAAS,UAAU,KAAK,EAAE,UAAU,YAAY,CAAC;AACjD,eAAS,IAAI;AACb;AAAA,IACF;AAEA,aAAS,UAAU,KAAK,EAAE,OAAO,uDAAuD,CAAC;AAAA,EAC3F;AAEA,SAAO,OAAO,QAAQ,QAAQ,MAAM,IAAI;AACxC,QAAM,KAAK,QAAQ,WAAW;AAC9B,QAAM,UAAU,OAAO,QAAQ;AAE/B,SAAO;AAAA,IACL,KAAK,UAAU,SAAS,YAAY,cAAc,IAAI,IAAI,QAAQ,IAAI;AAAA,IACtE;AAAA,IACA,OAAO,YAAY;AACjB,YAAM,IAAI,QAAc,CAAC,YAAY;AACnC,eAAO,oBAAoB;AAC3B,eAAO,MAAM,MAAM,QAAQ,CAAC;AAAA,MAC9B,CAAC;AAED,YAAM,MAAM,QAAQ;AAAA,IACtB;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reqray/server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Reqray collector: batch ingestion from applications, storage, and the dashboard.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"nodejs",
|
|
8
|
+
"debugging",
|
|
9
|
+
"profiling",
|
|
10
|
+
"n+1",
|
|
11
|
+
"sql",
|
|
12
|
+
"observability",
|
|
13
|
+
"devtools",
|
|
14
|
+
"fastify",
|
|
15
|
+
"express",
|
|
16
|
+
"nestjs"
|
|
17
|
+
],
|
|
18
|
+
"homepage": "https://github.com/reqray/reqray#readme",
|
|
19
|
+
"bugs": "https://github.com/reqray/reqray/issues",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/reqray/reqray.git",
|
|
23
|
+
"directory": "packages/server"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=22.5"
|
|
28
|
+
},
|
|
29
|
+
"bin": {
|
|
30
|
+
"reqray-server": "./dist/cli.js"
|
|
31
|
+
},
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"import": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/index.js"
|
|
37
|
+
},
|
|
38
|
+
"require": {
|
|
39
|
+
"types": "./dist/index.d.cts",
|
|
40
|
+
"default": "./dist/index.cjs"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"main": "./dist/index.cjs",
|
|
45
|
+
"module": "./dist/index.js",
|
|
46
|
+
"types": "./dist/index.d.ts",
|
|
47
|
+
"files": [
|
|
48
|
+
"dist"
|
|
49
|
+
],
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@reqray/core": "^0.1.1",
|
|
55
|
+
"@reqray/dashboard": "^0.1.1",
|
|
56
|
+
"@reqray/transport-file": "^0.1.1",
|
|
57
|
+
"@reqray/store-memory": "^0.1.1",
|
|
58
|
+
"@reqray/store-sqlite": "^0.1.1"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@types/node": "^26.2.0",
|
|
62
|
+
"tsup": "^8.5.1",
|
|
63
|
+
"typescript": "^6.0.3",
|
|
64
|
+
"@reqray/transport-http": "^0.1.1"
|
|
65
|
+
},
|
|
66
|
+
"scripts": {
|
|
67
|
+
"build": "tsup",
|
|
68
|
+
"typecheck": "tsc --noEmit"
|
|
69
|
+
}
|
|
6
70
|
}
|