@firebreak/vitals 1.2.3 → 2.0.0

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.
@@ -1,25 +1,3 @@
1
- // src/auth.ts
2
- import { createHash, timingSafeEqual } from "crypto";
3
- function verifyToken(provided, expected) {
4
- if (!provided || !expected) return false;
5
- const providedHash = createHash("sha256").update(provided).digest();
6
- const expectedHash = createHash("sha256").update(expected).digest();
7
- return timingSafeEqual(providedHash, expectedHash);
8
- }
9
- function extractToken(options) {
10
- const { queryParams, authorizationHeader, queryParamName = "token" } = options;
11
- if (queryParams) {
12
- const value = queryParams[queryParamName];
13
- const str = Array.isArray(value) ? value[0] : value;
14
- if (str) return str;
15
- }
16
- if (authorizationHeader?.startsWith("Bearer ")) {
17
- const token = authorizationHeader.slice("Bearer ".length);
18
- if (token) return token;
19
- }
20
- return null;
21
- }
22
-
23
1
  // src/types.ts
24
2
  var Status = {
25
3
  HEALTHY: 2,
@@ -35,7 +13,7 @@ function statusToLabel(status) {
35
13
  return labels[status];
36
14
  }
37
15
  function toJson(response) {
38
- return {
16
+ const json = {
39
17
  status: statusToLabel(response.status),
40
18
  timestamp: response.timestamp,
41
19
  checks: Object.fromEntries(
@@ -45,64 +23,302 @@ function toJson(response) {
45
23
  ])
46
24
  )
47
25
  };
26
+ if (response.cachedAt !== void 0) {
27
+ json.cachedAt = response.cachedAt;
28
+ }
29
+ return json;
48
30
  }
49
31
  function httpStatusCode(status) {
50
32
  return status === Status.HEALTHY ? 200 : 503;
51
33
  }
52
34
 
53
35
  // src/handler.ts
54
- var RESERVED_METADATA_KEYS = ["status", "timestamp", "checks"];
36
+ var RESERVED_METADATA_KEYS = ["status", "timestamp", "checks", "cachedAt"];
55
37
  function createHealthcheckHandler(options) {
56
- const { registry, token: rawToken, queryParamName = "token", metadata = {} } = options;
57
- const token = rawToken || null;
38
+ const { registry, resolveDepth, metadata = {} } = options;
58
39
  for (const key of Object.keys(metadata)) {
59
40
  if (RESERVED_METADATA_KEYS.includes(key)) {
60
41
  throw new Error(`Metadata key '${key}' is reserved. Use a different key name.`);
61
42
  }
62
43
  }
63
44
  return async (req) => {
64
- if (token === null) {
65
- const body = {
66
- status: "ok",
67
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
68
- ...metadata
69
- };
70
- return { status: 200, body };
45
+ let depth = "shallow";
46
+ if (resolveDepth) {
47
+ try {
48
+ const result = await resolveDepth(req);
49
+ if (result === "deep" || result === "shallow") {
50
+ depth = result;
51
+ }
52
+ } catch {
53
+ }
71
54
  }
72
- const provided = extractToken({
73
- queryParams: req.queryParams,
74
- authorizationHeader: req.authorizationHeader,
75
- queryParamName
76
- });
77
- if (provided === null) {
78
- const body = {
79
- status: "ok",
80
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
81
- ...metadata
55
+ if (depth === "deep") {
56
+ const response = await registry.run();
57
+ return {
58
+ status: httpStatusCode(response.status),
59
+ body: { ...metadata, ...toJson(response) }
82
60
  };
83
- return { status: 200, body };
84
- }
85
- if (!verifyToken(provided, token)) {
86
- return { status: 403, body: { error: "Forbidden" } };
87
61
  }
88
- const response = await registry.run();
89
- return {
90
- status: httpStatusCode(response.status),
91
- body: { ...metadata, ...toJson(response) }
62
+ const body = {
63
+ status: "ok",
64
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
65
+ ...metadata
92
66
  };
67
+ return { status: 200, body };
93
68
  };
94
69
  }
95
70
 
71
+ // src/html.ts
72
+ function escapeHtml(str) {
73
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
74
+ }
75
+ function statusColor(status) {
76
+ switch (status) {
77
+ case "healthy":
78
+ case "ok":
79
+ return "#22C55E";
80
+ case "degraded":
81
+ return "#F59E0B";
82
+ case "outage":
83
+ return "#ED1C24";
84
+ default:
85
+ return "#ED1C24";
86
+ }
87
+ }
88
+ var DEEP_KNOWN_KEYS = /* @__PURE__ */ new Set(["status", "timestamp", "checks", "cachedAt"]);
89
+ function isDeepResponse(body) {
90
+ return "checks" in body && "status" in body && body.status !== "ok";
91
+ }
92
+ function isShallowResponse(body) {
93
+ return "status" in body && body.status === "ok";
94
+ }
95
+ function isErrorResponse(body) {
96
+ return "error" in body && !("status" in body);
97
+ }
98
+ function renderStatusBadge(label, color) {
99
+ return `<span style="
100
+ display: inline-flex;
101
+ align-items: center;
102
+ gap: 8px;
103
+ padding: 4px 12px;
104
+ border-radius: 9999px;
105
+ background: ${color}1A;
106
+ font-family: 'Inter', system-ui, sans-serif;
107
+ font-size: 12px;
108
+ font-weight: 600;
109
+ letter-spacing: 0.05em;
110
+ text-transform: uppercase;
111
+ color: ${color};
112
+ "><span style="
113
+ width: 8px;
114
+ height: 8px;
115
+ border-radius: 50%;
116
+ background: ${color};
117
+ box-shadow: 0 0 6px ${color}80;
118
+ "></span>${escapeHtml(label)}</span>`;
119
+ }
120
+ function renderMetadataItems(items) {
121
+ if (items.length === 0) return "";
122
+ return `<div style="
123
+ display: flex;
124
+ flex-wrap: wrap;
125
+ gap: 24px;
126
+ margin-top: 16px;
127
+ ">${items.map(
128
+ ([label, value]) => `<div>
129
+ <div style="
130
+ font-family: 'Inter', system-ui, sans-serif;
131
+ font-size: 10px;
132
+ font-weight: 600;
133
+ letter-spacing: 0.05em;
134
+ text-transform: uppercase;
135
+ color: #A1A1AA;
136
+ margin-bottom: 4px;
137
+ ">${escapeHtml(label)}</div>
138
+ <div style="
139
+ font-family: 'JetBrains Mono', monospace;
140
+ font-size: 13px;
141
+ color: #E4E4E7;
142
+ ">${escapeHtml(value)}</div>
143
+ </div>`
144
+ ).join("")}</div>`;
145
+ }
146
+ function renderCheckRow(name, check) {
147
+ const color = statusColor(check.status);
148
+ return `<div style="
149
+ display: flex;
150
+ align-items: center;
151
+ gap: 12px;
152
+ padding: 12px 0;
153
+ border-top: 1px solid #27272A;
154
+ ">
155
+ <span style="
156
+ width: 8px;
157
+ height: 8px;
158
+ border-radius: 50%;
159
+ background: ${color};
160
+ box-shadow: 0 0 6px ${color}80;
161
+ flex-shrink: 0;
162
+ "></span>
163
+ <span style="
164
+ font-family: 'Inter', system-ui, sans-serif;
165
+ font-size: 12px;
166
+ text-transform: uppercase;
167
+ letter-spacing: 0.05em;
168
+ color: ${color};
169
+ font-weight: 600;
170
+ min-width: 72px;
171
+ ">${escapeHtml(check.status)}</span>
172
+ <span style="
173
+ font-family: 'Inter', system-ui, sans-serif;
174
+ font-size: 14px;
175
+ font-weight: 500;
176
+ color: #E4E4E7;
177
+ flex: 1;
178
+ ">${escapeHtml(name)}</span>
179
+ <span style="
180
+ font-family: 'JetBrains Mono', monospace;
181
+ font-size: 12px;
182
+ color: #A1A1AA;
183
+ min-width: 60px;
184
+ text-align: right;
185
+ ">${escapeHtml(String(check.latencyMs))}ms</span>
186
+ <span style="
187
+ font-family: 'JetBrains Mono', monospace;
188
+ font-size: 12px;
189
+ color: #71717A;
190
+ max-width: 200px;
191
+ overflow: hidden;
192
+ text-overflow: ellipsis;
193
+ white-space: nowrap;
194
+ ">${escapeHtml(check.message)}</span>
195
+ </div>`;
196
+ }
197
+ function renderPage(borderColor, content) {
198
+ return `<!DOCTYPE html>
199
+ <html lang="en">
200
+ <head>
201
+ <meta charset="utf-8">
202
+ <meta name="viewport" content="width=device-width, initial-scale=1">
203
+ <title>Healthcheck</title>
204
+ <style></style>
205
+ </head>
206
+ <body style="
207
+ margin: 0;
208
+ padding: 40px 20px;
209
+ background: #08080A;
210
+ min-height: 100vh;
211
+ display: flex;
212
+ justify-content: center;
213
+ align-items: flex-start;
214
+ box-sizing: border-box;
215
+ ">
216
+ <div style="
217
+ width: 100%;
218
+ max-width: 560px;
219
+ background: #18181B;
220
+ border: 1px solid #27272A;
221
+ border-left: 3px solid ${borderColor};
222
+ border-radius: 8px;
223
+ padding: 24px;
224
+ ">
225
+ ${content}
226
+ </div>
227
+ </body>
228
+ </html>`;
229
+ }
230
+ function renderHealthcheckHtml(body) {
231
+ if (isErrorResponse(body)) {
232
+ const color = "#ED1C24";
233
+ return renderPage(
234
+ color,
235
+ `<div style="display: flex; align-items: center; justify-content: space-between;">
236
+ <span style="
237
+ font-family: 'Inter', system-ui, sans-serif;
238
+ font-size: 18px;
239
+ font-weight: 700;
240
+ color: #E4E4E7;
241
+ ">Healthcheck</span>
242
+ ${renderStatusBadge("ERROR", color)}
243
+ </div>
244
+ <div style="
245
+ margin-top: 16px;
246
+ font-family: 'JetBrains Mono', monospace;
247
+ font-size: 13px;
248
+ color: #EF4444;
249
+ ">${escapeHtml(body.error)}</div>`
250
+ );
251
+ }
252
+ if (isShallowResponse(body)) {
253
+ const color = statusColor("ok");
254
+ const { status: _, timestamp, ...rest } = body;
255
+ const metadataItems = Object.entries(rest).map(
256
+ ([k, v]) => [k, String(v)]
257
+ );
258
+ const allItems = [
259
+ ["timestamp", timestamp],
260
+ ...metadataItems
261
+ ];
262
+ return renderPage(
263
+ color,
264
+ `<div style="display: flex; align-items: center; justify-content: space-between;">
265
+ <span style="
266
+ font-family: 'Inter', system-ui, sans-serif;
267
+ font-size: 18px;
268
+ font-weight: 700;
269
+ color: #E4E4E7;
270
+ ">Healthcheck</span>
271
+ ${renderStatusBadge("OK", color)}
272
+ </div>
273
+ ${renderMetadataItems(allItems)}`
274
+ );
275
+ }
276
+ if (isDeepResponse(body)) {
277
+ const color = statusColor(body.status);
278
+ const { timestamp, checks } = body;
279
+ const metadataItems = Object.entries(body).filter(([k]) => !DEEP_KNOWN_KEYS.has(k)).map(([k, v]) => [k, String(v)]);
280
+ const allItems = [
281
+ ["timestamp", timestamp],
282
+ ...metadataItems
283
+ ];
284
+ const checkRows = Object.entries(checks).sort(([a], [b]) => a.localeCompare(b)).map(([name, check]) => renderCheckRow(name, check)).join("");
285
+ return renderPage(
286
+ color,
287
+ `<div style="display: flex; align-items: center; justify-content: space-between;">
288
+ <span style="
289
+ font-family: 'Inter', system-ui, sans-serif;
290
+ font-size: 18px;
291
+ font-weight: 700;
292
+ color: #E4E4E7;
293
+ ">Healthcheck</span>
294
+ ${renderStatusBadge(body.status, color)}
295
+ </div>
296
+ ${renderMetadataItems(allItems)}
297
+ <div style="margin-top: 20px;">
298
+ ${checkRows}
299
+ </div>`
300
+ );
301
+ }
302
+ return renderPage("#ED1C24", `<pre style="color: #E4E4E7; font-family: 'JetBrains Mono', monospace;">${escapeHtml(JSON.stringify(body, null, 2))}</pre>`);
303
+ }
304
+
96
305
  // src/integrations/express.ts
97
306
  function createHealthcheckMiddleware(options) {
98
307
  const handle = createHealthcheckHandler(options);
99
308
  return async (req, res) => {
100
309
  try {
101
310
  const result = await handle({
311
+ ip: req.ip,
312
+ headers: req.headers,
102
313
  queryParams: req.query,
103
314
  authorizationHeader: req.headers.authorization ?? null
104
315
  });
105
- res.status(result.status).json(result.body);
316
+ const preferred = req.accepts(["json", "html"]);
317
+ if (preferred === "html") {
318
+ res.status(result.status).type("html").send(renderHealthcheckHtml(result.body));
319
+ } else {
320
+ res.status(result.status).json(result.body);
321
+ }
106
322
  } catch {
107
323
  res.status(500).json({ error: "Internal Server Error" });
108
324
  }