hookdesk 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Petri Sandholm
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,309 @@
1
- # Temporary Holding Version
1
+ <img src="src/wordmark.svg" alt="HookDesk Mini" width="290" height="64">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/hookdesk.svg)](https://www.npmjs.com/package/hookdesk)
4
+ [![node](https://img.shields.io/badge/node-%3E%3D20-brightgreen)](https://nodejs.org)
5
+ [![license](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
6
+
7
+ Local-only webhook inspector. Point any webhook or HTTP client at `http://127.0.0.1:4317/hook/...` and watch requests land in a live browser dashboard, where you can inspect headers and bodies, copy them as cURL, and replay them. No account, no cloud, no database, and no npm dependencies. The npm package and the command are both **hookdesk**.
8
+
9
+ ## What It Does
10
+
11
+ - captures any HTTP method on any path under `/hook/`
12
+ - live activity timeline: one spike per request, colored by method, taller for bigger bodies
13
+ - live stats: requests in memory, requests in the last minute, time since the last request, total body size
14
+ - request table, newest first, with method, path, size, and age
15
+ - request detail with tabs: syntax-highlighted JSON body with line numbers, a headers table, and a ready cURL command
16
+ - replays a captured request to the local inbox, never to its original sender
17
+ - redacts credential headers (`authorization`, `cookie`, `x-api-key`, and more) in the dashboard and API
18
+ - keyboard navigation: `j` / `k` to move, `r` to replay, `c` to copy as cURL
19
+ - dark, light, or auto theme, remembered per browser
20
+ - every limit, path, header list, and UI setting is configurable through a JSON config file
21
+ - binds to `127.0.0.1` only, with `Host` and `Origin` checks
22
+
23
+ ## Requirements
24
+
25
+ - Node.js 20+
26
+ - macOS, Linux, or Windows
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ npm install -g hookdesk
32
+ ```
33
+
34
+ Or run it once without installing:
35
+
36
+ ```bash
37
+ npx hookdesk
38
+ ```
39
+
40
+ ### From source
41
+
42
+ ```bash
43
+ git clone https://github.com/psandis/hookdesk.git
44
+ cd hookdesk
45
+ npm link
46
+ hookdesk
47
+ ```
48
+
49
+ There is nothing to install or build: hookdesk has no dependencies. Without linking, use `npm start` in place of `hookdesk`.
50
+
51
+ ## Quick Start
52
+
53
+ Start the dashboard:
54
+
55
+ ```bash
56
+ hookdesk
57
+ ```
58
+
59
+ ```
60
+ HookDesk Mini is running
61
+ Dashboard: http://127.0.0.1:4317
62
+ Webhook: http://127.0.0.1:4317/hook
63
+ Example: curl -X POST http://127.0.0.1:4317/hook/demo -H 'Content-Type: application/json' -d '{"event":"hello"}'
64
+ ```
65
+
66
+ Open the dashboard URL in a browser, then send a test request from another terminal.
67
+
68
+ macOS / Linux:
69
+
70
+ ```bash
71
+ curl -X POST http://127.0.0.1:4317/hook/order.created \
72
+ -H 'Content-Type: application/json' \
73
+ -d '{"event":"order.created","orderId":123,"amount":49.90}'
74
+ ```
75
+
76
+ Windows (PowerShell):
77
+
78
+ ```powershell
79
+ Invoke-RestMethod -Method Post -Uri http://127.0.0.1:4317/hook/order.created `
80
+ -ContentType 'application/json' `
81
+ -Body '{"event":"order.created","orderId":123,"amount":49.90}'
82
+ ```
83
+
84
+ The request appears in the dashboard within the poll interval (1.5 seconds by default). Stop the server with `Ctrl+C`.
85
+
86
+ ## Dashboard
87
+
88
+ ### Header
89
+
90
+ - **Logo**: brand mark on the left
91
+ - **host / buffer / storage**: bind address, how many requests are kept, and where (memory)
92
+ - **Live**: whether the dashboard can reach the local server; turns to **Offline** when it cannot
93
+ - **Theme**: `Auto` follows the operating system, `Light` and `Dark` force a theme. The choice is remembered in the browser.
94
+
95
+ ### Stats
96
+
97
+ | Tile | Shows |
98
+ |---|---|
99
+ | Captured | Requests held in memory |
100
+ | Last 60 s | Requests received in the past minute |
101
+ | Last hit | Time since the newest request |
102
+ | In memory | Total size of all request bodies. Hover for the exact byte count. |
103
+
104
+ ### Activity timeline
105
+
106
+ The last 5 minutes (`ui.timelineWindowMs`) of traffic. Each spike is one request: its color is the HTTP method (see the legend), its height grows with the body size on a log scale. Hover a spike to preview the request, click it to open it. New requests pulse when they arrive.
107
+
108
+ ### Send a test
109
+
110
+ The command bar shows a ready `curl` command for your endpoint.
111
+
112
+ | Button | Action |
113
+ |---|---|
114
+ | Copy endpoint | Copies the base URL, for pasting into a webhook provider or your app |
115
+ | Copy curl | Copies the test command |
116
+ | Refresh | Reloads the request list immediately |
117
+ | Clear | Deletes all captured requests, after a confirmation |
118
+
119
+ ### Requests
120
+
121
+ A table of captured requests, newest first.
122
+
123
+ | Column | Description |
124
+ |---|---|
125
+ | Method | HTTP method, colored as in the timeline legend |
126
+ | Path | Path and query string. Replayed requests are marked `replay`. |
127
+ | Size | Body size. Hover for the exact byte count. |
128
+ | Age | Time since the request arrived, updated every second |
129
+
130
+ ### Request detail
131
+
132
+ Clicking a row opens the request with its path, method, received date and time, size, and short ID.
133
+
134
+ | Tab | Content |
135
+ |---|---|
136
+ | Body | The body as received. JSON is pretty-printed and syntax-highlighted with line numbers. |
137
+ | Headers | All headers. Sensitive values show as `[REDACTED]`. |
138
+ | cURL | A command that re-sends the request, without redacted headers |
139
+
140
+ **Replay locally** re-sends the request to this hookdesk inbox, never to the original sender. Credential headers and hop-by-hop headers are stripped; the body is re-sent unchanged. `CONNECT`, `TRACE`, and `TRACK` requests cannot be replayed.
141
+
142
+ ### Keyboard
143
+
144
+ | Key | Action |
145
+ |---|---|
146
+ | `j` or `Down` | Next request |
147
+ | `k` or `Up` | Previous request |
148
+ | `r` | Replay the selected request |
149
+ | `c` | Copy the selected request as cURL |
150
+
151
+ ## Configuration
152
+
153
+ All defaults live in [`config/default.json`](config/default.json). To change them, create a JSON file with only the keys you want to override and pass it with `--config`:
154
+
155
+ ```json
156
+ {
157
+ "capture": { "maxEvents": 50, "pathPrefix": "/inbox" },
158
+ "redaction": { "sensitiveHeaders": ["authorization", "cookie", "x-signature"] },
159
+ "ui": { "defaultTheme": "light" }
160
+ }
161
+ ```
162
+
163
+ ```bash
164
+ hookdesk --config=./hookdesk.config.json
165
+ ```
166
+
167
+ Values are merged in this order, later ones win:
168
+
169
+ 1. built-in defaults (`config/default.json`)
170
+ 2. the file passed with `--config=<path>`
171
+ 3. the `PORT` environment variable
172
+ 4. the `--port=<number>` flag
173
+
174
+ Changing the port:
175
+
176
+ ```bash
177
+ # macOS / Linux
178
+ hookdesk --port=4343
179
+ PORT=4343 hookdesk
180
+ ```
181
+
182
+ ```powershell
183
+ # Windows (PowerShell)
184
+ hookdesk --port=4343
185
+ $env:PORT=4343; hookdesk
186
+ ```
187
+
188
+ ### Settings
189
+
190
+ | Key | Type | Default | Description |
191
+ |---|---|---|---|
192
+ | `server.host` | string | `127.0.0.1` | Bind address. Must be loopback: `127.0.0.1`, `localhost`, or `::1` |
193
+ | `server.port` | integer | `4317` | Port. `0` picks a free port |
194
+ | `server.allowedHostnames` | string[] | `["127.0.0.1", "localhost"]` | Accepted `Host` and `Origin` hostnames. Loopback names only |
195
+ | `capture.pathPrefix` | string | `/hook` | Path under which requests are captured |
196
+ | `capture.maxBodyBytes` | integer | `1048576` | Body size limit (1 MiB). Larger bodies get HTTP 413 |
197
+ | `capture.maxEvents` | integer | `200` | Number of requests kept in memory |
198
+ | `replay.timeoutMs` | integer | `5000` | Replay request timeout |
199
+ | `replay.blockedMethods` | string[] | `["CONNECT", "TRACE", "TRACK"]` | Methods that cannot be replayed |
200
+ | `replay.excludedHeaders` | string[] | hop-by-hop and browser headers | Headers dropped on replay. Sensitive headers are always dropped too |
201
+ | `redaction.sensitiveHeaders` | string[] | `authorization`, `cookie`, `x-api-key`, ... | Headers shown as the placeholder in the dashboard and API |
202
+ | `redaction.placeholder` | string | `[REDACTED]` | Replacement text for redacted values |
203
+ | `ui.pollIntervalMs` | integer | `1500` | Dashboard refresh interval |
204
+ | `ui.timelineWindowMs` | integer | `300000` | Time span of the activity timeline (5 minutes) |
205
+ | `ui.defaultTheme` | string | `auto` | `auto`, `light`, or `dark`. Each viewer can still switch in the header |
206
+ | `ui.curlExcludedHeaders` | string[] | `host`, `content-length`, ... | Headers left out of "Copy as cURL" |
207
+
208
+ ### Validation
209
+
210
+ The configuration is validated at startup. Unknown keys (usually typos) and invalid values stop the server with exit code 1:
211
+
212
+ ```
213
+ $ hookdesk --config=./hookdesk.config.json
214
+ Unknown config key "capture.maxEvent"
215
+
216
+ $ hookdesk --port=abc
217
+ Invalid configuration:
218
+ - server.port must be an integer 0..65535 (0 picks a free port)
219
+ ```
220
+
221
+ ## Storage
222
+
223
+ hookdesk writes nothing to disk. Captured requests are held only in memory (the last `capture.maxEvents`, default 200) and are erased when the server stops or restarts. The only file it reads besides its own is the optional `--config` file. The theme choice is kept in the browser's `localStorage`.
224
+
225
+ ## API
226
+
227
+ hookdesk exposes a local REST API on the same port as the dashboard.
228
+
229
+ | Method | Path | Description |
230
+ |---|---|---|
231
+ | any | `/hook`, `/hook/*` | Capture a request |
232
+ | `GET` | `/api/events` | List captured requests (summaries, no headers or body) |
233
+ | `GET` | `/api/events/:id` | One request with redacted headers and the body |
234
+ | `POST` | `/api/events/:id/replay` | Replay a request to the local inbox |
235
+ | `DELETE` | `/api/events` | Clear all captured requests |
236
+ | `GET` | `/api/config` | Settings the dashboard uses |
237
+
238
+ All endpoints return JSON.
239
+
240
+ ## Security
241
+
242
+ - Binds to loopback only. `Host` and `Origin` checks block DNS rebinding and cross-site requests from web pages.
243
+ - The dashboard is served with a strict Content Security Policy and no inline scripts or styles.
244
+ - Sensitive headers are redacted in the dashboard and API. **Bodies are not redacted**, so do not send production credentials or personal data to it.
245
+ - hookdesk is not a tunnel. To receive webhooks from an external provider, use a trusted tunnel separately.
246
+ - Bodies are stored as UTF-8 text; binary payloads are not supported yet.
247
+
248
+ ## Testing
249
+
250
+ ```bash
251
+ npm test
252
+ ```
253
+
254
+ Current bar:
255
+
256
+ - 30 tests across config loading and the HTTP server, using the built-in Node.js test runner
257
+ - integration tests run a real HTTP server on port 0
258
+ - expected defaults are read from `config/default.json`, so changing a setting does not break tests; only the security requirements (loopback binding, `authorization` redaction, blocked replay methods) are fixed values
259
+ - the `hookdesk` command is tested by launching it through a symlink, the way `npm install -g` runs it
260
+
261
+ ## Tech Stack
262
+
263
+ | Tool | Purpose |
264
+ |---|---|
265
+ | Node.js 20+ | Runtime |
266
+ | node:http | HTTP server, no framework |
267
+ | Vanilla JS / HTML / CSS | Dashboard, no frontend framework, no build step |
268
+ | Canvas 2D | Activity timeline |
269
+ | node:test | Testing |
270
+
271
+ ## File Structure
272
+
273
+ ```
274
+ hookdesk/
275
+ ├── config/
276
+ │ └── default.json default settings
277
+ ├── src/
278
+ │ ├── server.js HTTP server, API, and the hookdesk command
279
+ │ ├── config.js config loading, merging, and validation
280
+ │ ├── ui.html dashboard markup
281
+ │ ├── ui.css dashboard styles and themes
282
+ │ ├── ui.js dashboard logic and timeline
283
+ │ ├── logo.svg logo and favicon
284
+ │ └── wordmark.svg README wordmark
285
+ ├── tests/
286
+ │ ├── config.test.js
287
+ │ └── server.test.js
288
+ ├── package.json
289
+ ├── LICENSE
290
+ └── README.md
291
+ ```
292
+
293
+ ## Next Steps
294
+
295
+ 1. Configurable mocked responses (status, body, and delay per path)
296
+ 2. Request filtering and search
297
+ 3. Export and import of captured requests as JSON
298
+ 4. Binary payload support
299
+
300
+ ## Related
301
+
302
+ - [wiremonitor](https://github.com/psandis/wiremonitor): Network traffic web dashboard
303
+ - [portmind](https://github.com/psandis/portmind): Scan listening ports and remember what normally runs where
304
+ - [mydevkit](https://github.com/psandis/mydevkit): Everyday developer tools in one CLI
305
+ - [nscout](https://github.com/psandis/nscout): Scout a name across npm, GitHub, PyPI, and domain registries
306
+
307
+ ## License
308
+
309
+ See [MIT](LICENSE)
@@ -0,0 +1,57 @@
1
+ {
2
+ "server": {
3
+ "host": "127.0.0.1",
4
+ "port": 4317,
5
+ "allowedHostnames": ["127.0.0.1", "localhost"]
6
+ },
7
+ "capture": {
8
+ "pathPrefix": "/hook",
9
+ "maxBodyBytes": 1048576,
10
+ "maxEvents": 200
11
+ },
12
+ "replay": {
13
+ "timeoutMs": 5000,
14
+ "blockedMethods": ["CONNECT", "TRACE", "TRACK"],
15
+ "excludedHeaders": [
16
+ "host",
17
+ "origin",
18
+ "referer",
19
+ "content-length",
20
+ "connection",
21
+ "keep-alive",
22
+ "transfer-encoding",
23
+ "te",
24
+ "trailer",
25
+ "upgrade",
26
+ "expect",
27
+ "accept-encoding"
28
+ ]
29
+ },
30
+ "redaction": {
31
+ "placeholder": "[REDACTED]",
32
+ "sensitiveHeaders": [
33
+ "authorization",
34
+ "proxy-authorization",
35
+ "cookie",
36
+ "set-cookie",
37
+ "x-api-key",
38
+ "api-key",
39
+ "x-auth-token"
40
+ ]
41
+ },
42
+ "ui": {
43
+ "pollIntervalMs": 1500,
44
+ "timelineWindowMs": 300000,
45
+ "defaultTheme": "auto",
46
+ "curlExcludedHeaders": [
47
+ "host",
48
+ "content-length",
49
+ "connection",
50
+ "keep-alive",
51
+ "transfer-encoding",
52
+ "expect",
53
+ "accept-encoding",
54
+ "x-hookdesk-replay"
55
+ ]
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "hookdesk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Local-only webhook inspector: capture, inspect, and replay HTTP requests in a live browser dashboard",
5
+ "keywords": [
6
+ "webhook",
7
+ "webhooks",
8
+ "http",
9
+ "inspector",
10
+ "request-bin",
11
+ "replay",
12
+ "debugging",
13
+ "dashboard",
14
+ "local-first",
15
+ "developer-tools"
16
+ ],
17
+ "author": "Petri Sandholm <petri.sandholm@gmail.com>",
18
+ "homepage": "https://github.com/psandis/hookdesk#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/psandis/hookdesk/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/psandis/hookdesk.git"
25
+ },
26
+ "type": "module",
27
+ "bin": {
28
+ "hookdesk": "./src/server.js"
29
+ },
30
+ "files": [
31
+ "src",
32
+ "config",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "scripts": {
37
+ "start": "node src/server.js",
38
+ "dev": "node --watch src/server.js",
39
+ "test": "node --test"
40
+ },
41
+ "engines": {
42
+ "node": ">=20"
43
+ },
44
+ "license": "MIT"
45
+ }
package/src/config.js ADDED
@@ -0,0 +1,71 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ export const defaultConfigPath = fileURLToPath(new URL('../config/default.json', import.meta.url));
5
+ const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'];
6
+ const LOOPBACK_HOSTNAMES = ['127.0.0.1', 'localhost', '[::1]'];
7
+
8
+ export function readConfigFile(path) {
9
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
10
+ catch (error) { throw new Error(`Cannot read config file ${path}: ${error.message}`); }
11
+ }
12
+
13
+ // Merges one level deep: each section is merged key by key, arrays are replaced whole.
14
+ // Unknown sections and keys are rejected so typos never pass silently.
15
+ export function mergeConfig(base, override = {}) {
16
+ const merged = {};
17
+ for (const [section, values] of Object.entries(override)) {
18
+ if (!(section in base)) throw new Error(`Unknown config section "${section}"`);
19
+ if (typeof values !== 'object' || values === null || Array.isArray(values)) throw new Error(`Config section "${section}" must be an object`);
20
+ for (const key of Object.keys(values)) if (!(key in base[section])) throw new Error(`Unknown config key "${section}.${key}"`);
21
+ }
22
+ for (const section of Object.keys(base)) merged[section] = { ...base[section], ...(override[section] || {}) };
23
+ return merged;
24
+ }
25
+
26
+ const isInt = (value, min, max) => Number.isInteger(value) && value >= min && value <= max;
27
+ const isStringList = value => Array.isArray(value) && value.every(x => typeof x === 'string' && x.length > 0);
28
+
29
+ export function validateConfig(config) {
30
+ const { server, capture, replay, redaction, ui } = config;
31
+ const errors = [];
32
+ const check = (ok, message) => { if (!ok) errors.push(message); };
33
+ check(LOOPBACK_HOSTS.includes(server.host), `server.host must be a loopback address (${LOOPBACK_HOSTS.join(', ')})`);
34
+ check(isInt(server.port, 0, 65535), 'server.port must be an integer 0..65535 (0 picks a free port)');
35
+ check(isStringList(server.allowedHostnames) && server.allowedHostnames.length > 0 && server.allowedHostnames.every(x => LOOPBACK_HOSTNAMES.includes(x)), `server.allowedHostnames must be a non-empty list of ${LOOPBACK_HOSTNAMES.join(', ')}`);
36
+ check(isStringList(server.allowedHostnames) && server.allowedHostnames.includes(server.host === '::1' ? '[::1]' : server.host), 'server.allowedHostnames must include server.host');
37
+ check(typeof capture.pathPrefix === 'string' && /^\/[A-Za-z0-9._~-]+(\/[A-Za-z0-9._~-]+)*$/.test(capture.pathPrefix) && !/^\/(api|ui\.)/.test(capture.pathPrefix), 'capture.pathPrefix must look like "/hook" (no trailing slash, not under /api)');
38
+ check(isInt(capture.maxBodyBytes, 1, 100 * 1024 * 1024), 'capture.maxBodyBytes must be an integer 1..104857600');
39
+ check(isInt(capture.maxEvents, 1, 100000), 'capture.maxEvents must be an integer 1..100000');
40
+ check(isInt(replay.timeoutMs, 100, 60000), 'replay.timeoutMs must be an integer 100..60000');
41
+ check(isStringList(replay.blockedMethods), 'replay.blockedMethods must be a list of method names');
42
+ check(isStringList(replay.excludedHeaders), 'replay.excludedHeaders must be a list of header names');
43
+ check(typeof redaction.placeholder === 'string' && redaction.placeholder.length > 0, 'redaction.placeholder must be a non-empty string');
44
+ check(isStringList(redaction.sensitiveHeaders), 'redaction.sensitiveHeaders must be a list of header names');
45
+ check(isInt(ui.pollIntervalMs, 250, 60000), 'ui.pollIntervalMs must be an integer 250..60000');
46
+ check(isInt(ui.timelineWindowMs, 10000, 86400000), 'ui.timelineWindowMs must be an integer 10000..86400000');
47
+ check(['auto', 'light', 'dark'].includes(ui.defaultTheme), 'ui.defaultTheme must be "auto", "light" or "dark"');
48
+ check(isStringList(ui.curlExcludedHeaders), 'ui.curlExcludedHeaders must be a list of header names');
49
+ if (errors.length) throw new Error(`Invalid configuration:\n - ${errors.join('\n - ')}`);
50
+ }
51
+
52
+ function normalize(config) {
53
+ const lower = list => list.map(x => x.toLowerCase());
54
+ return {
55
+ ...config,
56
+ replay: { ...config.replay, blockedMethods: config.replay.blockedMethods.map(x => x.toUpperCase()), excludedHeaders: lower(config.replay.excludedHeaders) },
57
+ redaction: { ...config.redaction, sensitiveHeaders: lower(config.redaction.sensitiveHeaders) },
58
+ ui: { ...config.ui, curlExcludedHeaders: lower(config.ui.curlExcludedHeaders) },
59
+ };
60
+ }
61
+
62
+ const deepFreeze = value => { if (value && typeof value === 'object') { Object.values(value).forEach(deepFreeze); Object.freeze(value); } return value; };
63
+
64
+ // Precedence: config/default.json < file (--config) < overrides (PORT, --port, tests).
65
+ export function loadConfig({ file, overrides } = {}) {
66
+ let config = readConfigFile(defaultConfigPath);
67
+ if (file) config = mergeConfig(config, readConfigFile(file));
68
+ if (overrides) config = mergeConfig(config, overrides);
69
+ validateConfig(config);
70
+ return deepFreeze(normalize(config));
71
+ }
package/src/logo.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" fill="none">
2
+ <title>Hookdesk</title>
3
+ <rect width="40" height="40" rx="11" fill="#c6ff3d"/>
4
+ <path d="M13 13v10a8 8 0 0 0 16 0v-3" stroke="#0b0e02" stroke-width="3.5" stroke-linecap="round"/>
5
+ <path d="m30.75 14-7 8 5.25-1 1.75 3Z" fill="#0b0e02"/>
6
+ <circle cx="13" cy="10" r="3" stroke="#0b0e02" stroke-width="2.5"/>
7
+ </svg>
package/src/server.js ADDED
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+ import http from 'node:http';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { realpathSync } from 'node:fs';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { loadConfig } from './config.js';
8
+
9
+ const REPLAY_HEADER = 'x-hookdesk-replay';
10
+ const DASHBOARD_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'";
11
+ const STATIC_FILES = {
12
+ '/': { file: 'ui.html', type: 'text/html; charset=utf-8', headers: { 'x-frame-options': 'DENY', 'content-security-policy': DASHBOARD_CSP } },
13
+ '/ui.js': { file: 'ui.js', type: 'text/javascript; charset=utf-8' },
14
+ '/ui.css': { file: 'ui.css', type: 'text/css; charset=utf-8' },
15
+ '/logo.svg': { file: 'logo.svg', type: 'image/svg+xml' },
16
+ };
17
+
18
+ export function redactHeaders(headers, { sensitiveHeaders, placeholder } = loadConfig().redaction) {
19
+ const sensitive = new Set(sensitiveHeaders);
20
+ return Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, sensitive.has(key.toLowerCase()) ? placeholder : value]));
21
+ }
22
+
23
+ export async function readBody(req, limit) {
24
+ const chunks = [];
25
+ let total = 0;
26
+ for await (const chunk of req) {
27
+ total += chunk.length;
28
+ if (total > limit) { const error = new Error(`Payload exceeds ${limit} bytes`); error.status = 413; throw error; }
29
+ chunks.push(chunk);
30
+ }
31
+ return Buffer.concat(chunks).toString('utf8');
32
+ }
33
+
34
+ function respond(res, status, value, extraHeaders = {}) {
35
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...extraHeaders });
36
+ res.end(JSON.stringify(value));
37
+ }
38
+
39
+ const summarize = ({ id, timestamp, method, path, bytes, replayOf }) => ({ id, timestamp, method, path, bytes, replayOf });
40
+ const hostnameOf = value => { try { return new URL(`http://${value}`).hostname; } catch { return null; } };
41
+
42
+ export function createApp({ config = loadConfig() } = {}) {
43
+ const { capture, replay, redaction, ui } = config;
44
+ const events = [];
45
+ const allowedHostnames = new Set(config.server.allowedHostnames);
46
+ const listenHost = config.server.host === '::1' ? '[::1]' : config.server.host;
47
+ const notForwarded = new Set([...redaction.sensitiveHeaders, ...replay.excludedHeaders, REPLAY_HEADER]);
48
+ const safeView = event => ({ ...event, headers: redactHeaders(event.headers, redaction) });
49
+ const publicConfig = { host: config.server.host, captureBase: capture.pathPrefix, maxEvents: capture.maxEvents, maxBodyBytes: capture.maxBodyBytes, pollIntervalMs: ui.pollIntervalMs, timelineWindowMs: ui.timelineWindowMs, defaultTheme: ui.defaultTheme, curlExcludedHeaders: ui.curlExcludedHeaders, redactedPlaceholder: redaction.placeholder };
50
+
51
+ const handler = async (req, res) => {
52
+ // Not intended as an externally exposed service; reject foreign hosts (DNS rebinding) and cross-site browser requests.
53
+ const host = req.headers.host || '';
54
+ if (!/^[A-Za-z0-9.:[\]-]+$/.test(host) || !allowedHostnames.has(hostnameOf(host))) return respond(res, 403, { error: 'Only localhost is allowed' });
55
+ const origin = req.headers.origin;
56
+ if (origin) {
57
+ try { const u = new URL(origin); if (u.protocol !== 'http:' || !allowedHostnames.has(u.hostname) || u.port !== String(server.address().port)) return respond(res, 403, { error: 'Cross-origin requests are blocked' }); }
58
+ catch { return respond(res, 403, { error: 'Invalid origin' }); }
59
+ }
60
+ const url = new URL(req.url || '/', `http://${host}`);
61
+ try {
62
+ const staticFile = STATIC_FILES[url.pathname];
63
+ if ((req.method === 'GET' || req.method === 'HEAD') && staticFile) {
64
+ const content = await readFile(fileURLToPath(new URL(`./${staticFile.file}`, import.meta.url)));
65
+ res.writeHead(200, { 'content-type': staticFile.type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...staticFile.headers });
66
+ res.end(req.method === 'HEAD' ? undefined : content);
67
+ return;
68
+ }
69
+ if (req.method === 'GET' && url.pathname === '/api/config') return respond(res, 200, publicConfig);
70
+ if (req.method === 'GET' && url.pathname === '/api/events') return respond(res, 200, { events: events.map(summarize), count: events.length });
71
+ if (req.method === 'DELETE' && url.pathname === '/api/events') { events.splice(0); return respond(res, 200, { ok: true }); }
72
+ const detailMatch = url.pathname.match(/^\/api\/events\/([^/]+)$/);
73
+ if (req.method === 'GET' && detailMatch) {
74
+ const event = events.find(x => x.id === detailMatch[1]);
75
+ return event ? respond(res, 200, { event: safeView(event) }) : respond(res, 404, { error: 'Event not found' });
76
+ }
77
+ const replayMatch = url.pathname.match(/^\/api\/events\/([^/]+)\/replay$/);
78
+ if (req.method === 'POST' && replayMatch) {
79
+ const source = events.find(x => x.id === replayMatch[1]);
80
+ if (!source) return respond(res, 404, { error: 'Event not found' });
81
+ if (replay.blockedMethods.includes(source.method)) return respond(res, 400, { error: `${source.method} requests cannot be replayed` });
82
+ // Replay stays inside this app. Credentials, hop-by-hop and browser-controlled headers are never forwarded.
83
+ const headers = Object.fromEntries(Object.entries(source.headers).filter(([key]) => !notForwarded.has(key.toLowerCase())));
84
+ headers[REPLAY_HEADER] = source.id;
85
+ const destination = `http://${listenHost}:${server.address().port}${source.path}`;
86
+ let result;
87
+ try {
88
+ result = await fetch(destination, { method: source.method, headers, body: ['GET', 'HEAD'].includes(source.method) ? undefined : source.body, signal: AbortSignal.timeout(replay.timeoutMs) });
89
+ await result.body?.cancel();
90
+ } catch (error) { return respond(res, 502, { error: `Replay failed: ${error.cause?.message || error.message}` }); }
91
+ return respond(res, 200, { ok: true, responseStatus: result.status });
92
+ }
93
+ if (url.pathname === capture.pathPrefix || url.pathname.startsWith(`${capture.pathPrefix}/`)) {
94
+ const body = await readBody(req, capture.maxBodyBytes);
95
+ const event = { id: randomUUID(), timestamp: new Date().toISOString(), method: req.method, path: url.pathname + url.search, headers: { ...req.headers }, body, bytes: Buffer.byteLength(body), replayOf: req.headers[REPLAY_HEADER] || null };
96
+ events.unshift(event);
97
+ if (events.length > capture.maxEvents) events.length = capture.maxEvents;
98
+ return respond(res, 200, { received: true, id: event.id });
99
+ }
100
+ return respond(res, 404, { error: 'Not found' });
101
+ } catch (error) {
102
+ const status = error.status || 500;
103
+ // Close the connection on 413 so the client stops streaming the rest of the oversized body.
104
+ return respond(res, status, { error: error.status ? error.message : 'Internal server error' }, status === 413 ? { connection: 'close' } : {});
105
+ }
106
+ };
107
+ const server = http.createServer(handler);
108
+ return { server, events, config };
109
+ }
110
+
111
+ const argValue = name => process.argv.find(x => x.startsWith(`--${name}=`))?.slice(name.length + 3);
112
+ // Resolve symlinks so the server also starts when launched through an npm bin link.
113
+ const isMain = () => { try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)); } catch { return false; } };
114
+
115
+ if (process.argv[1] && isMain()) {
116
+ const port = argValue('port') ?? process.env.PORT;
117
+ let config;
118
+ try { config = loadConfig({ file: argValue('config'), overrides: port === undefined ? undefined : { server: { port: Number(port) } } }); }
119
+ catch (error) { console.error(error.message); process.exit(1); }
120
+ const { server } = createApp({ config });
121
+ server.on('error', error => { console.error(`Cannot start HookDesk Mini: ${error.message}`); process.exit(1); });
122
+ server.listen(config.server.port, config.server.host, () => {
123
+ const host = config.server.host === '::1' ? '[::1]' : config.server.host;
124
+ const base = `http://${host}:${server.address().port}`;
125
+ console.log(`\n HookDesk Mini is running`);
126
+ console.log(` Dashboard: ${base}`);
127
+ console.log(` Webhook: ${base}${config.capture.pathPrefix}`);
128
+ console.log(` Example: curl -X POST ${base}${config.capture.pathPrefix}/demo -H 'Content-Type: application/json' -d '{"event":"hello"}'\n`);
129
+ });
130
+ }
package/src/ui.css ADDED
@@ -0,0 +1,222 @@
1
+ /* Dark is the base theme. Light applies via [data-theme="light"], or via the OS when the theme is "auto". */
2
+ :root {
3
+ --bg: #09090a;
4
+ --surface: #0e0e10;
5
+ --raise: #151518;
6
+ --hover: #1b1b1f;
7
+ --line: #1f1f23;
8
+ --line-strong: #2c2c31;
9
+ --text: #ededef;
10
+ --dim: #8b8b94;
11
+ --faint: #5f5f68;
12
+ --accent: #c6ff3d;
13
+ --accent-hover: #d7ff73;
14
+ --accent-ink: #0b0e02;
15
+ --accent-text: #c6ff3d;
16
+ --danger: #ff5c5c;
17
+ --m-get: #7cc4ff;
18
+ --m-post: #c6ff3d;
19
+ --m-put: #ffb547;
20
+ --m-patch: #ffb547;
21
+ --m-delete: #ff5c5c;
22
+ --m-other: #b69cff;
23
+ --t-key: #9ecbff;
24
+ --t-str: #b8e86c;
25
+ --t-num: #ffb547;
26
+ --t-lit: #ff86c2;
27
+ --shadow: rgba(0,0,0,.5);
28
+ color-scheme: dark;
29
+ }
30
+ @media (prefers-color-scheme: light) {
31
+ :root:not([data-theme="dark"]) {
32
+ --bg: #f6f6f7; --surface: #ffffff; --raise: #efeff1; --hover: #e7e7ea; --line: #e3e3e7; --line-strong: #cfcfd5;
33
+ --text: #0b0b0d; --dim: #55555e; --faint: #8e8e97;
34
+ --accent: #4d7c0f; --accent-hover: #3f6a08; --accent-ink: #ffffff; --accent-text: #3f6a08; --danger: #d42020;
35
+ --m-get: #0b69b3; --m-post: #4d7c0f; --m-put: #b45309; --m-patch: #b45309; --m-delete: #d42020; --m-other: #7034d6;
36
+ --t-key: #0550ae; --t-str: #3f6212; --t-num: #b45309; --t-lit: #be185d; --shadow: rgba(20,20,30,.12);
37
+ color-scheme: light;
38
+ }
39
+ }
40
+ :root[data-theme="light"] {
41
+ --bg: #f6f6f7; --surface: #ffffff; --raise: #efeff1; --hover: #e7e7ea; --line: #e3e3e7; --line-strong: #cfcfd5;
42
+ --text: #0b0b0d; --dim: #55555e; --faint: #8e8e97;
43
+ --accent: #4d7c0f; --accent-hover: #3f6a08; --accent-ink: #ffffff; --accent-text: #3f6a08; --danger: #d42020;
44
+ --m-get: #0b69b3; --m-post: #4d7c0f; --m-put: #b45309; --m-patch: #b45309; --m-delete: #d42020; --m-other: #7034d6;
45
+ --t-key: #0550ae; --t-str: #3f6212; --t-num: #b45309; --t-lit: #be185d; --shadow: rgba(20,20,30,.12);
46
+ color-scheme: light;
47
+ }
48
+ :root {
49
+ --sans: "Inter Display", Inter, -apple-system, "SF Pro Display", "Segoe UI Variable Display", system-ui, sans-serif;
50
+ --mono: "JetBrains Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace;
51
+ --pad: clamp(16px, 2.4vw, 32px);
52
+ }
53
+
54
+ * { box-sizing: border-box; }
55
+ html, body { height: 100%; }
56
+ body { margin: 0; background: var(--bg); color: var(--text); font-family: var(--sans); font-size: 14px; -webkit-font-smoothing: antialiased; display: flex; flex-direction: column; }
57
+ ::selection { background: var(--accent); color: var(--accent-ink); }
58
+ button { font: inherit; color: inherit; cursor: pointer; }
59
+ :focus-visible { outline: 1.5px solid var(--accent); outline-offset: 2px; }
60
+ kbd { display: inline-grid; place-items: center; min-width: 18px; height: 18px; padding: 0 4px; margin-right: 3px; border: 1px solid var(--line-strong); border-bottom-width: 2px; border-radius: 4px; font-family: var(--mono); font-size: 10px; color: var(--dim); }
61
+ .keys { font-family: var(--mono); font-size: 11px; color: var(--faint); }
62
+
63
+ /* Header */
64
+ .top { display: flex; align-items: center; gap: 28px; height: 52px; padding: 0 var(--pad); border-bottom: 1px solid var(--line); }
65
+ .brand { display: flex; align-items: center; gap: 10px; }
66
+ .brand-mark { display: block; flex-shrink: 0; }
67
+ .brand-name { font-weight: 600; font-size: 15px; letter-spacing: -.02em; }
68
+ .brand-tag { font-family: var(--mono); font-size: 10px; color: var(--dim); border: 1px solid var(--line-strong); border-radius: 4px; padding: 1px 5px; }
69
+ .top-meta { display: flex; gap: 22px; margin-left: auto; font-family: var(--mono); font-size: 11px; }
70
+ .kv .k { color: var(--faint); margin-right: 7px; }
71
+ .kv .v { color: var(--dim); }
72
+ .live { display: flex; align-items: center; gap: 8px; font-family: var(--mono); font-size: 11px; color: var(--accent-text); }
73
+ .live-dot { position: relative; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); }
74
+ .live-dot::after { content: ""; position: absolute; inset: -4px; border-radius: 50%; border: 1px solid var(--accent); animation: ping 1.8s cubic-bezier(0,0,.2,1) infinite; }
75
+ .live.offline { color: var(--danger); }
76
+ .live.offline .live-dot { background: var(--danger); }
77
+ .live.offline .live-dot::after { display: none; }
78
+
79
+ /* Scope: stats + timeline */
80
+ .scope { display: grid; grid-template-columns: minmax(280px, 380px) 1fr; border-bottom: 1px solid var(--line); }
81
+ .stats { display: grid; grid-template-columns: 1fr 1fr; border-right: 1px solid var(--line); }
82
+ .stat { padding: 18px var(--pad) 16px; border-bottom: 1px solid var(--line); }
83
+ .stat:nth-child(odd) { border-right: 1px solid var(--line); }
84
+ .stat:nth-last-child(-n+2) { border-bottom: 0; }
85
+ .stat-k { font-family: var(--mono); font-size: 10.5px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); }
86
+ .stat-v { margin-top: 8px; font-size: clamp(26px, 2.6vw, 38px); font-weight: 500; letter-spacing: -.045em; line-height: 1; font-variant-numeric: tabular-nums; white-space: nowrap; }
87
+ .stat { min-width: 0; }
88
+ .stat-v { overflow: hidden; text-overflow: ellipsis; }
89
+ .stat-v .unit { margin-left: 6px; font-size: 13px; font-weight: 400; letter-spacing: 0; color: var(--dim); }
90
+ .stat-v.bump { animation: bump .6s cubic-bezier(.2,.8,.2,1); }
91
+ .scope-chart { position: relative; padding: 14px var(--pad) 8px; min-width: 0; background: radial-gradient(120% 140% at 100% 0%, rgba(198,255,61,.05), transparent 55%); }
92
+ #scope { display: block; width: 100%; height: 132px; cursor: crosshair; }
93
+ .scope-axis { display: flex; justify-content: space-between; margin-top: 6px; font-family: var(--mono); font-size: 10px; color: var(--faint); font-variant-numeric: tabular-nums; }
94
+
95
+ /* Command bar */
96
+ .command { display: flex; align-items: center; gap: 14px; padding: 12px var(--pad); border-bottom: 1px solid var(--line); background: var(--surface); }
97
+ .prompt { font-family: var(--mono); color: var(--accent-text); }
98
+ .command-text { flex: 1; min-width: 0; font-family: var(--mono); font-size: 12.5px; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
99
+ .command-text .url { color: var(--text); }
100
+ .command-actions { display: flex; gap: 6px; }
101
+
102
+ /* Buttons */
103
+ .btn { height: 30px; padding: 0 12px; border: 1px solid var(--line-strong); border-radius: 6px; background: var(--raise); font-size: 12.5px; font-weight: 500; letter-spacing: -.005em; transition: border-color .15s, background .15s, color .15s, transform .1s; white-space: nowrap; }
104
+ .btn:hover { border-color: var(--faint); background: var(--hover); }
105
+ .btn:active { transform: translateY(1px); }
106
+ .btn:disabled { opacity: .4; cursor: not-allowed; }
107
+ .btn-primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; }
108
+ .btn-primary:hover { background: var(--accent-hover); border-color: var(--accent-hover); }
109
+ .btn-ghost { background: transparent; border-color: transparent; color: var(--dim); }
110
+ .btn-ghost:hover { background: var(--raise); border-color: var(--line-strong); color: var(--text); }
111
+ .btn-danger:hover { color: var(--danger); }
112
+
113
+ /* Split panes */
114
+ .split { flex: 1; display: grid; grid-template-columns: minmax(340px, 5fr) 7fr; min-height: 0; }
115
+ .pane { min-width: 0; min-height: 0; display: flex; flex-direction: column; }
116
+ .pane-list { border-right: 1px solid var(--line); }
117
+ .pane-head { display: flex; align-items: center; justify-content: space-between; height: 44px; padding: 0 var(--pad); border-bottom: 1px solid var(--line); }
118
+ .pane-title { font-weight: 600; font-size: 13px; }
119
+ .table-head, .row { display: grid; grid-template-columns: 62px minmax(0, 1fr) 84px 46px; gap: 12px; align-items: center; padding: 0 var(--pad); }
120
+ .table-head { height: 30px; border-bottom: 1px solid var(--line); font-family: var(--mono); font-size: 10px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); }
121
+ .num { text-align: right; font-variant-numeric: tabular-nums; }
122
+ .entries { flex: 1; overflow: auto; max-height: calc(100vh - 330px); min-height: 220px; }
123
+ .row { width: 100%; height: 40px; border: 0; border-bottom: 1px solid var(--line); background: transparent; text-align: left; font-family: var(--mono); font-size: 12.5px; transition: background .12s; }
124
+ .row:hover { background: var(--surface); }
125
+ .row.selected { background: var(--raise); box-shadow: inset 2px 0 0 var(--accent); }
126
+ .row.is-new { animation: flash 1.4s ease-out; }
127
+ .row .path { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); }
128
+ .row .num { color: var(--dim); font-size: 11.5px; }
129
+ .row .replay-mark { color: var(--accent-text); margin-left: 8px; font-size: 10px; }
130
+ .m { font-family: var(--mono); font-size: 11px; font-weight: 600; letter-spacing: .02em; }
131
+ .m-get { color: var(--m-get); } .m-post { color: var(--m-post); } .m-put { color: var(--m-put); } .m-patch { color: var(--m-patch); } .m-delete { color: var(--m-delete); } .m-other { color: var(--m-other); }
132
+
133
+ /* Detail */
134
+ .detail { padding: 24px var(--pad) 28px; overflow: auto; max-height: calc(100vh - 286px); }
135
+ .detail-path { margin: 0; font-family: var(--mono); font-size: clamp(17px, 1.7vw, 22px); font-weight: 500; letter-spacing: -.02em; overflow-wrap: anywhere; }
136
+ .detail-meta { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
137
+ .chip { height: 22px; display: inline-flex; align-items: center; padding: 0 8px; border: 1px solid var(--line-strong); border-radius: 5px; font-family: var(--mono); font-size: 11px; color: var(--dim); }
138
+ .chip-accent { color: var(--accent-text); border-color: var(--accent); }
139
+
140
+ /* Theme switch */
141
+ .theme { display: inline-flex; padding: 2px; border: 1px solid var(--line-strong); border-radius: 7px; background: var(--surface); }
142
+ .theme button { height: 24px; padding: 0 9px; border: 0; border-radius: 5px; background: transparent; font-family: var(--mono); font-size: 11px; color: var(--dim); }
143
+ .theme button:hover { color: var(--text); }
144
+ .theme button[aria-pressed="true"] { background: var(--raise); color: var(--text); box-shadow: inset 0 0 0 1px var(--line-strong); }
145
+
146
+ /* Explanations */
147
+ .stat-d { margin-top: 6px; font-size: 11.5px; color: var(--dim); }
148
+ .scope-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 14px; margin-bottom: 10px; }
149
+ .scope-title { font-weight: 600; font-size: 13px; }
150
+ .scope-help { font-size: 12px; color: var(--dim); }
151
+ .legend { display: flex; gap: 12px; margin-left: auto; }
152
+ .legend .m::before { content: ""; display: inline-block; width: 7px; height: 7px; margin-right: 5px; border-radius: 50%; background: currentColor; }
153
+ .command-label { font-family: var(--mono); font-size: 10.5px; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); white-space: nowrap; }
154
+ .pane-sub { margin-left: 8px; font-weight: 400; font-size: 12px; color: var(--faint); }
155
+ .detail-actions { display: flex; gap: 6px; margin-top: 18px; }
156
+ .tabs { display: flex; gap: 22px; margin-top: 26px; border-bottom: 1px solid var(--line); }
157
+ .tab { position: relative; height: 34px; padding: 0; border: 0; background: none; color: var(--dim); font-size: 13px; font-weight: 500; }
158
+ .tab .count { margin-left: 6px; font-family: var(--mono); font-size: 10.5px; color: var(--faint); }
159
+ .tab:hover { color: var(--text); }
160
+ .tab[aria-selected="true"] { color: var(--text); }
161
+ .tab[aria-selected="true"]::after { content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; background: var(--accent); }
162
+ .tab-panel { margin-top: 16px; }
163
+ .code { counter-reset: ln; margin: 0; padding: 14px 0; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); font-family: var(--mono); font-size: 12.5px; line-height: 1.7; overflow: auto; max-height: 420px; }
164
+ .code-line { counter-increment: ln; display: grid; grid-template-columns: 44px 1fr; white-space: pre-wrap; word-break: break-word; padding-right: 16px; }
165
+ .code-line::before { content: counter(ln); padding-right: 14px; text-align: right; color: var(--faint); user-select: none; }
166
+ .code-line:hover { background: var(--raise); }
167
+ .t-key { color: var(--t-key); } .t-str { color: var(--t-str); } .t-num { color: var(--t-num); } .t-lit { color: var(--t-lit); } .t-punc { color: var(--faint); }
168
+ .headers { border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
169
+ .header-row { display: grid; grid-template-columns: minmax(140px, 32%) 1fr; gap: 16px; padding: 9px 14px; border-bottom: 1px solid var(--line); font-family: var(--mono); font-size: 12px; }
170
+ .header-row:last-child { border-bottom: 0; }
171
+ .header-row .hk { color: var(--dim); }
172
+ .header-row .hv { overflow-wrap: anywhere; }
173
+ .header-row .hv.redacted { color: var(--danger); }
174
+ .note { margin-top: 12px; font-family: var(--mono); font-size: 11px; color: var(--faint); }
175
+
176
+ /* Empty states */
177
+ .empty { padding: 36px var(--pad); color: var(--faint); font-family: var(--mono); font-size: 12px; }
178
+ .waiting { padding: 8px 0; }
179
+ .waiting-title { margin: 0; font-size: clamp(26px, 3vw, 40px); font-weight: 500; letter-spacing: -.045em; line-height: 1.05; }
180
+ .waiting-title .cursor { display: inline-block; width: .5em; height: .9em; margin-left: 4px; vertical-align: -.08em; background: var(--accent); animation: blink 1s steps(1) infinite; }
181
+ .waiting-text { margin: 14px 0 20px; color: var(--dim); max-width: 460px; line-height: 1.6; }
182
+
183
+ /* Footer */
184
+ .foot { display: flex; justify-content: space-between; gap: 16px; padding: 10px var(--pad); border-top: 1px solid var(--line); font-family: var(--mono); font-size: 11px; color: var(--faint); }
185
+
186
+ /* Toast */
187
+ .toast { position: fixed; left: 50%; bottom: 22px; padding: 10px 14px; border: 1px solid var(--line-strong); border-radius: 8px; background: var(--raise); box-shadow: 0 12px 40px var(--shadow); font-family: var(--mono); font-size: 12px; opacity: 0; transform: translate(-50%, 12px); transition: opacity .2s, transform .3s cubic-bezier(.2,.8,.2,1); pointer-events: none; z-index: 10; }
188
+ .toast.show { opacity: 1; transform: translate(-50%, 0); }
189
+
190
+ @keyframes ping { 75%, 100% { transform: scale(2.2); opacity: 0; } }
191
+ @keyframes flash { from { background: rgba(198,255,61,.14); } }
192
+ @keyframes bump { 30% { color: var(--accent-text); } }
193
+ @keyframes blink { 50% { opacity: 0; } }
194
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
195
+
196
+ @media (max-width: 900px) {
197
+ /* Single column: let the page grow and scroll instead of squeezing panes into the window height. */
198
+ html, body { height: auto; }
199
+ .split { flex: none; }
200
+ .top-meta { display: none; }
201
+ .live { margin-left: auto; }
202
+ .legend { margin-left: 0; }
203
+ .command-label { display: none; }
204
+ .scope { grid-template-columns: 1fr; }
205
+ .stats { border-right: 0; border-bottom: 1px solid var(--line); }
206
+ .command { flex-wrap: wrap; }
207
+ .command-text { flex-basis: calc(100% - 30px); }
208
+ .split { grid-template-columns: 1fr; }
209
+ .pane-list { border-right: 0; border-bottom: 1px solid var(--line); }
210
+ .entries, .detail { max-height: none; }
211
+ .foot .keys { display: none; }
212
+ }
213
+ @media (max-width: 600px) {
214
+ .top { gap: 12px; }
215
+ .brand-tag, #live-label, .keys { display: none; }
216
+ .theme button { padding: 0 7px; }
217
+ .stats { grid-template-columns: 1fr 1fr; }
218
+ .stat { padding: 14px 16px 12px; }
219
+ .stat-d { font-size: 11px; }
220
+ .scope-help { flex-basis: 100%; }
221
+ .detail-meta .chip:nth-child(4) { display: none; }
222
+ }
package/src/ui.html ADDED
@@ -0,0 +1,66 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>HookDesk Mini</title>
3
+ <link rel="stylesheet" href="/ui.css">
4
+ <link rel="icon" href="/logo.svg" type="image/svg+xml">
5
+ </head><body>
6
+ <header class="top">
7
+ <div class="brand"><img class="brand-mark" src="/logo.svg" width="28" height="28" alt=""><span class="brand-name">hookdesk</span><span class="brand-tag">mini</span></div>
8
+ <div class="top-meta">
9
+ <span class="kv"><span class="k">host</span><span class="v" data-bind="host">127.0.0.1</span></span>
10
+ <span class="kv"><span class="k">buffer</span><span class="v"><span data-bind="limit">200</span> req</span></span>
11
+ <span class="kv"><span class="k">storage</span><span class="v">memory</span></span>
12
+ </div>
13
+ <div id="live" class="live" title="Whether the dashboard can reach the local server"><span class="live-dot" aria-hidden="true"></span><span id="live-label">Live</span></div>
14
+ <div class="theme" role="group" aria-label="Color theme">
15
+ <button data-theme-choice="auto" title="Follow the system setting">Auto</button>
16
+ <button data-theme-choice="light" title="Light theme">Light</button>
17
+ <button data-theme-choice="dark" title="Dark theme">Dark</button>
18
+ </div>
19
+ </header>
20
+
21
+ <section class="scope">
22
+ <div class="stats">
23
+ <div class="stat"><div class="stat-k">Captured</div><div id="count" class="stat-v">0</div><div class="stat-d">requests held in memory</div></div>
24
+ <div class="stat"><div class="stat-k">Last 60 s</div><div id="rate" class="stat-v">0</div><div class="stat-d">requests in the past minute</div></div>
25
+ <div class="stat"><div class="stat-k">Last hit</div><div id="last" class="stat-v">none</div><div class="stat-d">since the newest request</div></div>
26
+ <div class="stat"><div class="stat-k">In memory</div><div id="bytes" class="stat-v">0 B</div><div class="stat-d">total size of all bodies</div></div>
27
+ </div>
28
+ <div class="scope-chart">
29
+ <div class="scope-head">
30
+ <span class="scope-title">Activity, last <span data-bind="window">5m</span></span>
31
+ <span class="scope-help">Each spike is one request. Taller means a bigger body. Hover to preview, click to open.</span>
32
+ <span class="legend"><span class="m m-get">GET</span><span class="m m-post">POST</span><span class="m m-put">PUT/PATCH</span><span class="m m-delete">DELETE</span><span class="m m-other">other</span></span>
33
+ </div>
34
+ <canvas id="scope" role="img" aria-label="Request activity timeline"></canvas>
35
+ <div id="axis" class="scope-axis"></div>
36
+ </div>
37
+ </section>
38
+
39
+ <section class="command">
40
+ <span class="command-label">Send a test</span>
41
+ <span class="prompt" aria-hidden="true">$</span>
42
+ <code id="command" class="command-text" title="Run this in a terminal to send a test webhook"></code>
43
+ <div class="command-actions">
44
+ <button id="copy" class="btn" title="Copy the base URL to paste into your webhook provider or app">Copy endpoint</button>
45
+ <button id="copy-cmd" class="btn" title="Copy the test command on the left">Copy curl</button>
46
+ <button id="refresh" class="btn btn-ghost" title="Reload the request list now">Refresh</button>
47
+ <button id="clear" class="btn btn-ghost btn-danger" title="Delete all captured requests">Clear</button>
48
+ </div>
49
+ </section>
50
+
51
+ <main class="split">
52
+ <section class="pane pane-list">
53
+ <div class="pane-head"><span class="pane-title">Requests<span class="pane-sub">newest first</span></span><span class="keys"><kbd>j</kbd><kbd>k</kbd> navigate</span></div>
54
+ <div class="table-head"><span>Method</span><span>Path</span><span class="num">Size</span><span class="num">Age</span></div>
55
+ <div id="entries" class="entries"></div>
56
+ </section>
57
+ <section class="pane pane-detail"><div id="detail" class="detail"></div></section>
58
+ </main>
59
+
60
+ <footer class="foot">
61
+ <span>Local only. Bodies are shown as received and may contain secrets.</span>
62
+ <span class="keys"><kbd>r</kbd> replay <kbd>c</kbd> copy curl</span>
63
+ </footer>
64
+
65
+ <div id="toast" class="toast" role="status"></div>
66
+ <script src="/ui.js"></script></body></html>
package/src/ui.js ADDED
@@ -0,0 +1,323 @@
1
+ const $ = id => document.getElementById(id);
2
+ // Settings come from GET /api/config, which mirrors config/default.json plus any overrides.
3
+ const state = { config: null, events: [], selected: null, detail: null, listKey: '', online: true, seen: null, tab: 'body', flashes: new Map(), hover: null };
4
+ const node = (tag, text, cls) => { const el = document.createElement(tag); if (text !== undefined) el.textContent = text; if (cls) el.className = cls; return el; };
5
+ let toastTimer;
6
+ const showToast = message => { const el = $('toast'); el.textContent = message; el.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => el.classList.remove('show'), 2200); };
7
+ const quote = s => "'" + String(s).replaceAll("'", "'\\''") + "'";
8
+ const copyText = (text, message) => navigator.clipboard.writeText(text).then(() => showToast(message)).catch(() => showToast('Clipboard unavailable'));
9
+ async function getJson(path, options) {
10
+ const response = await fetch(path, { cache: 'no-store', ...options });
11
+ const data = await response.json().catch(() => ({}));
12
+ if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
13
+ return data;
14
+ }
15
+
16
+ const bytesParts = n => n < 1024 ? [String(n), n === 1 ? 'byte' : 'bytes'] : n < 1048576 ? [(n / 1024).toFixed(1), 'KB'] : [(n / 1048576).toFixed(1), 'MB'];
17
+ const fmtBytes = n => bytesParts(n).join(' ');
18
+ const exactBytes = n => `${n.toLocaleString()} bytes`;
19
+ const fmtAge = t => { const s = Math.max(0, Math.round((Date.now() - t) / 1000)); return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m` : `${Math.floor(s / 3600)}h`; };
20
+ const fmtSpan = ms => ms >= 3600000 ? `${+(ms / 3600000).toFixed(1)}h` : ms >= 60000 ? `${+(ms / 60000).toFixed(1)}m` : `${Math.round(ms / 1000)}s`;
21
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
22
+ const methodClass = m => `m m-${METHODS.includes(m) ? m.toLowerCase() : 'other'}`;
23
+
24
+ function setOnline(online) {
25
+ if (online === state.online) return;
26
+ state.online = online;
27
+ $('live-label').textContent = online ? 'Live' : 'Offline';
28
+ $('live').classList.toggle('offline', !online);
29
+ showToast(online ? 'Reconnected to local server' : 'Cannot reach local server');
30
+ }
31
+
32
+ // The number is shown large and the unit small, so values like "119 bytes" fit the stat box.
33
+ function setStat(id, value, unit = '', bump = true) {
34
+ const el = $(id); const text = `${value} ${unit}`;
35
+ if (el.dataset.v === text) return;
36
+ el.dataset.v = text;
37
+ el.replaceChildren(value);
38
+ if (unit) el.append(node('span', unit, 'unit'));
39
+ if (bump) { el.classList.remove('bump'); void el.offsetWidth; el.classList.add('bump'); }
40
+ }
41
+ function renderStats() {
42
+ const now = Date.now();
43
+ setStat('count', String(state.events.length));
44
+ setStat('rate', String(state.events.filter(e => now - e.t < 60000).length));
45
+ if (state.events.length) setStat('last', fmtAge(state.events[0].t), 'ago', false); else setStat('last', 'none', '', false);
46
+ const total = state.events.reduce((sum, e) => sum + e.bytes, 0);
47
+ setStat('bytes', ...bytesParts(total)); $('bytes').title = exactBytes(total);
48
+ }
49
+ const tickAges = () => { document.querySelectorAll('[data-t]').forEach(el => { el.textContent = fmtAge(Number(el.dataset.t)); }); renderStats(); };
50
+
51
+ const currentListKey = () => `${state.selected}|${state.events.map(x => x.id).join(',')}`;
52
+ function renderList() {
53
+ state.listKey = currentListKey();
54
+ const list = $('entries'); list.replaceChildren();
55
+ if (!state.events.length) list.append(node('div', 'No requests yet.', 'empty'));
56
+ // Only requests that arrived after the first render flash in the list and on the timeline.
57
+ const firstRender = state.seen === null; state.seen ??= new Set();
58
+ for (const event of state.events) {
59
+ const isNew = !firstRender && !state.seen.has(event.id);
60
+ if (isNew) state.flashes.set(event.id, performance.now());
61
+ state.seen.add(event.id);
62
+ const row = node('button', undefined, ['row', event.id === state.selected && 'selected', isNew && 'is-new'].filter(Boolean).join(' '));
63
+ const path = node('span', event.path, 'path');
64
+ if (event.replayOf) path.append(node('span', 'replay', 'replay-mark'));
65
+ const age = node('span', fmtAge(event.t), 'num'); age.dataset.t = String(event.t);
66
+ const size = node('span', fmtBytes(event.bytes), 'num'); size.title = exactBytes(event.bytes);
67
+ row.append(node('span', event.method, methodClass(event.method)), path, size, age);
68
+ row.addEventListener('click', () => select(event.id));
69
+ list.append(row);
70
+ if (event.id === state.selected) requestAnimationFrame(() => row.scrollIntoView({ block: 'nearest' }));
71
+ }
72
+ }
73
+
74
+ function curlCommand(event) {
75
+ const excluded = new Set(state.config.curlExcludedHeaders);
76
+ const headers = Object.entries(event.headers).filter(([k, v]) => !excluded.has(k.toLowerCase()) && v !== state.config.redactedPlaceholder);
77
+ return ['curl', '-X', quote(event.method), ...headers.flatMap(([k, v]) => ['-H', quote(`${k}: ${v}`)]), ...(event.body ? ['--data-raw', quote(event.body)] : []), quote(location.origin + event.path)].join(' ');
78
+ }
79
+
80
+ const TOKEN = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([{}[\],])/g;
81
+ function highlightJsonLine(line) {
82
+ const frag = document.createDocumentFragment(); let last = 0;
83
+ for (const m of line.matchAll(TOKEN)) {
84
+ if (m.index > last) frag.append(line.slice(last, m.index));
85
+ if (m[1]) { frag.append(node('span', m[1], m[2] ? 't-key' : 't-str')); if (m[2]) frag.append(node('span', m[2], 't-punc')); }
86
+ else if (m[3]) frag.append(node('span', m[3], 't-lit'));
87
+ else if (m[4]) frag.append(node('span', m[4], 't-num'));
88
+ else frag.append(node('span', m[5], 't-punc'));
89
+ last = m.index + m[0].length;
90
+ }
91
+ if (last < line.length) frag.append(line.slice(last));
92
+ return frag;
93
+ }
94
+ function codeBlock(text, highlight) {
95
+ const block = node('div', undefined, 'code');
96
+ for (const line of text.split('\n')) { const row = node('div', undefined, 'code-line'); const content = node('span'); content.append(highlight ? highlightJsonLine(line) : line); row.append(content); block.append(row); }
97
+ return block;
98
+ }
99
+
100
+ function waitingState() {
101
+ const box = node('div', undefined, 'waiting');
102
+ const title = node('h2', 'Waiting for the first request', 'waiting-title'); title.append(node('span', undefined, 'cursor'));
103
+ box.append(title, node('p', `Send any HTTP method to ${state.endpoint}/anything. It shows up here and on the timeline the moment it lands.`, 'waiting-text'));
104
+ box.append(codeBlock(state.demoCommand, false));
105
+ const actions = node('div', undefined, 'detail-actions');
106
+ const copy = node('button', 'Copy curl', 'btn btn-primary'); copy.addEventListener('click', () => copyText(state.demoCommand, 'curl copied'));
107
+ actions.append(copy); box.append(actions);
108
+ return box;
109
+ }
110
+
111
+ function renderDetail() {
112
+ const detail = $('detail'); detail.replaceChildren();
113
+ const event = state.detail;
114
+ if (!event) { detail.append(state.events.length ? node('div', 'Select a request.', 'empty') : waitingState()); return; }
115
+ const meta = node('div', undefined, 'detail-meta');
116
+ const chip = (text, cls = '') => node('span', text, `chip ${cls}`);
117
+ meta.append(chip(event.method, methodClass(event.method)), chip(new Date(event.timestamp).toLocaleString()), chip(fmtBytes(event.bytes)), chip(event.id.slice(0, 8)));
118
+ if (event.replayOf) meta.append(chip(`replay of ${event.replayOf.slice(0, 8)}`, 'chip-accent'));
119
+ const actions = node('div', undefined, 'detail-actions');
120
+ const replay = node('button', 'Replay locally', 'btn btn-primary'); replay.id = 'replay-btn';
121
+ replay.addEventListener('click', replaySelected);
122
+ const copy = node('button', 'Copy as curl', 'btn'); copy.addEventListener('click', () => copyText(curlCommand(event), 'curl copied. Check for secrets before sharing.'));
123
+ actions.append(replay, copy);
124
+
125
+ const headerCount = Object.keys(event.headers).length;
126
+ const tabs = node('div', undefined, 'tabs'); tabs.setAttribute('role', 'tablist');
127
+ for (const [id, label, count] of [['body', 'Body', fmtBytes(event.bytes)], ['headers', 'Headers', String(headerCount)], ['curl', 'cURL']]) {
128
+ const tab = node('button', label, 'tab'); tab.setAttribute('role', 'tab'); tab.setAttribute('aria-selected', String(state.tab === id));
129
+ if (count) tab.append(node('span', count, 'count'));
130
+ tab.addEventListener('click', () => { state.tab = id; renderDetail(); });
131
+ tabs.append(tab);
132
+ }
133
+ const panel = node('div', undefined, 'tab-panel');
134
+ if (state.tab === 'body') {
135
+ const contentType = String(event.headers['content-type'] || '');
136
+ let text = event.body; let json = false;
137
+ if (text) { try { text = JSON.stringify(JSON.parse(text), null, 2); json = true; } catch {} }
138
+ panel.append(text ? codeBlock(text, json) : node('div', 'Empty body.', 'note'), node('div', `${contentType || 'no content-type'}${json ? ' / formatted' : ''}`, 'note'));
139
+ } else if (state.tab === 'headers') {
140
+ const table = node('div', undefined, 'headers');
141
+ for (const [k, v] of Object.entries(event.headers)) { const row = node('div', undefined, 'header-row'); row.append(node('span', k, 'hk'), node('span', String(v), v === state.config.redactedPlaceholder ? 'hv redacted' : 'hv')); table.append(row); }
142
+ panel.append(table, node('div', 'Sensitive header values are redacted.', 'note'));
143
+ } else {
144
+ panel.append(codeBlock(curlCommand(event), false), node('div', 'Redacted headers are left out. The body may still contain secrets.', 'note'));
145
+ }
146
+ detail.append(node('h2', event.path, 'detail-path'), meta, actions, tabs, panel);
147
+ }
148
+
149
+ // Full headers and body are fetched only for the selected event; the list carries summaries.
150
+ async function loadDetail(id) {
151
+ if (!id) { state.detail = null; renderDetail(); return; }
152
+ try { const { event } = await getJson(`/api/events/${encodeURIComponent(id)}`); if (state.selected !== id) return; state.detail = event; }
153
+ catch (error) { if (state.selected !== id) return; state.detail = null; showToast(`Cannot load request: ${error.message}`); }
154
+ renderDetail();
155
+ }
156
+ function select(id) {
157
+ if (!id || id === state.selected) return;
158
+ state.selected = id;
159
+ renderList();
160
+ return loadDetail(id);
161
+ }
162
+ async function replaySelected() {
163
+ const event = state.detail; if (!event) return;
164
+ const button = $('replay-btn'); if (button) button.disabled = true;
165
+ try { const data = await getJson(`/api/events/${encodeURIComponent(event.id)}/replay`, { method: 'POST' }); showToast(`Replayed locally / HTTP ${data.responseStatus}`); await refresh(); }
166
+ catch (e) { showToast(`Replay failed: ${e.message}`); }
167
+ finally { const b = $('replay-btn'); if (b) b.disabled = false; }
168
+ }
169
+
170
+ // Re-renders only what changed so scroll position and text selection survive polling.
171
+ async function refresh() {
172
+ let data;
173
+ try { data = await getJson('/api/events'); } catch { setOnline(false); return; }
174
+ setOnline(true);
175
+ state.events = data.events.map(e => ({ ...e, t: Date.parse(e.timestamp) }));
176
+ let target = state.selected;
177
+ if (target && !state.events.some(x => x.id === target)) target = null;
178
+ if (!target && state.events.length) target = state.events[0].id;
179
+ const selectionChanged = target !== state.selected;
180
+ state.selected = target;
181
+ if (currentListKey() !== state.listKey) renderList();
182
+ renderStats();
183
+ if (selectionChanged) await loadDetail(target);
184
+ }
185
+ async function poll() { await refresh(); setTimeout(poll, state.config.pollIntervalMs); }
186
+
187
+ // Timeline: one spike per request, height by payload size (log scale), color by method.
188
+ const scope = { canvas: null, ctx: null, w: 0, h: 0, dpr: 1, colors: {}, lastDraw: 0 };
189
+ // The canvas cannot use CSS variables directly, so theme colors are re-read whenever the theme changes.
190
+ function readColors() {
191
+ const css = getComputedStyle(document.documentElement);
192
+ for (const name of ['line', 'line-strong', 'faint', 'dim', 'text', 'accent', 'raise', 'm-get', 'm-post', 'm-put', 'm-patch', 'm-delete', 'm-other']) scope.colors[name] = css.getPropertyValue(`--${name}`).trim();
193
+ scope.lastDraw = 0;
194
+ }
195
+ function setupScope() {
196
+ scope.canvas = $('scope'); scope.ctx = scope.canvas.getContext('2d');
197
+ readColors();
198
+ const resize = () => { const r = scope.canvas.getBoundingClientRect(); scope.dpr = window.devicePixelRatio || 1; scope.w = r.width; scope.h = r.height; scope.canvas.width = Math.round(r.width * scope.dpr); scope.canvas.height = Math.round(r.height * scope.dpr); scope.lastDraw = 0; };
199
+ new ResizeObserver(resize).observe(scope.canvas); resize();
200
+ const axis = $('axis'); const step = state.config.timelineWindowMs / 5;
201
+ for (let i = 5; i >= 0; i--) axis.append(node('span', i ? `-${fmtSpan(step * i)}` : 'now'));
202
+ scope.canvas.addEventListener('mousemove', e => {
203
+ const x = e.clientX - scope.canvas.getBoundingClientRect().left;
204
+ let best = null, bestDist = 8;
205
+ for (const ev of state.events) { const d = Math.abs(spikeX(ev.t) - x); if (d < bestDist) { best = ev; bestDist = d; } }
206
+ state.hover = best; scope.canvas.style.cursor = best ? 'pointer' : 'crosshair'; scope.lastDraw = 0;
207
+ });
208
+ scope.canvas.addEventListener('mouseleave', () => { state.hover = null; scope.lastDraw = 0; });
209
+ scope.canvas.addEventListener('click', () => { if (state.hover) select(state.hover.id); });
210
+ requestAnimationFrame(drawScope);
211
+ }
212
+ const spikeX = t => (t - (Date.now() - state.config.timelineWindowMs)) / state.config.timelineWindowMs * scope.w;
213
+ function drawScope(now) {
214
+ requestAnimationFrame(drawScope);
215
+ const animating = [...state.flashes.values()].some(start => now - start < 1400);
216
+ if (!animating && now - scope.lastDraw < 250) return;
217
+ scope.lastDraw = now;
218
+ for (const [id, start] of state.flashes) if (now - start > 1400) state.flashes.delete(id);
219
+ const { ctx, w, h, dpr, colors } = scope;
220
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h);
221
+ const base = h - 0.5;
222
+ ctx.lineWidth = 1;
223
+ ctx.strokeStyle = colors.line;
224
+ for (let i = 0; i <= 5; i++) { const x = Math.round(i * (w - 1) / 5) + 0.5; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
225
+ ctx.setLineDash([2, 4]);
226
+ for (const y of [h * 0.33, h * 0.66]) { ctx.beginPath(); ctx.moveTo(0, Math.round(y) + 0.5); ctx.lineTo(w, Math.round(y) + 0.5); ctx.stroke(); }
227
+ ctx.setLineDash([]);
228
+ ctx.strokeStyle = colors['line-strong']; ctx.beginPath(); ctx.moveTo(0, base); ctx.lineTo(w, base); ctx.stroke();
229
+
230
+ const maxLog = Math.log2(state.config.maxBodyBytes + 1);
231
+ const emphasized = new Set([state.selected, state.hover?.id]);
232
+ for (const ev of [...state.events].reverse()) {
233
+ const x = spikeX(ev.t); if (x < -4 || x > w + 4) continue;
234
+ const height = 8 + (h - 22) * Math.min(1, Math.log2(ev.bytes + 1) / maxLog);
235
+ const color = colors[`m-${METHODS.includes(ev.method) ? ev.method.toLowerCase() : 'other'}`];
236
+ const strong = emphasized.has(ev.id);
237
+ ctx.globalAlpha = strong ? 1 : 0.7; ctx.fillStyle = color;
238
+ ctx.fillRect(Math.round(x) - (strong ? 1 : 0.5), base - height, strong ? 2 : 1, height);
239
+ ctx.beginPath(); ctx.arc(x, base - height, strong ? 3.5 : 2.5, 0, Math.PI * 2); ctx.fill();
240
+ const start = state.flashes.get(ev.id);
241
+ if (start !== undefined) {
242
+ const p = (now - start) / 1400;
243
+ ctx.globalAlpha = Math.max(0, 1 - p); ctx.strokeStyle = color; ctx.lineWidth = 1.5;
244
+ ctx.beginPath(); ctx.arc(x, base - height, 3 + p * 18, 0, Math.PI * 2); ctx.stroke(); ctx.lineWidth = 1;
245
+ }
246
+ }
247
+ ctx.globalAlpha = 1;
248
+ const sel = state.events.find(e => e.id === state.selected);
249
+ if (sel) { const x = Math.round(spikeX(sel.t)) + 0.5; ctx.strokeStyle = colors.accent; ctx.globalAlpha = 0.35; ctx.setLineDash([3, 3]); ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; }
250
+ if (state.hover) {
251
+ const label = `${state.hover.method} ${state.hover.path} ${fmtBytes(state.hover.bytes)} ${fmtAge(state.hover.t)} ago`;
252
+ ctx.font = '11px "JetBrains Mono", "SF Mono", ui-monospace, Menlo, monospace';
253
+ const tw = Math.min(ctx.measureText(label).width + 16, w);
254
+ const lx = Math.min(Math.max(spikeX(state.hover.t) - tw / 2, 0), w - tw);
255
+ ctx.fillStyle = colors.raise; ctx.strokeStyle = colors['line-strong'];
256
+ ctx.fillRect(lx, 2, tw, 22); ctx.strokeRect(lx + 0.5, 2.5, tw - 1, 21);
257
+ ctx.fillStyle = colors.text; ctx.fillText(label, lx + 8, 17, tw - 16);
258
+ }
259
+ }
260
+
261
+ function moveSelection(step) {
262
+ if (!state.events.length) return;
263
+ const index = state.events.findIndex(e => e.id === state.selected);
264
+ const next = state.events[Math.min(state.events.length - 1, Math.max(0, (index === -1 ? 0 : index + step)))];
265
+ select(next.id);
266
+ }
267
+ function onKey(e) {
268
+ if (e.metaKey || e.ctrlKey || e.altKey || /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;
269
+ if (e.key === 'j' || e.key === 'ArrowDown') { e.preventDefault(); moveSelection(1); }
270
+ else if (e.key === 'k' || e.key === 'ArrowUp') { e.preventDefault(); moveSelection(-1); }
271
+ else if (e.key === 'r') replaySelected();
272
+ else if (e.key === 'c' && state.detail) copyText(curlCommand(state.detail), 'curl copied. Check for secrets before sharing.');
273
+ }
274
+
275
+ // Theme: "auto" follows the OS. The viewer's choice is remembered in this browser only.
276
+ const THEMES = ['auto', 'light', 'dark'];
277
+ const THEME_KEY = 'hookdesk-theme';
278
+ function applyTheme(choice, remember) {
279
+ if (!THEMES.includes(choice)) choice = 'auto';
280
+ if (choice === 'auto') delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = choice;
281
+ document.querySelectorAll('[data-theme-choice]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.themeChoice === choice)));
282
+ if (remember) { try { localStorage.setItem(THEME_KEY, choice); } catch {} }
283
+ readColors();
284
+ }
285
+ function setupTheme() {
286
+ let stored = null;
287
+ try { stored = localStorage.getItem(THEME_KEY); } catch {}
288
+ applyTheme(stored ?? state.config.defaultTheme, false);
289
+ document.querySelectorAll('[data-theme-choice]').forEach(b => b.addEventListener('click', () => applyTheme(b.dataset.themeChoice, true)));
290
+ matchMedia('(prefers-color-scheme: light)').addEventListener('change', readColors);
291
+ }
292
+
293
+ function renderCommand() {
294
+ const el = $('command'); el.replaceChildren();
295
+ el.append('curl -X POST ', node('span', `${state.endpoint}/demo`, 'url'), ` -H 'Content-Type: application/json' -d '{"hello":"world"}'`);
296
+ }
297
+
298
+ async function init() {
299
+ try { state.config = await getJson('/api/config'); }
300
+ catch { setOnline(false); setTimeout(init, 3000); return; }
301
+ setOnline(true);
302
+ state.endpoint = `${location.origin}${state.config.captureBase}`;
303
+ state.demoCommand = `curl -X POST ${state.endpoint}/demo -H 'Content-Type: application/json' -d '{"hello":"world"}'`;
304
+ document.querySelectorAll('[data-bind="host"]').forEach(el => { el.textContent = state.config.host; });
305
+ document.querySelectorAll('[data-bind="limit"]').forEach(el => { el.textContent = String(state.config.maxEvents); });
306
+ document.querySelectorAll('[data-bind="window"]').forEach(el => { el.textContent = fmtSpan(state.config.timelineWindowMs); });
307
+ renderCommand();
308
+ $('copy').addEventListener('click', () => copyText(state.endpoint, 'Endpoint copied'));
309
+ $('copy-cmd').addEventListener('click', () => copyText(state.demoCommand, 'curl copied'));
310
+ $('refresh').addEventListener('click', refresh);
311
+ $('clear').addEventListener('click', async () => {
312
+ if (!confirm('Clear all captured requests?')) return;
313
+ try { await getJson('/api/events', { method: 'DELETE' }); } catch (e) { showToast(`Clear failed: ${e.message}`); return; }
314
+ state.selected = null; state.detail = null; await refresh(); renderDetail();
315
+ });
316
+ document.addEventListener('keydown', onKey);
317
+ setupScope();
318
+ setupTheme();
319
+ // The list renders on the first poll, so requests already in memory at page load don't flash as new.
320
+ renderDetail(); poll();
321
+ setInterval(tickAges, 1000);
322
+ }
323
+ init();
@@ -0,0 +1,13 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="290" height="64" viewBox="0 0 290 64" fill="none">
2
+ <title>Hookdesk Mini</title>
3
+ <rect width="290" height="64" rx="14" fill="#09090a"/>
4
+ <g transform="translate(12 12)">
5
+ <rect width="40" height="40" rx="11" fill="#c6ff3d"/>
6
+ <path d="M13 13v10a8 8 0 0 0 16 0v-3" stroke="#0b0e02" stroke-width="3.5" stroke-linecap="round"/>
7
+ <path d="m30.75 14-7 8 5.25-1 1.75 3Z" fill="#0b0e02"/>
8
+ <circle cx="13" cy="10" r="3" stroke="#0b0e02" stroke-width="2.5"/>
9
+ </g>
10
+ <text x="65" y="41" fill="#ededef" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" font-size="28" font-weight="650" letter-spacing="-1">hookdesk</text>
11
+ <rect x="234" y="23" width="43" height="20" rx="5" stroke="#3e3e45"/>
12
+ <text x="255.5" y="37" text-anchor="middle" fill="#a1a1aa" font-family="ui-monospace, monospace" font-size="11">mini</text>
13
+ </svg>