@emeryld/rrroutes-openapi 2.3.1 → 2.3.2
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/README.md +21 -10
- package/dist/docs/LeafDocsPage.d.ts +4 -22
- package/dist/docs/docs.d.ts +5 -7
- package/dist/docs/schemaIntrospection.d.ts +1 -1
- package/dist/docs/serializer.d.ts +8 -7
- package/dist/index.cjs +430 -643
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +33 -87
- package/dist/index.mjs +433 -643
- package/dist/index.mjs.map +1 -1
- package/dist/public/assets/docs.js +260 -21
- package/dist/web/app.d.ts +1 -8
- package/dist/web/main.d.ts +1 -1
- package/dist/web/utils/grouping.d.ts +2 -8
- package/dist/web/utils/security.d.ts +21 -0
- package/dist/web/utils/types.d.ts +17 -0
- package/dist/web/v2/AppShell.d.ts +7 -0
- package/dist/web/v2/components/JsonInput.d.ts +10 -0
- package/dist/web/v2/components/JsonViewer.d.ts +12 -0
- package/dist/web/v2/components/MethodBadge.d.ts +4 -0
- package/dist/web/v2/components/New/HttpMethodChip.d.ts +7 -0
- package/dist/web/v2/components/New/ListToolBar.d.ts +11 -0
- package/dist/web/v2/components/New/MethodFiltersChips.d.ts +7 -0
- package/dist/web/v2/components/New/RequestStatusChip.d.ts +6 -0
- package/dist/web/v2/components/New/SplitPageLayout.d.ts +7 -0
- package/dist/web/v2/components/New/StabilityChip.d.ts +7 -0
- package/dist/web/v2/components/New/StatusRangeFilter.d.ts +8 -0
- package/dist/web/v2/components/RecordItem.d.ts +34 -0
- package/dist/web/v2/components/ResizableSidePanel.d.ts +12 -0
- package/dist/web/v2/components/SchemaTable.d.ts +5 -0
- package/dist/web/v2/components/SectionHeader.d.ts +9 -0
- package/dist/web/v2/endpoints/EndpointDetailsPanel.d.ts +5 -0
- package/dist/web/v2/endpoints/EndpointList.d.ts +12 -0
- package/dist/web/v2/endpoints/EndpointsPage.d.ts +1 -0
- package/dist/web/v2/endpoints/endpoints.utils.d.ts +3 -0
- package/dist/web/v2/stores/clientStore.d.ts +48 -0
- package/dist/web/v2/stores/endpointsStore.d.ts +20 -0
- package/dist/web/v2/stores/logsStore.d.ts +5 -0
- package/dist/web/v2/theme.d.ts +21 -0
- package/dist/web/v2/types/types.base.d.ts +30 -0
- package/dist/web/v2/types/types.cacheLog.d.ts +165 -0
- package/dist/web/v2/types/types.endpoint.d.ts +326 -0
- package/dist/web/v2/types/types.log.d.ts +119 -0
- package/dist/web/v2/types/types.preset.d.ts +251 -0
- package/dist/web/v2/types/types.requestLog.d.ts +264 -0
- package/package.json +15 -5
- package/dist/docs/presets.d.ts +0 -14
- package/dist/public/assets/docs.css +0 -1
- package/dist/web/components/Analytics.d.ts +0 -68
- package/dist/web/components/CopyablePre.d.ts +0 -7
- package/dist/web/components/EndpointCard.d.ts +0 -10
- package/dist/web/components/Filters.d.ts +0 -9
- package/dist/web/components/FiltersBar.d.ts +0 -25
- package/dist/web/components/HelperEnumInput.d.ts +0 -11
- package/dist/web/components/HistoryView.d.ts +0 -7
- package/dist/web/components/LogsView.d.ts +0 -1
- package/dist/web/components/PlaygroundOverlay.d.ts +0 -94
- package/dist/web/components/PresetsView.d.ts +0 -15
- package/dist/web/components/RequestLogs.d.ts +0 -10
- package/dist/web/components/SchemaTable.d.ts +0 -4
- package/dist/web/components/ui/Button.d.ts +0 -8
- package/dist/web/components/ui/Clickable.d.ts +0 -7
- package/dist/web/components/ui/Tag.d.ts +0 -9
- package/dist/web/components/ui/Text.d.ts +0 -8
- package/dist/web/components/ui/index.d.ts +0 -4
- package/dist/web/historyStore.d.ts +0 -68
- package/dist/web/logsStore.d.ts +0 -51
- package/dist/web/types.d.ts +0 -5
- package/dist/webhooks.d.ts +0 -181
package/dist/index.mjs
CHANGED
|
@@ -8,6 +8,11 @@ import { fileURLToPath } from "url";
|
|
|
8
8
|
// src/docs/LeafDocsPage.tsx
|
|
9
9
|
import { renderToStaticMarkup } from "react-dom/server";
|
|
10
10
|
|
|
11
|
+
// src/docs/serializer.ts
|
|
12
|
+
import {
|
|
13
|
+
routeSchemaParse
|
|
14
|
+
} from "@emeryld/rrroutes-contract";
|
|
15
|
+
|
|
11
16
|
// src/docs/schemaIntrospection.ts
|
|
12
17
|
import * as z from "zod";
|
|
13
18
|
function getDef(schema) {
|
|
@@ -153,10 +158,10 @@ function serializeLeaf(leaf) {
|
|
|
153
158
|
hasQuery: !!cfg.querySchema,
|
|
154
159
|
hasParams: !!cfg.paramsSchema,
|
|
155
160
|
hasOutput: !!cfg.outputSchema,
|
|
156
|
-
bodySchema: introspectSchema(cfg.bodySchema),
|
|
157
|
-
querySchema: introspectSchema(cfg.querySchema),
|
|
158
|
-
paramsSchema: introspectSchema(cfg.paramsSchema),
|
|
159
|
-
outputSchema: introspectSchema(cfg.outputSchema)
|
|
161
|
+
bodySchema: cfg.bodySchema ? introspectSchema(routeSchemaParse(cfg.bodySchema)) : void 0,
|
|
162
|
+
querySchema: cfg.querySchema ? introspectSchema(routeSchemaParse(cfg.querySchema)) : void 0,
|
|
163
|
+
paramsSchema: cfg.paramsSchema ? introspectSchema(routeSchemaParse(cfg.paramsSchema)) : void 0,
|
|
164
|
+
outputSchema: cfg.outputSchema ? introspectSchema(routeSchemaParse(cfg.outputSchema)) : void 0
|
|
160
165
|
}
|
|
161
166
|
};
|
|
162
167
|
}
|
|
@@ -173,25 +178,17 @@ function normalizeDocsBase(base) {
|
|
|
173
178
|
if (base === "/") return "/";
|
|
174
179
|
return base.endsWith("/") && base.length > 1 ? base.slice(0, -1) : base;
|
|
175
180
|
}
|
|
176
|
-
function normalizeBaseUrlSuffix(suffix) {
|
|
177
|
-
if (!suffix) return "";
|
|
178
|
-
const trimmed = suffix.endsWith("/") && suffix.length > 1 ? suffix.slice(0, -1) : suffix;
|
|
179
|
-
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
180
|
-
}
|
|
181
181
|
var DocsDocument = ({
|
|
182
182
|
leavesJson,
|
|
183
|
-
presetsJson,
|
|
184
183
|
assetBase,
|
|
185
184
|
docsBase,
|
|
186
|
-
historyJson,
|
|
187
|
-
logsJson,
|
|
188
|
-
baseUrlSuffix,
|
|
189
|
-
webhooks,
|
|
190
185
|
cspNonce
|
|
191
186
|
}) => {
|
|
192
187
|
const cssHref = `${assetBase}/docs.css`;
|
|
193
188
|
const jsSrc = `${assetBase}/docs.js`;
|
|
194
|
-
const configJson = serializeConfig({
|
|
189
|
+
const configJson = serializeConfig({
|
|
190
|
+
docsBasePath: docsBase
|
|
191
|
+
});
|
|
195
192
|
return /* @__PURE__ */ jsxs("html", { lang: "en", children: [
|
|
196
193
|
/* @__PURE__ */ jsxs("head", { children: [
|
|
197
194
|
/* @__PURE__ */ jsx("meta", { charSet: "UTF-8" }),
|
|
@@ -210,33 +207,6 @@ var DocsDocument = ({
|
|
|
210
207
|
dangerouslySetInnerHTML: { __html: leavesJson }
|
|
211
208
|
}
|
|
212
209
|
),
|
|
213
|
-
/* @__PURE__ */ jsx(
|
|
214
|
-
"script",
|
|
215
|
-
{
|
|
216
|
-
id: "preset-data",
|
|
217
|
-
type: "application/json",
|
|
218
|
-
nonce: cspNonce,
|
|
219
|
-
dangerouslySetInnerHTML: { __html: presetsJson }
|
|
220
|
-
}
|
|
221
|
-
),
|
|
222
|
-
/* @__PURE__ */ jsx(
|
|
223
|
-
"script",
|
|
224
|
-
{
|
|
225
|
-
id: "history-data",
|
|
226
|
-
type: "application/json",
|
|
227
|
-
nonce: cspNonce,
|
|
228
|
-
dangerouslySetInnerHTML: { __html: historyJson }
|
|
229
|
-
}
|
|
230
|
-
),
|
|
231
|
-
/* @__PURE__ */ jsx(
|
|
232
|
-
"script",
|
|
233
|
-
{
|
|
234
|
-
id: "logs-data",
|
|
235
|
-
type: "application/json",
|
|
236
|
-
nonce: cspNonce,
|
|
237
|
-
dangerouslySetInnerHTML: { __html: logsJson }
|
|
238
|
-
}
|
|
239
|
-
),
|
|
240
210
|
/* @__PURE__ */ jsx(
|
|
241
211
|
"script",
|
|
242
212
|
{
|
|
@@ -250,627 +220,39 @@ var DocsDocument = ({
|
|
|
250
220
|
] })
|
|
251
221
|
] });
|
|
252
222
|
};
|
|
253
|
-
function serializeLeaves(
|
|
254
|
-
return JSON.stringify(
|
|
255
|
-
}
|
|
256
|
-
function serializePresets(presets) {
|
|
257
|
-
return JSON.stringify(Array.isArray(presets) ? presets : []).replace(/<\//g, "<\\/");
|
|
258
|
-
}
|
|
259
|
-
function serializeHistorySeeds(historySeeds) {
|
|
260
|
-
return JSON.stringify(Array.isArray(historySeeds) ? historySeeds : []).replace(/<\//g, "<\\/");
|
|
261
|
-
}
|
|
262
|
-
function serializeLogSeeds(logSeeds) {
|
|
263
|
-
return JSON.stringify(Array.isArray(logSeeds) ? logSeeds : []).replace(/<\//g, "<\\/");
|
|
223
|
+
function serializeLeaves(leaves2) {
|
|
224
|
+
return JSON.stringify(leaves2.map(serializeLeaf)).replace(/<\//g, "<\\/");
|
|
264
225
|
}
|
|
265
226
|
function serializeConfig(config) {
|
|
266
227
|
return JSON.stringify(config).replace(/<\//g, "<\\/");
|
|
267
228
|
}
|
|
268
|
-
function createLeafDocsDocument(
|
|
229
|
+
function createLeafDocsDocument(leaves2, options = {}) {
|
|
269
230
|
const assetBase = normalizeBase(options.assetBasePath ?? DEFAULT_ASSET_BASE);
|
|
270
|
-
const leavesJson = serializeLeaves(
|
|
271
|
-
const presetsJson = serializePresets(options.presets);
|
|
231
|
+
const leavesJson = serializeLeaves(leaves2);
|
|
272
232
|
const docsBase = normalizeDocsBase(options.docsBasePath);
|
|
273
|
-
const historyJson = serializeHistorySeeds(options.historySeeds);
|
|
274
|
-
const logsJson = serializeLogSeeds(options.logSeeds);
|
|
275
|
-
const baseUrlSuffix = normalizeBaseUrlSuffix(options.baseUrlSuffix);
|
|
276
|
-
const webhooks = options.webhooks;
|
|
277
233
|
return /* @__PURE__ */ jsx(
|
|
278
234
|
DocsDocument,
|
|
279
235
|
{
|
|
280
236
|
leavesJson,
|
|
281
|
-
presetsJson,
|
|
282
237
|
assetBase,
|
|
283
238
|
docsBase,
|
|
284
|
-
historyJson,
|
|
285
|
-
logsJson,
|
|
286
|
-
baseUrlSuffix,
|
|
287
|
-
webhooks,
|
|
288
239
|
cspNonce: options.cspNonce
|
|
289
240
|
}
|
|
290
241
|
);
|
|
291
242
|
}
|
|
292
|
-
function renderLeafDocsHTML(
|
|
293
|
-
const doc = createLeafDocsDocument(
|
|
243
|
+
function renderLeafDocsHTML(leaves2, options = {}) {
|
|
244
|
+
const doc = createLeafDocsDocument(leaves2, options);
|
|
294
245
|
const html = renderToStaticMarkup(doc);
|
|
295
246
|
return `<!DOCTYPE html>${html}`;
|
|
296
247
|
}
|
|
297
248
|
|
|
298
249
|
// src/docs/docs.ts
|
|
299
|
-
function renderLeafDocsHTML2(
|
|
300
|
-
return renderLeafDocsHTML(
|
|
250
|
+
function renderLeafDocsHTML2(leaves2, options = {}) {
|
|
251
|
+
return renderLeafDocsHTML(leaves2, options);
|
|
301
252
|
}
|
|
302
253
|
|
|
303
|
-
// src/
|
|
304
|
-
import
|
|
305
|
-
var logTypeSchema = z2.enum(["debug", "info", "warn", "error", "system"]);
|
|
306
|
-
var historyFeedEntrySchema = z2.object({
|
|
307
|
-
id: z2.string(),
|
|
308
|
-
requestId: z2.string().optional(),
|
|
309
|
-
timestamp: z2.number(),
|
|
310
|
-
method: z2.string(),
|
|
311
|
-
path: z2.string(),
|
|
312
|
-
fullUrl: z2.string().optional(),
|
|
313
|
-
params: z2.record(z2.string(), z2.string()).optional(),
|
|
314
|
-
query: z2.record(z2.string(), z2.string()).optional(),
|
|
315
|
-
body: z2.string().optional(),
|
|
316
|
-
output: z2.string().optional(),
|
|
317
|
-
status: z2.number().optional(),
|
|
318
|
-
durationMs: z2.number(),
|
|
319
|
-
error: z2.string().optional()
|
|
320
|
-
});
|
|
321
|
-
var logFeedEntrySchema = z2.object({
|
|
322
|
-
id: z2.string(),
|
|
323
|
-
type: logTypeSchema,
|
|
324
|
-
message: z2.string(),
|
|
325
|
-
timestamp: z2.number(),
|
|
326
|
-
requestId: z2.string().optional(),
|
|
327
|
-
tags: z2.array(z2.string()).optional(),
|
|
328
|
-
metadata: z2.string().optional()
|
|
329
|
-
});
|
|
330
|
-
var historyFeedQuerySchema = z2.object({
|
|
331
|
-
cursor: z2.string().optional(),
|
|
332
|
-
limit: z2.number().int().positive().optional(),
|
|
333
|
-
methods: z2.array(z2.string()).optional(),
|
|
334
|
-
path: z2.string().optional(),
|
|
335
|
-
status: z2.string().optional(),
|
|
336
|
-
text: z2.string().optional(),
|
|
337
|
-
from: z2.number().optional(),
|
|
338
|
-
to: z2.number().optional(),
|
|
339
|
-
sortBy: z2.enum(["timestamp", "path", "duration"]).optional(),
|
|
340
|
-
sortDir: z2.enum(["asc", "desc"]).optional()
|
|
341
|
-
});
|
|
342
|
-
var logFeedQuerySchema = z2.object({
|
|
343
|
-
cursor: z2.string().optional(),
|
|
344
|
-
limit: z2.number().int().positive().optional(),
|
|
345
|
-
types: z2.array(logTypeSchema).optional(),
|
|
346
|
-
tags: z2.array(z2.string()).optional(),
|
|
347
|
-
requestId: z2.string().optional(),
|
|
348
|
-
text: z2.string().optional(),
|
|
349
|
-
from: z2.number().optional(),
|
|
350
|
-
to: z2.number().optional(),
|
|
351
|
-
sortDir: z2.enum(["asc", "desc"]).optional()
|
|
352
|
-
});
|
|
353
|
-
var webhookPageSchema = (itemSchema) => z2.object({
|
|
354
|
-
items: z2.array(itemSchema).default([]),
|
|
355
|
-
nextCursor: z2.string().optional(),
|
|
356
|
-
prevCursor: z2.string().optional(),
|
|
357
|
-
total: z2.number().optional()
|
|
358
|
-
});
|
|
359
|
-
var historyWebhookResponseSchema = webhookPageSchema(historyFeedEntrySchema);
|
|
360
|
-
var logWebhookResponseSchema = webhookPageSchema(logFeedEntrySchema);
|
|
361
|
-
|
|
362
|
-
// src/index.ts
|
|
363
|
-
var trimTrailingSlash = (value) => value.endsWith("/") && value.length > 1 ? value.slice(0, -1) : value;
|
|
364
|
-
function mountRRRoutesDocs({
|
|
365
|
-
router,
|
|
366
|
-
leaves,
|
|
367
|
-
presets = [],
|
|
368
|
-
options = {}
|
|
369
|
-
}) {
|
|
370
|
-
const prefix = options.prefix ? trimTrailingSlash(options.prefix) : "";
|
|
371
|
-
const docsPath = options.path ?? "/__rrroutes/docs";
|
|
372
|
-
const normalizedDocsPath = trimTrailingSlash(docsPath);
|
|
373
|
-
const assetsMountPath = trimTrailingSlash(
|
|
374
|
-
options.assetBasePath ?? `${normalizedDocsPath}/assets`
|
|
375
|
-
);
|
|
376
|
-
const webhookBaseInput = options.logWebhook?.basePath ?? `${normalizedDocsPath}/webhooks`;
|
|
377
|
-
const webhookBasePath = trimTrailingSlash(
|
|
378
|
-
webhookBaseInput.startsWith("/") ? webhookBaseInput : `/${webhookBaseInput}`
|
|
379
|
-
);
|
|
380
|
-
const defaultHistoryLimit = 200;
|
|
381
|
-
const defaultLogLimit = 400;
|
|
382
|
-
const redactLogEntry = createLogRedactor(options.redactLogEntry);
|
|
383
|
-
const seededHistory = normalizeHistorySeeds(options.historySeeds, defaultHistoryLimit);
|
|
384
|
-
const seededLogs = normalizeLogSeeds(options.logSeeds, defaultLogLimit, redactLogEntry);
|
|
385
|
-
const inMemoryHistory = seededHistory.slice();
|
|
386
|
-
const inMemoryLogs = seededLogs.slice();
|
|
387
|
-
const historySeedsForUi = seededHistory.map((entry) => ({
|
|
388
|
-
...entry,
|
|
389
|
-
fullUrl: entry.fullUrl || entry.path
|
|
390
|
-
}));
|
|
391
|
-
const webhookPaths = {
|
|
392
|
-
history: `${webhookBasePath}/history`,
|
|
393
|
-
logs: `${webhookBasePath}/logs`
|
|
394
|
-
};
|
|
395
|
-
const webhookSchemas = {
|
|
396
|
-
history: {
|
|
397
|
-
query: historyFeedQuerySchema,
|
|
398
|
-
response: historyWebhookResponseSchema,
|
|
399
|
-
entry: historyFeedEntrySchema
|
|
400
|
-
},
|
|
401
|
-
logs: {
|
|
402
|
-
query: logFeedQuerySchema,
|
|
403
|
-
response: logWebhookResponseSchema,
|
|
404
|
-
entry: logFeedEntrySchema
|
|
405
|
-
}
|
|
406
|
-
};
|
|
407
|
-
const webhookLeaves = {
|
|
408
|
-
history: {
|
|
409
|
-
method: "get",
|
|
410
|
-
path: webhookPaths.history,
|
|
411
|
-
cfg: {
|
|
412
|
-
summary: "RRRoutes docs history feed",
|
|
413
|
-
description: "Returns request history for the docs UI.",
|
|
414
|
-
querySchema: historyFeedQuerySchema,
|
|
415
|
-
outputSchema: historyWebhookResponseSchema,
|
|
416
|
-
tags: ["rrroutes", "docs"]
|
|
417
|
-
}
|
|
418
|
-
},
|
|
419
|
-
logs: {
|
|
420
|
-
method: "get",
|
|
421
|
-
path: webhookPaths.logs,
|
|
422
|
-
cfg: {
|
|
423
|
-
summary: "RRRoutes docs request logs",
|
|
424
|
-
description: "Returns request logs for the docs UI.",
|
|
425
|
-
querySchema: logFeedQuerySchema,
|
|
426
|
-
outputSchema: logWebhookResponseSchema,
|
|
427
|
-
tags: ["rrroutes", "docs"]
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
};
|
|
431
|
-
const publicDir = resolvePublicDir();
|
|
432
|
-
const assetsDir = path.join(publicDir, "assets");
|
|
433
|
-
const cspEnabled = options.csp !== false;
|
|
434
|
-
const authConfig = options.auth;
|
|
435
|
-
const authEnabled = authConfig?.enabled !== false;
|
|
436
|
-
const docsPassword = resolveDocsPassword(authConfig);
|
|
437
|
-
const authRealm = authConfig?.realm || "RRRoutes Docs";
|
|
438
|
-
if (authEnabled) {
|
|
439
|
-
const guard = docsPassword ? createPasswordGuard(docsPassword, authRealm) : createMissingPasswordGuard();
|
|
440
|
-
[normalizedDocsPath, assetsMountPath, webhookBasePath].forEach((p) => {
|
|
441
|
-
router.use(p, guard);
|
|
442
|
-
});
|
|
443
|
-
}
|
|
444
|
-
router.use(assetsMountPath, expressStatic(assetsDir, { immutable: true, maxAge: "365d" }));
|
|
445
|
-
const usingFakeHistory = !options.logWebhook?.history;
|
|
446
|
-
const usingFakeLogs = !options.logWebhook?.logs;
|
|
447
|
-
if (usingFakeHistory || usingFakeLogs) {
|
|
448
|
-
router.use((req, res, next) => {
|
|
449
|
-
if (req.path.startsWith(webhookBasePath) || req.path.startsWith(assetsMountPath) || req.path.startsWith(normalizedDocsPath)) {
|
|
450
|
-
return next();
|
|
451
|
-
}
|
|
452
|
-
const start = Date.now();
|
|
453
|
-
const requestIdHeader = req.headers["x-request-id"] || req.headers["x-requestid"] || req.headers["x-request_id"];
|
|
454
|
-
const requestId = Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader;
|
|
455
|
-
res.once("finish", () => {
|
|
456
|
-
const timestamp = Date.now();
|
|
457
|
-
const durationMs = Math.max(timestamp - start, 0);
|
|
458
|
-
const methodUpper = String(req.method || "GET").toUpperCase();
|
|
459
|
-
const pathOnly = req.path || req.originalUrl || "";
|
|
460
|
-
const status = res.statusCode;
|
|
461
|
-
const errorMsg = status >= 400 ? `${status}` : void 0;
|
|
462
|
-
if (usingFakeHistory) {
|
|
463
|
-
inMemoryHistory.unshift({
|
|
464
|
-
id: randomBytes(8).toString("hex"),
|
|
465
|
-
requestId: requestId ? String(requestId) : void 0,
|
|
466
|
-
timestamp,
|
|
467
|
-
method: methodUpper,
|
|
468
|
-
path: pathOnly,
|
|
469
|
-
fullUrl: req.originalUrl || pathOnly,
|
|
470
|
-
params: {},
|
|
471
|
-
query: coerceQueryRecord(req.query),
|
|
472
|
-
body: coercePayload(req.body),
|
|
473
|
-
output: "",
|
|
474
|
-
status,
|
|
475
|
-
durationMs,
|
|
476
|
-
error: errorMsg
|
|
477
|
-
});
|
|
478
|
-
if (inMemoryHistory.length > defaultHistoryLimit) inMemoryHistory.length = defaultHistoryLimit;
|
|
479
|
-
}
|
|
480
|
-
if (usingFakeLogs) {
|
|
481
|
-
const logType = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
|
|
482
|
-
const metadata = JSON.stringify({
|
|
483
|
-
query: req.query,
|
|
484
|
-
durationMs
|
|
485
|
-
});
|
|
486
|
-
const redacted = redactLogEntry({
|
|
487
|
-
id: randomBytes(8).toString("hex"),
|
|
488
|
-
type: logType,
|
|
489
|
-
message: `${methodUpper} ${pathOnly} -> ${status}`,
|
|
490
|
-
timestamp,
|
|
491
|
-
requestId: requestId ? String(requestId) : void 0,
|
|
492
|
-
tags: [],
|
|
493
|
-
metadata
|
|
494
|
-
});
|
|
495
|
-
if (redacted) {
|
|
496
|
-
inMemoryLogs.unshift(redacted);
|
|
497
|
-
if (inMemoryLogs.length > defaultLogLimit) inMemoryLogs.length = defaultLogLimit;
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
});
|
|
501
|
-
next();
|
|
502
|
-
});
|
|
503
|
-
}
|
|
504
|
-
router.get(webhookPaths.history, async (req, res) => {
|
|
505
|
-
const handler = options.logWebhook?.history;
|
|
506
|
-
try {
|
|
507
|
-
applyDocsSecurityHeaders(res);
|
|
508
|
-
const query = parseHistoryWebhookQuery(req);
|
|
509
|
-
if (!handler) {
|
|
510
|
-
const filtered2 = applyHistoryQuery(inMemoryHistory, query, defaultHistoryLimit);
|
|
511
|
-
res.json(filtered2);
|
|
512
|
-
return;
|
|
513
|
-
}
|
|
514
|
-
const result = await handler({ query, req, res });
|
|
515
|
-
const normalized = normalizeWebhookPage(result);
|
|
516
|
-
const filtered = applyHistoryQuery(normalized.items, query, defaultHistoryLimit);
|
|
517
|
-
res.json(filtered);
|
|
518
|
-
} catch (err) {
|
|
519
|
-
console.error("Failed to serve history webhook", err);
|
|
520
|
-
res.status(500).json({ error: "Failed to load history feed" });
|
|
521
|
-
}
|
|
522
|
-
});
|
|
523
|
-
router.get(webhookPaths.logs, async (req, res) => {
|
|
524
|
-
const handler = options.logWebhook?.logs;
|
|
525
|
-
try {
|
|
526
|
-
applyDocsSecurityHeaders(res);
|
|
527
|
-
const query = parseLogWebhookQuery(req);
|
|
528
|
-
if (!handler) {
|
|
529
|
-
const filtered2 = applyLogsQuery(inMemoryLogs, query, defaultLogLimit);
|
|
530
|
-
res.json(filtered2);
|
|
531
|
-
return;
|
|
532
|
-
}
|
|
533
|
-
const result = await handler({ query, req, res });
|
|
534
|
-
const normalized = normalizeWebhookPage(result);
|
|
535
|
-
const redacted = applyLogRedaction(normalized.items, redactLogEntry);
|
|
536
|
-
const filtered = applyLogsQuery(redacted, query, defaultLogLimit);
|
|
537
|
-
res.json(filtered);
|
|
538
|
-
} catch (err) {
|
|
539
|
-
console.error("Failed to serve log webhook", err);
|
|
540
|
-
res.status(500).json({ error: "Failed to load logs feed" });
|
|
541
|
-
}
|
|
542
|
-
});
|
|
543
|
-
const docsRoutePaths = [normalizedDocsPath, `${normalizedDocsPath}/`, `${normalizedDocsPath}/*id`];
|
|
544
|
-
router.get(docsRoutePaths, (req, res) => {
|
|
545
|
-
const preparedLeaves = Array.isArray(leaves) ? leaves.filter((leaf) => leaf.cfg.docsHidden !== true) : [];
|
|
546
|
-
const preparedPresets = Array.isArray(presets) ? presets : [];
|
|
547
|
-
const onRequestResult = options.onRequest?.({ req, res, leaves: preparedLeaves, presets: preparedPresets }) ?? {};
|
|
548
|
-
const finalLeaves = onRequestResult.leaves ?? preparedLeaves;
|
|
549
|
-
const finalPresets = onRequestResult.presets ?? preparedPresets;
|
|
550
|
-
const hasCustomHtml = typeof onRequestResult.html === "string";
|
|
551
|
-
let nonce = onRequestResult.nonce;
|
|
552
|
-
if (!nonce && cspEnabled && !hasCustomHtml) {
|
|
553
|
-
nonce = randomBytes(16).toString("base64");
|
|
554
|
-
}
|
|
555
|
-
const html = hasCustomHtml ? onRequestResult.html : renderLeafDocsHTML2(finalLeaves, {
|
|
556
|
-
cspNonce: nonce,
|
|
557
|
-
assetBasePath: `${prefix}${assetsMountPath}`,
|
|
558
|
-
docsBasePath: `${prefix}${normalizedDocsPath}`,
|
|
559
|
-
baseUrlSuffix: prefix,
|
|
560
|
-
historySeeds: historySeedsForUi,
|
|
561
|
-
logSeeds: seededLogs,
|
|
562
|
-
presets: normalizePresets(finalPresets),
|
|
563
|
-
webhooks: {
|
|
564
|
-
history: `${prefix}${webhookPaths.history}`,
|
|
565
|
-
logs: `${prefix}${webhookPaths.logs}`
|
|
566
|
-
}
|
|
567
|
-
});
|
|
568
|
-
applyDocsSecurityHeaders(res);
|
|
569
|
-
if (cspEnabled && nonce) {
|
|
570
|
-
res.setHeader(
|
|
571
|
-
"Content-Security-Policy",
|
|
572
|
-
[
|
|
573
|
-
"default-src 'self'",
|
|
574
|
-
`script-src 'self' 'nonce-${nonce}'`,
|
|
575
|
-
`style-src 'self' 'nonce-${nonce}'`,
|
|
576
|
-
"img-src 'self' data:",
|
|
577
|
-
"connect-src 'self'",
|
|
578
|
-
"font-src 'self'",
|
|
579
|
-
"frame-ancestors 'self'"
|
|
580
|
-
].join("; ")
|
|
581
|
-
);
|
|
582
|
-
}
|
|
583
|
-
res.send(html);
|
|
584
|
-
});
|
|
585
|
-
return { path: docsPath, webhooks: webhookPaths, webhookLeaves, webhookSchemas };
|
|
586
|
-
}
|
|
587
|
-
function resolvePublicDir() {
|
|
588
|
-
const moduleDir = typeof __dirname !== "undefined" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
|
|
589
|
-
const fromModule = path.resolve(moduleDir, "../public");
|
|
590
|
-
if (fs.existsSync(fromModule)) return fromModule;
|
|
591
|
-
const fallback = path.resolve(moduleDir, "../dist/public");
|
|
592
|
-
if (fs.existsSync(fallback)) return fallback;
|
|
593
|
-
return fromModule;
|
|
594
|
-
}
|
|
595
|
-
function normalizePresets(presets) {
|
|
596
|
-
if (!Array.isArray(presets)) return [];
|
|
597
|
-
return presets.map((preset) => ({
|
|
598
|
-
name: preset.name,
|
|
599
|
-
description: preset.description,
|
|
600
|
-
tags: Array.isArray(preset.tags) ? preset.tags.slice() : [],
|
|
601
|
-
docsGroup: preset.docsGroup,
|
|
602
|
-
ops: Array.isArray(preset.ops) ? preset.ops.map((op) => ({
|
|
603
|
-
method: typeof op.method === "string" ? op.method.toUpperCase() : "",
|
|
604
|
-
path: typeof op.path === "string" ? op.path : "",
|
|
605
|
-
body: op.body,
|
|
606
|
-
query: op.query,
|
|
607
|
-
params: op.params
|
|
608
|
-
})) : []
|
|
609
|
-
}));
|
|
610
|
-
}
|
|
611
|
-
function parseHistoryWebhookQuery(req) {
|
|
612
|
-
const query = req.query || {};
|
|
613
|
-
const methods = parseStringList(query.methods);
|
|
614
|
-
const path2 = typeof query.path === "string" ? query.path : void 0;
|
|
615
|
-
const status = typeof query.status === "string" ? query.status : void 0;
|
|
616
|
-
const text = typeof query.text === "string" ? query.text : void 0;
|
|
617
|
-
const cursor = typeof query.cursor === "string" ? query.cursor : void 0;
|
|
618
|
-
const sortBy = isSortKey(query.sortBy) ? query.sortBy : void 0;
|
|
619
|
-
const sortDir = isSortDir(query.sortDir) ? query.sortDir : void 0;
|
|
620
|
-
const limit = parseLimit(query.limit);
|
|
621
|
-
const from = parseDateInput(query.from);
|
|
622
|
-
const to = parseDateInput(query.to);
|
|
623
|
-
return {
|
|
624
|
-
cursor,
|
|
625
|
-
methods,
|
|
626
|
-
path: path2,
|
|
627
|
-
status,
|
|
628
|
-
text,
|
|
629
|
-
limit,
|
|
630
|
-
from,
|
|
631
|
-
to,
|
|
632
|
-
sortBy,
|
|
633
|
-
sortDir
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
function parseLogWebhookQuery(req) {
|
|
637
|
-
const query = req.query || {};
|
|
638
|
-
const types = parseStringList(query.types);
|
|
639
|
-
const tags = parseStringList(query.tags);
|
|
640
|
-
const requestId = typeof query.requestId === "string" ? query.requestId : void 0;
|
|
641
|
-
const text = typeof query.text === "string" ? query.text : void 0;
|
|
642
|
-
const cursor = typeof query.cursor === "string" ? query.cursor : void 0;
|
|
643
|
-
const limit = parseLimit(query.limit);
|
|
644
|
-
const from = parseDateInput(query.from);
|
|
645
|
-
const to = parseDateInput(query.to);
|
|
646
|
-
const sortDir = isSortDir(query.sortDir) ? query.sortDir : void 0;
|
|
647
|
-
return {
|
|
648
|
-
cursor,
|
|
649
|
-
types,
|
|
650
|
-
tags,
|
|
651
|
-
requestId,
|
|
652
|
-
text,
|
|
653
|
-
limit,
|
|
654
|
-
from,
|
|
655
|
-
to,
|
|
656
|
-
sortDir
|
|
657
|
-
};
|
|
658
|
-
}
|
|
659
|
-
function parseStringList(value) {
|
|
660
|
-
if (typeof value !== "string") return void 0;
|
|
661
|
-
const parts = value.split(",").map((p) => p.trim()).filter(Boolean);
|
|
662
|
-
return parts.length ? parts : void 0;
|
|
663
|
-
}
|
|
664
|
-
function parseLimit(value) {
|
|
665
|
-
if (value === void 0) return void 0;
|
|
666
|
-
const num = Number(value);
|
|
667
|
-
if (!Number.isFinite(num) || num <= 0) return void 0;
|
|
668
|
-
return num;
|
|
669
|
-
}
|
|
670
|
-
function parseDateInput(value) {
|
|
671
|
-
if (typeof value !== "string") return void 0;
|
|
672
|
-
const numeric = Number(value);
|
|
673
|
-
if (Number.isFinite(numeric)) return numeric;
|
|
674
|
-
const timestamp = Date.parse(value);
|
|
675
|
-
if (Number.isNaN(timestamp)) return void 0;
|
|
676
|
-
return timestamp;
|
|
677
|
-
}
|
|
678
|
-
function isSortKey(value) {
|
|
679
|
-
return value === "timestamp" || value === "path" || value === "duration";
|
|
680
|
-
}
|
|
681
|
-
function isSortDir(value) {
|
|
682
|
-
return value === "asc" || value === "desc";
|
|
683
|
-
}
|
|
684
|
-
function normalizeWebhookPage(page) {
|
|
685
|
-
if (!page || typeof page !== "object") return { items: [] };
|
|
686
|
-
return {
|
|
687
|
-
items: Array.isArray(page.items) ? page.items : [],
|
|
688
|
-
nextCursor: page.nextCursor,
|
|
689
|
-
prevCursor: page.prevCursor,
|
|
690
|
-
total: page.total
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
function applyHistoryQuery(items, query, hardLimit) {
|
|
694
|
-
const fromTs = typeof query.from === "number" ? query.from : void 0;
|
|
695
|
-
const toTs = typeof query.to === "number" ? query.to : void 0;
|
|
696
|
-
const methods = query.methods ? new Set(query.methods.map((m) => m.toUpperCase())) : void 0;
|
|
697
|
-
const pathNeedle = (query.path || "").toLowerCase();
|
|
698
|
-
const textNeedle = (query.text || "").toLowerCase();
|
|
699
|
-
const statusNeedle = (query.status || "").trim();
|
|
700
|
-
const filtered = (Array.isArray(items) ? items : []).filter((entry) => {
|
|
701
|
-
if (methods?.size && !methods.has(String(entry.method || "").toUpperCase())) return false;
|
|
702
|
-
if (pathNeedle && !String(entry.path || "").toLowerCase().includes(pathNeedle)) return false;
|
|
703
|
-
if (statusNeedle) {
|
|
704
|
-
const statusStr = entry.status !== void 0 && entry.status !== null ? String(entry.status) : "ERR";
|
|
705
|
-
if (!statusStr.startsWith(statusNeedle)) return false;
|
|
706
|
-
}
|
|
707
|
-
if (Number.isFinite(fromTs) && entry.timestamp < fromTs) return false;
|
|
708
|
-
if (Number.isFinite(toTs) && entry.timestamp > toTs) return false;
|
|
709
|
-
if (textNeedle) {
|
|
710
|
-
const haystack = [
|
|
711
|
-
entry.path,
|
|
712
|
-
entry.fullUrl,
|
|
713
|
-
entry.body,
|
|
714
|
-
entry.output,
|
|
715
|
-
entry.error,
|
|
716
|
-
JSON.stringify(entry.params || {}),
|
|
717
|
-
JSON.stringify(entry.query || {})
|
|
718
|
-
].filter(Boolean).join(" ").toLowerCase();
|
|
719
|
-
if (!haystack.includes(textNeedle)) return false;
|
|
720
|
-
}
|
|
721
|
-
return true;
|
|
722
|
-
});
|
|
723
|
-
const sortBy = query.sortBy || "timestamp";
|
|
724
|
-
const direction = query.sortDir === "asc" ? 1 : -1;
|
|
725
|
-
const sorted = filtered.slice().sort((a, b) => {
|
|
726
|
-
let delta = 0;
|
|
727
|
-
if (sortBy === "path") {
|
|
728
|
-
delta = String(a.path || "").localeCompare(String(b.path || ""));
|
|
729
|
-
} else if (sortBy === "duration") {
|
|
730
|
-
delta = (a.durationMs || 0) - (b.durationMs || 0);
|
|
731
|
-
} else {
|
|
732
|
-
delta = (a.timestamp || 0) - (b.timestamp || 0);
|
|
733
|
-
}
|
|
734
|
-
return delta * direction;
|
|
735
|
-
});
|
|
736
|
-
return paginateItems(sorted, query.cursor, query.limit, hardLimit, 25);
|
|
737
|
-
}
|
|
738
|
-
function applyLogsQuery(items, query, hardLimit) {
|
|
739
|
-
const fromTs = typeof query.from === "number" ? query.from : void 0;
|
|
740
|
-
const toTs = typeof query.to === "number" ? query.to : void 0;
|
|
741
|
-
const textNeedle = (query.text || "").toLowerCase();
|
|
742
|
-
const requestIdNeedle = (query.requestId || "").toLowerCase();
|
|
743
|
-
const types = query.types ? new Set(query.types) : void 0;
|
|
744
|
-
const tags = query.tags ? new Set(query.tags) : void 0;
|
|
745
|
-
const filtered = (Array.isArray(items) ? items : []).filter((entry) => {
|
|
746
|
-
if (types?.size && !types.has(entry.type)) return false;
|
|
747
|
-
const entryTags = Array.isArray(entry.tags) ? entry.tags : [];
|
|
748
|
-
if (tags?.size && !entryTags.some((tag) => tags.has(tag))) return false;
|
|
749
|
-
if (requestIdNeedle && !(entry.requestId || "").toLowerCase().includes(requestIdNeedle))
|
|
750
|
-
return false;
|
|
751
|
-
if (Number.isFinite(fromTs) && entry.timestamp < fromTs) return false;
|
|
752
|
-
if (Number.isFinite(toTs) && entry.timestamp > toTs) return false;
|
|
753
|
-
if (textNeedle) {
|
|
754
|
-
const haystack = [
|
|
755
|
-
entry.message,
|
|
756
|
-
entry.requestId,
|
|
757
|
-
entryTags.join(" "),
|
|
758
|
-
typeof entry.metadata === "string" ? entry.metadata : JSON.stringify(entry.metadata || "")
|
|
759
|
-
].filter(Boolean).join(" ").toLowerCase();
|
|
760
|
-
if (!haystack.includes(textNeedle)) return false;
|
|
761
|
-
}
|
|
762
|
-
return true;
|
|
763
|
-
});
|
|
764
|
-
const direction = query.sortDir === "asc" ? 1 : -1;
|
|
765
|
-
const sorted = filtered.slice().sort((a, b) => (a.timestamp - b.timestamp) * direction);
|
|
766
|
-
return paginateItems(sorted, query.cursor, query.limit, hardLimit, 50);
|
|
767
|
-
}
|
|
768
|
-
function paginateItems(items, cursor, limit, hardLimit, fallbackLimit) {
|
|
769
|
-
const safeLimit = clampLimit(limit, hardLimit, fallbackLimit);
|
|
770
|
-
const start = parseCursor(cursor);
|
|
771
|
-
const end = start + safeLimit;
|
|
772
|
-
const slice = items.slice(start, end);
|
|
773
|
-
const nextCursor = end < items.length ? String(end) : void 0;
|
|
774
|
-
const prevCursor = start > 0 ? String(Math.max(start - safeLimit, 0)) : void 0;
|
|
775
|
-
return {
|
|
776
|
-
items: slice,
|
|
777
|
-
nextCursor,
|
|
778
|
-
prevCursor,
|
|
779
|
-
total: items.length
|
|
780
|
-
};
|
|
781
|
-
}
|
|
782
|
-
function clampLimit(value, hardLimit, fallback) {
|
|
783
|
-
if (!Number.isFinite(value)) return Math.min(hardLimit, fallback);
|
|
784
|
-
const safe = Math.max(1, Math.min(hardLimit, value));
|
|
785
|
-
return safe;
|
|
786
|
-
}
|
|
787
|
-
function parseCursor(cursor) {
|
|
788
|
-
const num = Number(cursor);
|
|
789
|
-
if (Number.isFinite(num) && num >= 0) return Math.floor(num);
|
|
790
|
-
return 0;
|
|
791
|
-
}
|
|
792
|
-
function normalizeHistorySeeds(seeds, hardLimit) {
|
|
793
|
-
if (!Array.isArray(seeds)) return [];
|
|
794
|
-
return seeds.slice(0, hardLimit).map((entry, idx) => ({
|
|
795
|
-
id: entry.id || randomBytes(8).toString("hex"),
|
|
796
|
-
requestId: typeof entry.requestId === "string" ? entry.requestId : void 0,
|
|
797
|
-
timestamp: entry.timestamp ?? Date.now() - idx * 1e3,
|
|
798
|
-
method: entry.method || "GET",
|
|
799
|
-
path: entry.path || "/",
|
|
800
|
-
fullUrl: entry.fullUrl || entry.path || "/",
|
|
801
|
-
params: entry.params || {},
|
|
802
|
-
query: entry.query || {},
|
|
803
|
-
body: entry.body || "",
|
|
804
|
-
output: entry.output || "",
|
|
805
|
-
status: entry.status,
|
|
806
|
-
durationMs: entry.durationMs ?? 0,
|
|
807
|
-
error: entry.error
|
|
808
|
-
})).filter((entry) => entry.method && entry.path);
|
|
809
|
-
}
|
|
810
|
-
function normalizeLogSeeds(seeds, hardLimit, redactor) {
|
|
811
|
-
if (!Array.isArray(seeds)) return [];
|
|
812
|
-
const normalized = seeds.slice(0, hardLimit).map((entry, idx) => ({
|
|
813
|
-
id: entry.id || randomBytes(8).toString("hex"),
|
|
814
|
-
type: entry.type || "info",
|
|
815
|
-
message: entry.message || "",
|
|
816
|
-
timestamp: entry.timestamp ?? Date.now() - idx * 1e3,
|
|
817
|
-
requestId: entry.requestId,
|
|
818
|
-
tags: Array.isArray(entry.tags) ? entry.tags : [],
|
|
819
|
-
metadata: entry.metadata
|
|
820
|
-
})).filter((entry) => entry.message);
|
|
821
|
-
return applyLogRedaction(normalized, redactor);
|
|
822
|
-
}
|
|
823
|
-
function coerceQueryRecord(query) {
|
|
824
|
-
if (!query || typeof query !== "object") return {};
|
|
825
|
-
return Object.fromEntries(
|
|
826
|
-
Object.entries(query).map(([key, value]) => [key, coerceValue(value)])
|
|
827
|
-
);
|
|
828
|
-
}
|
|
829
|
-
function coercePayload(body) {
|
|
830
|
-
if (body === void 0 || body === null) return "";
|
|
831
|
-
if (typeof body === "string") return body;
|
|
832
|
-
try {
|
|
833
|
-
return JSON.stringify(body);
|
|
834
|
-
} catch {
|
|
835
|
-
return String(body);
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
function coerceValue(value) {
|
|
839
|
-
if (value === void 0 || value === null) return "";
|
|
840
|
-
if (Array.isArray(value)) return value.map(coerceValue).join(",");
|
|
841
|
-
if (typeof value === "object") {
|
|
842
|
-
try {
|
|
843
|
-
return JSON.stringify(value);
|
|
844
|
-
} catch {
|
|
845
|
-
return String(value);
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
return String(value);
|
|
849
|
-
}
|
|
850
|
-
function createLogRedactor(redactor) {
|
|
851
|
-
if (!redactor) return (entry) => entry;
|
|
852
|
-
return (entry) => {
|
|
853
|
-
try {
|
|
854
|
-
return redactor(entry) ?? null;
|
|
855
|
-
} catch (err) {
|
|
856
|
-
console.error("Log redaction failed \u2013 dropping log entry", err);
|
|
857
|
-
return null;
|
|
858
|
-
}
|
|
859
|
-
};
|
|
860
|
-
}
|
|
861
|
-
function applyLogRedaction(entries, redactor) {
|
|
862
|
-
if (!Array.isArray(entries)) return [];
|
|
863
|
-
const next = [];
|
|
864
|
-
for (const entry of entries) {
|
|
865
|
-
const redacted = redactor(entry);
|
|
866
|
-
if (redacted) next.push(redacted);
|
|
867
|
-
}
|
|
868
|
-
return next;
|
|
869
|
-
}
|
|
870
|
-
function resolveDocsPassword(auth) {
|
|
871
|
-
if (auth?.password) return auth.password;
|
|
872
|
-
return void 0;
|
|
873
|
-
}
|
|
254
|
+
// src/web/utils/security.ts
|
|
255
|
+
import net from "net";
|
|
874
256
|
function createPasswordGuard(password, realm) {
|
|
875
257
|
const trimmed = password.trim();
|
|
876
258
|
return (req, res, next) => {
|
|
@@ -880,19 +262,40 @@ function createPasswordGuard(password, realm) {
|
|
|
880
262
|
}
|
|
881
263
|
applyDocsSecurityHeaders(res);
|
|
882
264
|
res.setHeader("WWW-Authenticate", `Basic realm="${realm}"`);
|
|
883
|
-
res.status(401).send(
|
|
265
|
+
res.status(401).send(
|
|
266
|
+
renderAuthErrorPage(
|
|
267
|
+
"Docs are password protected. Provide the configured password."
|
|
268
|
+
)
|
|
269
|
+
);
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
function createCookieGuard(cookieName, cookieSecret) {
|
|
273
|
+
return (req, res, next) => {
|
|
274
|
+
const cookies = req.cookies;
|
|
275
|
+
const value = cookies?.[cookieName];
|
|
276
|
+
const valid = cookieSecret ? value === cookieSecret : Boolean(value);
|
|
277
|
+
if (valid) {
|
|
278
|
+
return next();
|
|
279
|
+
}
|
|
280
|
+
applyDocsSecurityHeaders(res);
|
|
281
|
+
res.status(401).send(
|
|
282
|
+
renderAuthErrorPage(
|
|
283
|
+
"Docs are protected. You must be authenticated to access this page."
|
|
284
|
+
)
|
|
285
|
+
);
|
|
884
286
|
};
|
|
885
287
|
}
|
|
886
288
|
function createMissingPasswordGuard() {
|
|
887
289
|
return (_req, res) => {
|
|
888
290
|
applyDocsSecurityHeaders(res);
|
|
889
|
-
res.status(500).send(renderAuthErrorPage("Provide
|
|
291
|
+
res.status(500).send(renderAuthErrorPage("Provide auth configuration to mounted docs"));
|
|
890
292
|
};
|
|
891
293
|
}
|
|
892
294
|
function extractPassword(authHeader) {
|
|
893
295
|
if (!authHeader) return void 0;
|
|
894
296
|
const header = Array.isArray(authHeader) ? authHeader[0] : authHeader;
|
|
895
|
-
if (typeof header !== "string" || !header.startsWith("Basic "))
|
|
297
|
+
if (typeof header !== "string" || !header.startsWith("Basic "))
|
|
298
|
+
return void 0;
|
|
896
299
|
const token = header.slice("Basic ".length);
|
|
897
300
|
try {
|
|
898
301
|
const decoded = Buffer.from(token, "base64").toString("utf8");
|
|
@@ -903,6 +306,64 @@ function extractPassword(authHeader) {
|
|
|
903
306
|
return void 0;
|
|
904
307
|
}
|
|
905
308
|
}
|
|
309
|
+
function createIpAllowListGuard(allowed) {
|
|
310
|
+
const ranges = allowed.map((raw) => raw.trim()).filter(Boolean).map(parseIpPattern).filter((r) => r !== null);
|
|
311
|
+
return (req, res, next) => {
|
|
312
|
+
const rawIp = req.ip || req.connection && req.connection.remoteAddress || "";
|
|
313
|
+
const ip = normalizeIp(rawIp);
|
|
314
|
+
if (!ip || !isIpAllowed(ip, ranges)) {
|
|
315
|
+
applyDocsSecurityHeaders(res);
|
|
316
|
+
res.status(403).send(
|
|
317
|
+
renderAuthErrorPage(
|
|
318
|
+
"Access to docs is restricted from this IP address."
|
|
319
|
+
)
|
|
320
|
+
);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
next();
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function normalizeIp(ip) {
|
|
327
|
+
if (!ip) return "";
|
|
328
|
+
if (ip.startsWith("::ffff:")) return ip.slice(7);
|
|
329
|
+
if (ip === "::1") return "127.0.0.1";
|
|
330
|
+
return ip;
|
|
331
|
+
}
|
|
332
|
+
function parseIpPattern(raw) {
|
|
333
|
+
if (raw.includes("/")) {
|
|
334
|
+
const cidr = parseCidr(raw);
|
|
335
|
+
if (!cidr) return null;
|
|
336
|
+
return { kind: "cidr", base: cidr.base, mask: cidr.mask };
|
|
337
|
+
}
|
|
338
|
+
return { kind: "exact", value: normalizeIp(raw) };
|
|
339
|
+
}
|
|
340
|
+
function parseCidr(raw) {
|
|
341
|
+
const [baseIp, bitsStr] = raw.split("/");
|
|
342
|
+
const bits = Number(bitsStr);
|
|
343
|
+
if (!Number.isInteger(bits) || bits < 0 || bits > 32) return null;
|
|
344
|
+
if (net.isIP(baseIp) !== 4) return null;
|
|
345
|
+
const baseLong = ipToLong(baseIp);
|
|
346
|
+
if (baseLong == null) return null;
|
|
347
|
+
const mask = bits === 0 ? 0 : ~0 << 32 - bits >>> 0;
|
|
348
|
+
return { base: (baseLong & mask) >>> 0, mask };
|
|
349
|
+
}
|
|
350
|
+
function ipToLong(ip) {
|
|
351
|
+
const parts = ip.split(".").map((n) => Number(n));
|
|
352
|
+
if (parts.length !== 4) return null;
|
|
353
|
+
if (parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
|
|
354
|
+
return (parts[0] << 24 >>> 0) + (parts[1] << 16 >>> 0) + (parts[2] << 8 >>> 0) + parts[3];
|
|
355
|
+
}
|
|
356
|
+
function isIpAllowed(ip, ranges) {
|
|
357
|
+
const ipv4 = net.isIP(ip) === 4 ? ipToLong(ip) : null;
|
|
358
|
+
for (const r of ranges) {
|
|
359
|
+
if (r.kind === "exact") {
|
|
360
|
+
if (ip === r.value) return true;
|
|
361
|
+
} else if (r.kind === "cidr" && ipv4 != null) {
|
|
362
|
+
if ((ipv4 & r.mask) === r.base) return true;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
906
367
|
function renderAuthErrorPage(message) {
|
|
907
368
|
return `<!DOCTYPE html>
|
|
908
369
|
<html lang="en">
|
|
@@ -931,10 +392,339 @@ function applyDocsSecurityHeaders(res) {
|
|
|
931
392
|
res.setHeader("Referrer-Policy", "same-origin");
|
|
932
393
|
res.setHeader("X-Frame-Options", "SAMEORIGIN");
|
|
933
394
|
res.setHeader("Cache-Control", "no-store");
|
|
395
|
+
res.setHeader(
|
|
396
|
+
"Strict-Transport-Security",
|
|
397
|
+
"max-age=31536000; includeSubDomains"
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// src/web/utils/types.ts
|
|
402
|
+
import {
|
|
403
|
+
finalize,
|
|
404
|
+
resource as resource6
|
|
405
|
+
} from "@emeryld/rrroutes-contract";
|
|
406
|
+
|
|
407
|
+
// src/web/v2/types/types.cacheLog.ts
|
|
408
|
+
import { resource } from "@emeryld/rrroutes-contract";
|
|
409
|
+
import z3 from "zod";
|
|
410
|
+
|
|
411
|
+
// src/web/v2/types/types.base.ts
|
|
412
|
+
import z2 from "zod";
|
|
413
|
+
var METHODS = ["get", "post", "put", "patch", "delete"];
|
|
414
|
+
var baseEntitySchema = z2.object({
|
|
415
|
+
id: z2.string(),
|
|
416
|
+
name: z2.string(),
|
|
417
|
+
description: z2.string().optional(),
|
|
418
|
+
groupId: z2.string().optional(),
|
|
419
|
+
tags: z2.string().array().optional(),
|
|
420
|
+
createdAt: z2.number(),
|
|
421
|
+
updatedAt: z2.number()
|
|
422
|
+
});
|
|
423
|
+
var baseQuerySchema = z2.object({
|
|
424
|
+
beforeDate: z2.string().optional(),
|
|
425
|
+
afterDate: z2.string().optional(),
|
|
426
|
+
orderBy: z2.enum(["timestamp", "duration", "level", "path"]).default("timestamp"),
|
|
427
|
+
orderDirection: z2.enum(["asc", "desc"]).default("desc"),
|
|
428
|
+
searchQuery: z2.string().optional(),
|
|
429
|
+
groups: z2.string().array().optional(),
|
|
430
|
+
tags: z2.string().array().optional(),
|
|
431
|
+
cursor: z2.string().optional()
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
// src/web/v2/types/types.cacheLog.ts
|
|
435
|
+
var operationEnum = z3.enum(["hit", "miss", "set", "delete"]);
|
|
436
|
+
var cacheLogSchema = baseEntitySchema.extend({
|
|
437
|
+
operation: operationEnum,
|
|
438
|
+
// on hit, value = value retrieved
|
|
439
|
+
// on miss, value = null
|
|
440
|
+
// on set, value = value set
|
|
441
|
+
// on delete, value = value deleted
|
|
442
|
+
value: z3.any().nullable(),
|
|
443
|
+
size: z3.number().optional()
|
|
444
|
+
});
|
|
445
|
+
var cacheLogQuerySchema = baseQuerySchema.extend({
|
|
446
|
+
operations: operationEnum.array().optional()
|
|
447
|
+
});
|
|
448
|
+
var cacheLeaves = resource("cache").get({
|
|
449
|
+
feed: true,
|
|
450
|
+
outputSchema: cacheLogSchema.array(),
|
|
451
|
+
querySchema: cacheLogQuerySchema,
|
|
452
|
+
outputMetaSchema: z3.object({
|
|
453
|
+
totalCount: z3.number().optional()
|
|
454
|
+
})
|
|
455
|
+
}).post({
|
|
456
|
+
querySchema: cacheLogQuerySchema
|
|
457
|
+
}).done();
|
|
458
|
+
|
|
459
|
+
// src/web/v2/types/types.endpoint.ts
|
|
460
|
+
import { resource as resource4 } from "@emeryld/rrroutes-contract";
|
|
461
|
+
import z6 from "zod";
|
|
462
|
+
|
|
463
|
+
// src/web/v2/types/types.requestLog.ts
|
|
464
|
+
import { resource as resource3 } from "@emeryld/rrroutes-contract";
|
|
465
|
+
import z5 from "zod";
|
|
466
|
+
|
|
467
|
+
// src/web/v2/types/types.log.ts
|
|
468
|
+
import { resource as resource2 } from "@emeryld/rrroutes-contract";
|
|
469
|
+
import z4 from "zod";
|
|
470
|
+
var levelSchema = z4.enum(["info", "warning", "error", "debug", "trace"]);
|
|
471
|
+
var logSchema = baseEntitySchema.extend({
|
|
472
|
+
level: levelSchema,
|
|
473
|
+
meta: z4.json()
|
|
474
|
+
});
|
|
475
|
+
var logQuerySchema = baseQuerySchema.extend({
|
|
476
|
+
level: levelSchema.array().optional()
|
|
477
|
+
});
|
|
478
|
+
var logLeaves = resource2("logs").get({
|
|
479
|
+
feed: true,
|
|
480
|
+
outputSchema: logSchema.array(),
|
|
481
|
+
querySchema: logQuerySchema,
|
|
482
|
+
outputMetaSchema: z4.object({
|
|
483
|
+
totalCount: z4.number().optional()
|
|
484
|
+
})
|
|
485
|
+
}).done();
|
|
486
|
+
|
|
487
|
+
// src/web/v2/types/types.requestLog.ts
|
|
488
|
+
var requestSchema = baseEntitySchema.extend({
|
|
489
|
+
status: z5.number(),
|
|
490
|
+
body: z5.any().optional(),
|
|
491
|
+
fullUrl: z5.string(),
|
|
492
|
+
path: z5.string(),
|
|
493
|
+
method: z5.enum(METHODS),
|
|
494
|
+
query: z5.record(z5.string(), z5.any()).optional(),
|
|
495
|
+
params: z5.record(z5.string(), z5.any()).optional(),
|
|
496
|
+
output: z5.any().optional(),
|
|
497
|
+
headers: z5.record(z5.string(), z5.any()).optional(),
|
|
498
|
+
error: z5.string().optional(),
|
|
499
|
+
durationMs: z5.number()
|
|
500
|
+
});
|
|
501
|
+
var requestQuerySchema = baseQuerySchema.extend({
|
|
502
|
+
methods: z5.enum(METHODS).array().default([]),
|
|
503
|
+
statuses: z5.number().array().default([]),
|
|
504
|
+
path: z5.string().optional()
|
|
505
|
+
});
|
|
506
|
+
var requestLogLeaves = resource3("requests").get({
|
|
507
|
+
feed: true,
|
|
508
|
+
outputSchema: requestSchema.array(),
|
|
509
|
+
querySchema: requestQuerySchema,
|
|
510
|
+
outputMetaSchema: z5.object({
|
|
511
|
+
totalCount: z5.number().optional()
|
|
512
|
+
})
|
|
513
|
+
}).sub(
|
|
514
|
+
resource3(":requestId", void 0, z5.string()).get({
|
|
515
|
+
outputSchema: requestSchema.extend({
|
|
516
|
+
// Related by groupId
|
|
517
|
+
// Do I just use the existing feed endpoints with filter: groupId=?
|
|
518
|
+
logs: z5.array(logSchema),
|
|
519
|
+
caches: z5.array(cacheLogSchema)
|
|
520
|
+
})
|
|
521
|
+
}).done()
|
|
522
|
+
).done();
|
|
523
|
+
|
|
524
|
+
// src/web/v2/types/types.endpoint.ts
|
|
525
|
+
var nodeKind = [
|
|
526
|
+
"object",
|
|
527
|
+
"string",
|
|
528
|
+
"number",
|
|
529
|
+
"array",
|
|
530
|
+
"enum",
|
|
531
|
+
"literal",
|
|
532
|
+
"union"
|
|
533
|
+
];
|
|
534
|
+
var serializableSchemaSchema = z6.lazy(
|
|
535
|
+
() => z6.object({
|
|
536
|
+
kind: z6.enum(nodeKind),
|
|
537
|
+
optional: z6.boolean().optional(),
|
|
538
|
+
nullable: z6.boolean().optional(),
|
|
539
|
+
description: z6.string().optional(),
|
|
540
|
+
// object
|
|
541
|
+
properties: z6.record(z6.string(), serializableSchemaSchema).optional(),
|
|
542
|
+
// array
|
|
543
|
+
element: serializableSchemaSchema.optional(),
|
|
544
|
+
// union
|
|
545
|
+
union: z6.array(serializableSchemaSchema).optional(),
|
|
546
|
+
// literal
|
|
547
|
+
literal: z6.unknown().optional(),
|
|
548
|
+
// enum
|
|
549
|
+
enumValues: z6.array(z6.string()).optional()
|
|
550
|
+
})
|
|
551
|
+
);
|
|
552
|
+
var STABILITIES = [
|
|
553
|
+
"experimental",
|
|
554
|
+
"beta",
|
|
555
|
+
"stable",
|
|
556
|
+
"deprecated"
|
|
557
|
+
];
|
|
558
|
+
var stabilityEnum = z6.enum(STABILITIES);
|
|
559
|
+
var endpointSchema = baseEntitySchema.extend({
|
|
560
|
+
method: z6.enum(METHODS),
|
|
561
|
+
path: z6.string(),
|
|
562
|
+
contract: z6.object({
|
|
563
|
+
body: serializableSchemaSchema.optional(),
|
|
564
|
+
query: serializableSchemaSchema.optional(),
|
|
565
|
+
output: serializableSchemaSchema.optional(),
|
|
566
|
+
params: serializableSchemaSchema.optional(),
|
|
567
|
+
bodyFiles: z6.object({ name: z6.string(), maxCount: z6.number() })
|
|
568
|
+
}),
|
|
569
|
+
feed: z6.boolean().optional(),
|
|
570
|
+
summary: z6.string().optional(),
|
|
571
|
+
stability: stabilityEnum,
|
|
572
|
+
hidden: z6.boolean().optional(),
|
|
573
|
+
meta: z6.record(z6.string(), z6.string())
|
|
574
|
+
});
|
|
575
|
+
var endpointFilterSchema = baseQuerySchema.extend({
|
|
576
|
+
methods: z6.enum(METHODS).array().optional(),
|
|
577
|
+
path: z6.string().optional(),
|
|
578
|
+
stability: stabilityEnum.array().optional()
|
|
579
|
+
});
|
|
580
|
+
var endpointLeaves = resource4("endpoints").get({
|
|
581
|
+
feed: true,
|
|
582
|
+
querySchema: endpointFilterSchema,
|
|
583
|
+
outputSchema: endpointSchema.array(),
|
|
584
|
+
outputMetaSchema: z6.object({
|
|
585
|
+
totalCount: z6.number().optional()
|
|
586
|
+
})
|
|
587
|
+
}).sub(
|
|
588
|
+
resource4(":endpointId", void 0, z6.string()).get({
|
|
589
|
+
outputSchema: endpointSchema.extend({
|
|
590
|
+
// Related by groupId. Just use the existing feed endpoints with filter: groupId=?
|
|
591
|
+
requests: z6.array(requestSchema),
|
|
592
|
+
// Summary stats: return with the feed?
|
|
593
|
+
volumeTS: z6.array(
|
|
594
|
+
z6.object({
|
|
595
|
+
timestamp: z6.string(),
|
|
596
|
+
count: z6.number()
|
|
597
|
+
})
|
|
598
|
+
),
|
|
599
|
+
averageDurationMs: z6.number(),
|
|
600
|
+
successRate: z6.number(),
|
|
601
|
+
// Add id as query param to the existing feed endpoints? This way "requests" field can also be only Ids
|
|
602
|
+
latestErrorRequestIds: z6.array(z6.string())
|
|
603
|
+
})
|
|
604
|
+
}).done()
|
|
605
|
+
).done();
|
|
606
|
+
|
|
607
|
+
// src/web/v2/types/types.preset.ts
|
|
608
|
+
import { resource as resource5 } from "@emeryld/rrroutes-contract";
|
|
609
|
+
import z7 from "zod";
|
|
610
|
+
var presetSchema = baseEntitySchema.extend({
|
|
611
|
+
operations: z7.array(
|
|
612
|
+
z7.object({
|
|
613
|
+
endpointId: z7.string().optional(),
|
|
614
|
+
method: z7.enum(METHODS),
|
|
615
|
+
path: z7.string(),
|
|
616
|
+
body: z7.json().optional(),
|
|
617
|
+
extraHeaders: z7.record(z7.string(), z7.any()).optional(),
|
|
618
|
+
query: z7.record(z7.string(), z7.any()).optional()
|
|
619
|
+
})
|
|
620
|
+
)
|
|
621
|
+
});
|
|
622
|
+
var presetQuerySchema = baseQuerySchema.extend({
|
|
623
|
+
name: z7.string().optional(),
|
|
624
|
+
tags: z7.string().array().optional(),
|
|
625
|
+
group: z7.string().optional()
|
|
626
|
+
});
|
|
627
|
+
var presetLeaves = resource5("presets").get({
|
|
628
|
+
feed: true,
|
|
629
|
+
querySchema: presetQuerySchema.array(),
|
|
630
|
+
outputMetaSchema: z7.object({
|
|
631
|
+
totalCount: z7.number().optional()
|
|
632
|
+
}),
|
|
633
|
+
outputSchema: presetSchema
|
|
634
|
+
}).post({
|
|
635
|
+
bodySchema: presetSchema,
|
|
636
|
+
outputSchema: presetSchema
|
|
637
|
+
}).put({
|
|
638
|
+
bodySchema: presetSchema,
|
|
639
|
+
outputSchema: presetSchema
|
|
640
|
+
}).done();
|
|
641
|
+
|
|
642
|
+
// src/web/utils/types.ts
|
|
643
|
+
var allLeaves = resource6().sub(
|
|
644
|
+
resource6("___rrroutes").sub(
|
|
645
|
+
endpointLeaves,
|
|
646
|
+
requestLogLeaves,
|
|
647
|
+
logLeaves,
|
|
648
|
+
cacheLeaves,
|
|
649
|
+
presetLeaves
|
|
650
|
+
).done()
|
|
651
|
+
).done();
|
|
652
|
+
var leaves = finalize(allLeaves);
|
|
653
|
+
|
|
654
|
+
// src/index.ts
|
|
655
|
+
function resolvePublicDir() {
|
|
656
|
+
const moduleDir = typeof __dirname !== "undefined" ? __dirname : path.dirname(fileURLToPath(import.meta.url));
|
|
657
|
+
const fromModule = path.resolve(moduleDir, "../public");
|
|
658
|
+
if (fs.existsSync(fromModule)) return fromModule;
|
|
659
|
+
const fallback = path.resolve(moduleDir, "../dist/public");
|
|
660
|
+
if (fs.existsSync(fallback)) return fallback;
|
|
661
|
+
return fromModule;
|
|
662
|
+
}
|
|
663
|
+
function mountRRRoutesDocs({
|
|
664
|
+
router,
|
|
665
|
+
leaves: leaves2,
|
|
666
|
+
auth = {}
|
|
667
|
+
}) {
|
|
668
|
+
const docsPath = "/__rrroutes/docs";
|
|
669
|
+
const publicDir = resolvePublicDir();
|
|
670
|
+
const assetsDir = path.join(publicDir, "assets");
|
|
671
|
+
const cspEnabled = auth.csp !== false;
|
|
672
|
+
const authEnabled = auth.enabled !== false;
|
|
673
|
+
const docsPassword = auth.password;
|
|
674
|
+
const authRealm = auth.realm || "RRRoutes Docs";
|
|
675
|
+
const allowedIps = auth.allowedIps ?? [];
|
|
676
|
+
const cookieName = auth.cookieName;
|
|
677
|
+
const cookieSecret = auth?.cookieSecret;
|
|
678
|
+
const customGuard = auth?.guardMiddleware;
|
|
679
|
+
const ipGuard = allowedIps.length > 0 ? createIpAllowListGuard(allowedIps) : void 0;
|
|
680
|
+
const authGuard = !authEnabled ? (_req, _res, next) => next() : customGuard ? customGuard : cookieName ? createCookieGuard(cookieName, cookieSecret) : docsPassword ? createPasswordGuard(docsPassword, authRealm) : createMissingPasswordGuard();
|
|
681
|
+
[docsPath, `${docsPath}/assets`, `__rrroutes/`].forEach((p) => {
|
|
682
|
+
if (ipGuard) router.use(p, ipGuard);
|
|
683
|
+
router.use(p, authGuard);
|
|
684
|
+
});
|
|
685
|
+
router.use(
|
|
686
|
+
`${docsPath}/assets`,
|
|
687
|
+
expressStatic(assetsDir, { immutable: true, maxAge: "365d" })
|
|
688
|
+
);
|
|
689
|
+
const docsRoutePaths = [docsPath, `${docsPath}/`, `${docsPath}/*id`];
|
|
690
|
+
router.get(docsRoutePaths, (_req, res) => {
|
|
691
|
+
const nonce = cspEnabled ? randomBytes(16).toString("base64") : void 0;
|
|
692
|
+
const html = renderLeafDocsHTML2(
|
|
693
|
+
leaves2.filter((leaf) => leaf.cfg.docsHidden !== true),
|
|
694
|
+
{
|
|
695
|
+
cspNonce: nonce,
|
|
696
|
+
assetBasePath: `${`${docsPath}/assets`}`,
|
|
697
|
+
docsBasePath: `${docsPath}`
|
|
698
|
+
}
|
|
699
|
+
);
|
|
700
|
+
applyDocsSecurityHeaders(res);
|
|
701
|
+
if (cspEnabled && nonce) {
|
|
702
|
+
res.setHeader(
|
|
703
|
+
"Content-Security-Policy",
|
|
704
|
+
[
|
|
705
|
+
"default-src 'self'",
|
|
706
|
+
`script-src 'self' 'nonce-${nonce}'`,
|
|
707
|
+
`style-src 'self' 'nonce-${nonce}'`,
|
|
708
|
+
"img-src 'self' data:",
|
|
709
|
+
"connect-src 'self'",
|
|
710
|
+
"font-src 'self'",
|
|
711
|
+
"frame-ancestors 'self'",
|
|
712
|
+
"object-src 'none'",
|
|
713
|
+
"base-uri 'self'"
|
|
714
|
+
].join("; ")
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
res.send(html);
|
|
718
|
+
});
|
|
719
|
+
return {
|
|
720
|
+
path: docsPath
|
|
721
|
+
};
|
|
934
722
|
}
|
|
935
723
|
export {
|
|
724
|
+
introspectSchema,
|
|
936
725
|
mountRRRoutesDocs,
|
|
937
726
|
renderLeafDocsHTML2 as renderLeafDocsHTML,
|
|
727
|
+
leaves as requiredRoutes,
|
|
938
728
|
serializeLeaf
|
|
939
729
|
};
|
|
940
730
|
//# sourceMappingURL=index.mjs.map
|