@joinremba/catalog 0.2.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 +21 -0
- package/README.md +298 -0
- package/package.json +89 -0
- package/src/adapters/hono.test.ts +62 -0
- package/src/adapters/hono.ts +74 -0
- package/src/audit.test.ts +17 -0
- package/src/audit.ts +27 -0
- package/src/index.test.ts +87 -0
- package/src/index.ts +180 -0
- package/src/security.ts +25 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Remba
|
|
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
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# @joinremba/catalog
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@joinremba/catalog)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://github.com/joinremba/catalog/actions/workflows/ci.yml)
|
|
6
|
+
[](https://bun.sh)
|
|
7
|
+
|
|
8
|
+
Catalog is a production-ready logging and error event layer for TypeScript backends, built on [Pino](https://getpino.io/).
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- **Event-name-first API** — Log with descriptive event names: `catalog.info("wallet.created", { userId })`. Events are indexed, searchable, and consistent across your codebase.
|
|
13
|
+
- **Pino-based** — Ultra-fast structured JSON logging with full Pino ecosystem support.
|
|
14
|
+
- **Sensitive data redaction** — Automatically redacts PII, secrets, and credentials from log output via configurable path patterns.
|
|
15
|
+
- **Multi-transport** — Route logs to console, file, rolling files, or external services based on environment.
|
|
16
|
+
- **Request context** — Correlate logs with request IDs via child loggers.
|
|
17
|
+
- **Error serializer** — Standardised error serialization for consistent error objects in logs.
|
|
18
|
+
- **HTTP request logging** — Middleware for automatic request/response logging.
|
|
19
|
+
- **Environment-aware** — Pretty printing in development, structured JSON and file rolling in production.
|
|
20
|
+
- **Framework adapters** — Plug into Express, Hono, Fastify, or any Bun-native server.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
bun add @joinremba/catalog
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { createCatalog } from "@joinremba/catalog";
|
|
32
|
+
|
|
33
|
+
const catalog = createCatalog({
|
|
34
|
+
service: "@joinremba/api",
|
|
35
|
+
environment: process.env.NODE_ENV,
|
|
36
|
+
redact: ["authorization", "password", "bvn", "nin"],
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
catalog.info("wallet.created", { userId, walletId });
|
|
40
|
+
catalog.error("payment.failed", { amount: 100, error: err.message });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## API Reference
|
|
44
|
+
|
|
45
|
+
### `createCatalog(options)`
|
|
46
|
+
|
|
47
|
+
Creates and returns a configured Catalog instance. It is the main entry point for the package.
|
|
48
|
+
|
|
49
|
+
#### Options
|
|
50
|
+
|
|
51
|
+
| Option | Type | Default | Description |
|
|
52
|
+
| ------------- | ---------------------------------------- | --------------------- | ------------------------------------------------------ |
|
|
53
|
+
| `service` | `string` | — | Application or service name, included in every log. |
|
|
54
|
+
| `environment` | `string` | — | Environment name (e.g. `"production"`, `"staging"`). |
|
|
55
|
+
| `level` | `LogLevel` | `"info"` | Minimum log level. |
|
|
56
|
+
| `redact` | `string[]` | — | Paths to redact (e.g. `["password", "creditCard.*"]`). |
|
|
57
|
+
| `transport` | `TransportOptions \| TransportOptions[]` | Pino default (stdout) | Single or array of transport configurations. |
|
|
58
|
+
|
|
59
|
+
#### Log Levels
|
|
60
|
+
|
|
61
|
+
| Method | Use |
|
|
62
|
+
| -------------------- | --------------------- |
|
|
63
|
+
| `catalog.trace(...)` | Trace-level logging |
|
|
64
|
+
| `catalog.debug(...)` | Debug-level logging |
|
|
65
|
+
| `catalog.info(...)` | Informational logging |
|
|
66
|
+
| `catalog.warn(...)` | Warning logging |
|
|
67
|
+
| `catalog.error(...)` | Error logging |
|
|
68
|
+
| `catalog.fatal(...)` | Fatal logging |
|
|
69
|
+
|
|
70
|
+
Each method accepts an event name (string) and an optional data object:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
catalog.info("user.signed-in", { userId: 42 });
|
|
74
|
+
catalog.error("db.connection-failed", { err });
|
|
75
|
+
catalog.info("app.started"); // event name only
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Child Loggers
|
|
79
|
+
|
|
80
|
+
Create a child logger that inherits the parent's configuration and adds bound fields:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const catalog = createCatalog({ service: "app" });
|
|
84
|
+
const reqLog = catalog.child({ requestId: "abc-123" });
|
|
85
|
+
|
|
86
|
+
reqLog.info("request.handled", { path: "/api/users" });
|
|
87
|
+
// Includes requestId: "abc-123" in every log
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Redaction
|
|
91
|
+
|
|
92
|
+
Sensitive data is automatically redacted from log output. Configure paths using dot notation:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const catalog = createCatalog({
|
|
96
|
+
service: "secure-app",
|
|
97
|
+
redact: ["password", "creditCard.number", "ssn", "authorization"],
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
catalog.info("user.login", { userId: 42, password: "secret" });
|
|
101
|
+
// password is redacted as [REDACTED]
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Multi-transport
|
|
105
|
+
|
|
106
|
+
Route logs to multiple destinations:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
const catalog = createCatalog({
|
|
110
|
+
service: "my-app",
|
|
111
|
+
transport: [
|
|
112
|
+
{ target: "pino/file", options: {} }, // stdout
|
|
113
|
+
{ target: "pino/file", options: { destination: "./logs/app.log" } }, // file
|
|
114
|
+
{ target: "pino-roll", options: { file: "./logs/out.log", frequency: "daily" } }, // rolling
|
|
115
|
+
],
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Error Serializer
|
|
120
|
+
|
|
121
|
+
Catalog includes a built-in error serializer that converts `Error` instances into structured objects:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
try {
|
|
125
|
+
await riskyOperation();
|
|
126
|
+
} catch (err) {
|
|
127
|
+
catalog.error("operation.failed", { error: err });
|
|
128
|
+
// error is serialised: { message, name, stack, cause }
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Safe Error Response Helper
|
|
133
|
+
|
|
134
|
+
For API backends, Catalog provides helpers to build safe error responses without leaking internals:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { safeError } from "@joinremba/catalog";
|
|
138
|
+
|
|
139
|
+
app.onError((err, c) => {
|
|
140
|
+
catalog.error("request.error", { error: err });
|
|
141
|
+
return c.json(safeError(err), 500);
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Middleware
|
|
146
|
+
|
|
147
|
+
### Request ID Middleware
|
|
148
|
+
|
|
149
|
+
Automatically generates or extracts a request ID and binds it to all logs within a request:
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import { requestId } from "@joinremba/catalog";
|
|
153
|
+
import { createCatalog } from "@joinremba/catalog";
|
|
154
|
+
|
|
155
|
+
const catalog = createCatalog({ service: "my-api" });
|
|
156
|
+
|
|
157
|
+
// Express
|
|
158
|
+
app.use(requestId({ header: "X-Request-Id" }));
|
|
159
|
+
app.use((req, res, next) => {
|
|
160
|
+
const log = catalog.child({ requestId: req.headers["x-request-id"] });
|
|
161
|
+
req.log = log;
|
|
162
|
+
next();
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### HTTP Request Logger
|
|
167
|
+
|
|
168
|
+
Automatically log incoming requests and responses:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { httpLogger } from "@joinremba/catalog";
|
|
172
|
+
|
|
173
|
+
// Express
|
|
174
|
+
app.use(httpLogger({ catalog, excludePaths: ["/health"] }));
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Framework Adapters
|
|
178
|
+
|
|
179
|
+
Catalog is framework-agnostic but ships with adapters for popular frameworks:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
// Express
|
|
183
|
+
import { expressAdapter } from "@joinremba/catalog/adapters/express";
|
|
184
|
+
|
|
185
|
+
// Hono
|
|
186
|
+
import { honoAdapter } from "@joinremba/catalog/adapters/hono";
|
|
187
|
+
|
|
188
|
+
// Fastify
|
|
189
|
+
import { fastifyAdapter } from "@joinremba/catalog/adapters/fastify";
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Adapters automatically configure request ID tracking, error serialization, and HTTP logging for the target framework.
|
|
193
|
+
|
|
194
|
+
## TypeScript Types
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import type { Catalog, LogLevel, CatalogOptions, TransportOptions } from "@joinremba/catalog";
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
| Type | Description |
|
|
201
|
+
| ------------------ | ---------------------------------------------------------------------- |
|
|
202
|
+
| `Catalog` | The logger instance type. |
|
|
203
|
+
| `LogLevel` | Union: `"trace" \| "debug" \| "info" \| "warn" \| "error" \| "fatal"`. |
|
|
204
|
+
| `CatalogOptions` | Options object passed to `createCatalog`. |
|
|
205
|
+
| `TransportOptions` | Transport configuration with `target` and `options`. |
|
|
206
|
+
|
|
207
|
+
## Examples
|
|
208
|
+
|
|
209
|
+
### Basic usage
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
import { createCatalog } from "@joinremba/catalog";
|
|
213
|
+
|
|
214
|
+
const catalog = createCatalog({ service: "my-service" });
|
|
215
|
+
|
|
216
|
+
catalog.info("service.starting");
|
|
217
|
+
catalog.debug("config.loaded", { port: 3000 });
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### With request context
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import { createCatalog } from "@joinremba/catalog";
|
|
224
|
+
|
|
225
|
+
const catalog = createCatalog({ service: "web-app" });
|
|
226
|
+
|
|
227
|
+
Bun.serve({
|
|
228
|
+
port: 3000,
|
|
229
|
+
fetch(req) {
|
|
230
|
+
const log = catalog.child({ requestId: crypto.randomUUID() });
|
|
231
|
+
log.info("request.incoming", { url: req.url });
|
|
232
|
+
return new Response("OK");
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### Environment-aware config
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
const catalog = createCatalog({
|
|
241
|
+
service: "my-app",
|
|
242
|
+
environment: process.env.NODE_ENV,
|
|
243
|
+
level: process.env.NODE_ENV === "production" ? "info" : "debug",
|
|
244
|
+
transport:
|
|
245
|
+
process.env.NODE_ENV === "production"
|
|
246
|
+
? [
|
|
247
|
+
{ target: "pino/file", options: { destination: "./logs/app.log" } },
|
|
248
|
+
{ target: "pino-roll", options: { file: "./logs/out.log", frequency: "daily" } },
|
|
249
|
+
]
|
|
250
|
+
: undefined, // pretty-print to console in dev
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Roadmap
|
|
255
|
+
|
|
256
|
+
**MVP** (current)
|
|
257
|
+
|
|
258
|
+
- Pino wrapper with event-name-first API
|
|
259
|
+
- Sensitive data redaction with configurable paths
|
|
260
|
+
- Child loggers with bound context
|
|
261
|
+
- Multi-transport support
|
|
262
|
+
- Error serializer
|
|
263
|
+
- Safe error response helper
|
|
264
|
+
|
|
265
|
+
**V1**
|
|
266
|
+
|
|
267
|
+
- Request ID middleware
|
|
268
|
+
- HTTP request logging middleware
|
|
269
|
+
- Express, Hono, Fastify adapters
|
|
270
|
+
- Audit event module (`catalog.audit()`)
|
|
271
|
+
- Security event module (`catalog.security()`)
|
|
272
|
+
- Webhook event module
|
|
273
|
+
- Payment-safe log redaction defaults
|
|
274
|
+
- Local pretty log viewer
|
|
275
|
+
- OpenTelemetry bridge
|
|
276
|
+
- Log sampling
|
|
277
|
+
|
|
278
|
+
**V2**
|
|
279
|
+
|
|
280
|
+
- Hosted log ingestion
|
|
281
|
+
- Dashboards and alerts
|
|
282
|
+
- Retention policies
|
|
283
|
+
- Compliance exports
|
|
284
|
+
- Audit-log immutability
|
|
285
|
+
- Team access controls
|
|
286
|
+
|
|
287
|
+
## Related Packages
|
|
288
|
+
|
|
289
|
+
- [@joinremba/beacon](https://github.com/joinremba/beacon) — Environment validation, config, secrets, and feature gates.
|
|
290
|
+
- [@joinremba/gate](https://github.com/joinremba/gate) — API safety layer: validation, responses, idempotency, rate limiting, and API keys.
|
|
291
|
+
|
|
292
|
+
## Contributing
|
|
293
|
+
|
|
294
|
+
Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute to this project.
|
|
295
|
+
|
|
296
|
+
## License
|
|
297
|
+
|
|
298
|
+
MIT — see [LICENSE](LICENSE).
|
package/package.json
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@joinremba/catalog",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Production-ready logging and error event layer for TypeScript backends, built on Pino.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"types": "./src/index.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.ts",
|
|
11
|
+
"import": "./src/index.ts",
|
|
12
|
+
"default": "./src/index.ts"
|
|
13
|
+
},
|
|
14
|
+
"./audit": {
|
|
15
|
+
"types": "./src/audit.ts",
|
|
16
|
+
"import": "./src/audit.ts",
|
|
17
|
+
"default": "./src/audit.ts"
|
|
18
|
+
},
|
|
19
|
+
"./security": {
|
|
20
|
+
"types": "./src/security.ts",
|
|
21
|
+
"import": "./src/security.ts",
|
|
22
|
+
"default": "./src/security.ts"
|
|
23
|
+
},
|
|
24
|
+
"./adapters/hono": {
|
|
25
|
+
"types": "./src/adapters/hono.ts",
|
|
26
|
+
"import": "./src/adapters/hono.ts",
|
|
27
|
+
"default": "./src/adapters/hono.ts"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"src",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "bun build ./src/index.ts --outdir ./dist --target bun --format esm",
|
|
37
|
+
"dev": "bun --watch ./src/index.ts",
|
|
38
|
+
"format": "prettier --write .",
|
|
39
|
+
"format:check": "prettier --check .",
|
|
40
|
+
"lint": "eslint .",
|
|
41
|
+
"lint:fix": "eslint . --fix",
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"test": "bun test",
|
|
44
|
+
"test:watch": "bun test --watch",
|
|
45
|
+
"prepublishOnly": "bun run build",
|
|
46
|
+
"check": "bun lint && bun format:check && bun typecheck && bun test"
|
|
47
|
+
},
|
|
48
|
+
"author": {
|
|
49
|
+
"name": "Benson Isaac",
|
|
50
|
+
"email": "bensxnisaac@gmail.com"
|
|
51
|
+
},
|
|
52
|
+
"license": "MIT",
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "git+https://github.com/joinremba/catalog.git"
|
|
56
|
+
},
|
|
57
|
+
"bugs": {
|
|
58
|
+
"url": "https://github.com/joinremba/catalog/issues"
|
|
59
|
+
},
|
|
60
|
+
"homepage": "https://github.com/joinremba/catalog#readme",
|
|
61
|
+
"keywords": [
|
|
62
|
+
"logging",
|
|
63
|
+
"pino",
|
|
64
|
+
"logger",
|
|
65
|
+
"structured-logging",
|
|
66
|
+
"error-tracking",
|
|
67
|
+
"typescript"
|
|
68
|
+
],
|
|
69
|
+
"publishConfig": {
|
|
70
|
+
"access": "public"
|
|
71
|
+
},
|
|
72
|
+
"engines": {
|
|
73
|
+
"bun": ">=1.3.1"
|
|
74
|
+
},
|
|
75
|
+
"dependencies": {
|
|
76
|
+
"pino": "^10.3.1",
|
|
77
|
+
"pino-roll": "^4.0.0"
|
|
78
|
+
},
|
|
79
|
+
"devDependencies": {
|
|
80
|
+
"@types/bun": "latest",
|
|
81
|
+
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
|
82
|
+
"@typescript-eslint/parser": "^7.18.0",
|
|
83
|
+
"eslint": "^8.57.1",
|
|
84
|
+
"eslint-config-prettier": "^10.1.8",
|
|
85
|
+
"pino-pretty": "^13.1.3",
|
|
86
|
+
"prettier": "^3.8.3",
|
|
87
|
+
"typescript": "^6.0.3"
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { createCatalog } from "../index";
|
|
3
|
+
import { requestIdMiddleware, httpLoggerMiddleware } from "./hono";
|
|
4
|
+
|
|
5
|
+
interface MockCtx {
|
|
6
|
+
req: {
|
|
7
|
+
method: string;
|
|
8
|
+
path: string;
|
|
9
|
+
header(name: string): string | undefined;
|
|
10
|
+
query(): Record<string, string | undefined>;
|
|
11
|
+
};
|
|
12
|
+
get(key: string): unknown;
|
|
13
|
+
set(key: string, val: unknown): void;
|
|
14
|
+
res?: { status: number };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function mockHonoContext(overrides?: {
|
|
18
|
+
path?: string;
|
|
19
|
+
header?: (name: string) => string | undefined;
|
|
20
|
+
}): MockCtx {
|
|
21
|
+
const store: Record<string, unknown> = {};
|
|
22
|
+
return {
|
|
23
|
+
req: {
|
|
24
|
+
method: "GET",
|
|
25
|
+
path: overrides?.path ?? "/api/users",
|
|
26
|
+
header: overrides?.header ?? ((_name: string) => undefined),
|
|
27
|
+
query: () => ({}),
|
|
28
|
+
},
|
|
29
|
+
get: (key: string) => store[key],
|
|
30
|
+
set: (key: string, val: unknown) => {
|
|
31
|
+
store[key] = val;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
test("requestIdMiddleware sets requestId on context", async () => {
|
|
37
|
+
const catalog = createCatalog({ service: "test" });
|
|
38
|
+
const c = mockHonoContext();
|
|
39
|
+
let called = false;
|
|
40
|
+
await requestIdMiddleware(catalog)(c, async () => {
|
|
41
|
+
called = true;
|
|
42
|
+
});
|
|
43
|
+
expect(c.get("requestId")).toBeDefined();
|
|
44
|
+
expect(called).toBe(true);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("requestIdMiddleware preserves existing x-request-id header", async () => {
|
|
48
|
+
const catalog = createCatalog({ service: "test" });
|
|
49
|
+
const c = mockHonoContext({ header: () => "from-header" });
|
|
50
|
+
await requestIdMiddleware(catalog)(c, async () => {});
|
|
51
|
+
expect(c.get("requestId")).toBe("from-header");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("httpLoggerMiddleware skips excluded paths", async () => {
|
|
55
|
+
const catalog = createCatalog({ service: "test" });
|
|
56
|
+
const c = mockHonoContext({ path: "/health" });
|
|
57
|
+
let called = false;
|
|
58
|
+
await httpLoggerMiddleware(catalog)(c, async () => {
|
|
59
|
+
called = true;
|
|
60
|
+
});
|
|
61
|
+
expect(called).toBe(true);
|
|
62
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Catalog } from "../index";
|
|
2
|
+
|
|
3
|
+
interface HonoContext {
|
|
4
|
+
req: {
|
|
5
|
+
method: string;
|
|
6
|
+
path: string;
|
|
7
|
+
header(name: string): string | undefined;
|
|
8
|
+
query(): Record<string, string | undefined>;
|
|
9
|
+
};
|
|
10
|
+
get(key: string): unknown;
|
|
11
|
+
set(key: string, val: unknown): void;
|
|
12
|
+
res?: { status: number };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface HonoRequestIdOptions {
|
|
16
|
+
header?: string;
|
|
17
|
+
generate?: () => string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function requestIdMiddleware(catalog: Catalog, options?: HonoRequestIdOptions) {
|
|
21
|
+
const headerName = options?.header?.toLowerCase() ?? "x-request-id";
|
|
22
|
+
const generate = options?.generate ?? (() => crypto.randomUUID());
|
|
23
|
+
|
|
24
|
+
return (c: HonoContext, next: () => Promise<void>) => {
|
|
25
|
+
const existing = c.req.header(headerName) ?? c.req.header("x-request-id");
|
|
26
|
+
const requestId = existing ?? generate();
|
|
27
|
+
c.set("requestId", requestId);
|
|
28
|
+
return next();
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface HttpLogOptions {
|
|
33
|
+
excludePaths?: string[];
|
|
34
|
+
logBody?: boolean;
|
|
35
|
+
maxBodyLength?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function httpLoggerMiddleware(catalog: Catalog, options?: HttpLogOptions) {
|
|
39
|
+
const exclude = new Set(options?.excludePaths ?? ["/health", "/favicon.ico"]);
|
|
40
|
+
|
|
41
|
+
return (c: HonoContext, next: () => Promise<void>) => {
|
|
42
|
+
if (exclude.has(c.req.path)) return next();
|
|
43
|
+
|
|
44
|
+
const requestId = c.get("requestId") as string | undefined;
|
|
45
|
+
const log = requestId ? catalog.child({ requestId }) : catalog;
|
|
46
|
+
const start = performance.now();
|
|
47
|
+
const method = c.req.method;
|
|
48
|
+
const path = c.req.path;
|
|
49
|
+
|
|
50
|
+
log.info({
|
|
51
|
+
message: `--> ${method} ${path}`,
|
|
52
|
+
method,
|
|
53
|
+
path,
|
|
54
|
+
query: Object.fromEntries(Object.entries(c.req.query()).filter(([, v]) => v !== undefined)),
|
|
55
|
+
userAgent: c.req.header("user-agent"),
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
return next().then(() => {
|
|
59
|
+
const duration = ((performance.now() - start) * 1000).toFixed(2);
|
|
60
|
+
const status = c.res?.status ?? 200;
|
|
61
|
+
const level = status >= 500 ? "error" : status >= 400 ? "warn" : "info";
|
|
62
|
+
|
|
63
|
+
const logData = {
|
|
64
|
+
message: `<-- ${method} ${path} ${status} ${duration}ms`,
|
|
65
|
+
status,
|
|
66
|
+
durationMs: duration,
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
if (level === "info") log.info(logData);
|
|
70
|
+
else if (level === "warn") log.warn(logData);
|
|
71
|
+
else log.error(logData);
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { createCatalog } from "./index";
|
|
3
|
+
import { auditLogger } from "./audit";
|
|
4
|
+
|
|
5
|
+
test("auditLogger logs audit event", () => {
|
|
6
|
+
const catalog = createCatalog({ service: "test" });
|
|
7
|
+
const audit = auditLogger(catalog);
|
|
8
|
+
expect(() =>
|
|
9
|
+
audit.log({
|
|
10
|
+
action: "user.deleted",
|
|
11
|
+
actor: "admin@example.com",
|
|
12
|
+
resource: "user",
|
|
13
|
+
resourceId: "42",
|
|
14
|
+
outcome: "success",
|
|
15
|
+
})
|
|
16
|
+
).not.toThrow();
|
|
17
|
+
});
|
package/src/audit.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Catalog } from "./index";
|
|
2
|
+
|
|
3
|
+
export interface AuditEvent {
|
|
4
|
+
action: string;
|
|
5
|
+
actor: string;
|
|
6
|
+
resource: string;
|
|
7
|
+
resourceId?: string;
|
|
8
|
+
details?: Record<string, unknown>;
|
|
9
|
+
outcome: "success" | "failure";
|
|
10
|
+
reason?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function auditLogger(catalog: Catalog) {
|
|
14
|
+
return {
|
|
15
|
+
log(event: AuditEvent) {
|
|
16
|
+
catalog.info("audit." + event.action, {
|
|
17
|
+
audit: true,
|
|
18
|
+
actor: event.actor,
|
|
19
|
+
resource: event.resource,
|
|
20
|
+
resourceId: event.resourceId,
|
|
21
|
+
details: event.details,
|
|
22
|
+
outcome: event.outcome,
|
|
23
|
+
reason: event.reason,
|
|
24
|
+
});
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { createCatalog } from "./index";
|
|
3
|
+
|
|
4
|
+
test("creates a catalog instance", () => {
|
|
5
|
+
const catalog = createCatalog({ service: "test-service" });
|
|
6
|
+
expect(catalog).toBeDefined();
|
|
7
|
+
expect(typeof catalog.info).toBe("function");
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test("logs info with event name (event-name-first)", () => {
|
|
11
|
+
const catalog = createCatalog({ service: "test", level: "info" });
|
|
12
|
+
expect(() => catalog.info("user.created", { userId: "42" })).not.toThrow();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("logs with object style (standard pino)", () => {
|
|
16
|
+
const catalog = createCatalog({ service: "test", level: "info" });
|
|
17
|
+
expect(() => catalog.info({ userId: "42", message: "User created" })).not.toThrow();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("logs error with event name", () => {
|
|
21
|
+
const catalog = createCatalog({ service: "test", level: "error" });
|
|
22
|
+
expect(() => catalog.error("payment.failed", { amount: 100 })).not.toThrow();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("logs with just an event name (no data)", () => {
|
|
26
|
+
const catalog = createCatalog({ service: "test" });
|
|
27
|
+
expect(() => catalog.info("app.started")).not.toThrow();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test("respects log level", () => {
|
|
31
|
+
const catalog = createCatalog({ service: "test", level: "warn" });
|
|
32
|
+
expect(catalog.level).toBe("warn");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("creates child logger with bound fields", () => {
|
|
36
|
+
const catalog = createCatalog({ service: "app" });
|
|
37
|
+
const child = catalog.child({ requestId: "abc-123" });
|
|
38
|
+
expect(child).toBeDefined();
|
|
39
|
+
expect(typeof child.info).toBe("function");
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("child logger logs without errors", () => {
|
|
43
|
+
const catalog = createCatalog({ service: "app" });
|
|
44
|
+
const child = catalog.child({ requestId: "abc-123" });
|
|
45
|
+
expect(() => child.info("request.handled", { path: "/api" })).not.toThrow();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("child logger supports object style", () => {
|
|
49
|
+
const catalog = createCatalog({ service: "app" });
|
|
50
|
+
const child = catalog.child({ requestId: "abc-123" });
|
|
51
|
+
expect(() => child.info({ path: "/api", method: "GET" })).not.toThrow();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("redacts sensitive fields", () => {
|
|
55
|
+
const catalog = createCatalog({ service: "secure-app" });
|
|
56
|
+
expect(() => catalog.info("user.login", { userId: "1", password: "secret" })).not.toThrow();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("redacts sensitive fields in object style", () => {
|
|
60
|
+
const catalog = createCatalog({ service: "secure-app" });
|
|
61
|
+
expect(() => catalog.info({ userId: "1", password: "secret", email: "a@b.com" })).not.toThrow();
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("handles multiple transport targets", () => {
|
|
65
|
+
const catalog = createCatalog({
|
|
66
|
+
service: "multi-transport",
|
|
67
|
+
transport: [{ target: "pino/file", options: {} }],
|
|
68
|
+
});
|
|
69
|
+
expect(() => catalog.info("app.started")).not.toThrow();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("uses mixin for context injection", () => {
|
|
73
|
+
const catalog = createCatalog({
|
|
74
|
+
service: "with-mixin",
|
|
75
|
+
mixin: () => ({ requestId: "abc-123" }),
|
|
76
|
+
});
|
|
77
|
+
expect(() => catalog.info("request.started")).not.toThrow();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("child logger inherits mixin", () => {
|
|
81
|
+
const catalog = createCatalog({
|
|
82
|
+
service: "with-mixin",
|
|
83
|
+
mixin: () => ({ requestId: "abc-123" }),
|
|
84
|
+
});
|
|
85
|
+
const child = catalog.child({ userId: "42" });
|
|
86
|
+
expect(() => child.info("user.action")).not.toThrow();
|
|
87
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import pino from "pino";
|
|
2
|
+
import type { Logger as PinoLogger, Level as PinoLevel, LoggerOptions } from "pino";
|
|
3
|
+
|
|
4
|
+
export type LogLevel = PinoLevel;
|
|
5
|
+
|
|
6
|
+
export interface TransportOptions {
|
|
7
|
+
target: string;
|
|
8
|
+
options?: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface CatalogOptions {
|
|
12
|
+
service: string;
|
|
13
|
+
level?: LogLevel;
|
|
14
|
+
redact?: string[];
|
|
15
|
+
redactPaths?: string[];
|
|
16
|
+
transport?: TransportOptions | TransportOptions[];
|
|
17
|
+
mixin?: () => Record<string, unknown>;
|
|
18
|
+
base?: Record<string, unknown>;
|
|
19
|
+
environment?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Catalog {
|
|
23
|
+
trace(msg: string, data?: Record<string, unknown>): void;
|
|
24
|
+
trace(data: Record<string, unknown>): void;
|
|
25
|
+
debug(msg: string, data?: Record<string, unknown>): void;
|
|
26
|
+
debug(data: Record<string, unknown>): void;
|
|
27
|
+
info(msg: string, data?: Record<string, unknown>): void;
|
|
28
|
+
info(data: Record<string, unknown>): void;
|
|
29
|
+
warn(msg: string, data?: Record<string, unknown>): void;
|
|
30
|
+
warn(data: Record<string, unknown>): void;
|
|
31
|
+
error(msg: string, data?: Record<string, unknown>): void;
|
|
32
|
+
error(data: Record<string, unknown>): void;
|
|
33
|
+
fatal(msg: string, data?: Record<string, unknown>): void;
|
|
34
|
+
fatal(data: Record<string, unknown>): void;
|
|
35
|
+
child(bindings: Record<string, unknown>): Catalog;
|
|
36
|
+
readonly level: LogLevel;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const SENSITIVE_FIELDS = new Set([
|
|
40
|
+
"password",
|
|
41
|
+
"passwordHash",
|
|
42
|
+
"secret",
|
|
43
|
+
"apiKey",
|
|
44
|
+
"apiSecret",
|
|
45
|
+
"token",
|
|
46
|
+
"accessToken",
|
|
47
|
+
"refreshToken",
|
|
48
|
+
"idToken",
|
|
49
|
+
"ssn",
|
|
50
|
+
"taxId",
|
|
51
|
+
"passportNumber",
|
|
52
|
+
"driverLicense",
|
|
53
|
+
"phone",
|
|
54
|
+
"phoneNumber",
|
|
55
|
+
"mobile",
|
|
56
|
+
"email",
|
|
57
|
+
"emailAddress",
|
|
58
|
+
"accountNumber",
|
|
59
|
+
"routingNumber",
|
|
60
|
+
"iban",
|
|
61
|
+
"swift",
|
|
62
|
+
"cardNumber",
|
|
63
|
+
"cvv",
|
|
64
|
+
"cvc",
|
|
65
|
+
"expiryDate",
|
|
66
|
+
"pin",
|
|
67
|
+
"bvn",
|
|
68
|
+
"nin",
|
|
69
|
+
"bvnHash",
|
|
70
|
+
"ninHash",
|
|
71
|
+
"ip",
|
|
72
|
+
"ipAddress",
|
|
73
|
+
"userAgent",
|
|
74
|
+
"firstName",
|
|
75
|
+
"lastName",
|
|
76
|
+
"fullName",
|
|
77
|
+
"dateOfBirth",
|
|
78
|
+
"dob",
|
|
79
|
+
"address",
|
|
80
|
+
"location",
|
|
81
|
+
"otp",
|
|
82
|
+
"securityAnswer",
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
function redactFields(
|
|
86
|
+
data: Record<string, unknown>,
|
|
87
|
+
extraFields?: Set<string>
|
|
88
|
+
): Record<string, unknown> {
|
|
89
|
+
const fields = extraFields ? new Set([...SENSITIVE_FIELDS, ...extraFields]) : SENSITIVE_FIELDS;
|
|
90
|
+
const result: Record<string, unknown> = {};
|
|
91
|
+
for (const [key, value] of Object.entries(data)) {
|
|
92
|
+
if (fields.has(key) || fields.has(key.toLowerCase())) {
|
|
93
|
+
result[key] = "[REDACTED]";
|
|
94
|
+
} else if (
|
|
95
|
+
typeof value === "object" &&
|
|
96
|
+
value !== null &&
|
|
97
|
+
!Array.isArray(value) &&
|
|
98
|
+
!(value instanceof Error)
|
|
99
|
+
) {
|
|
100
|
+
result[key] = redactFields(value as Record<string, unknown>, fields);
|
|
101
|
+
} else {
|
|
102
|
+
result[key] = value;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const serializer: LoggerOptions["serializers"] = {
|
|
109
|
+
err: pino.stdSerializers.err,
|
|
110
|
+
error: pino.stdSerializers.err,
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
export function createCatalog(options: CatalogOptions): Catalog {
|
|
114
|
+
const { service, level, redact, redactPaths, transport, mixin, base } = options;
|
|
115
|
+
const extraRedactFields = redact ? new Set(redact) : undefined;
|
|
116
|
+
|
|
117
|
+
const pinoOptions: LoggerOptions = {
|
|
118
|
+
name: service,
|
|
119
|
+
level: level ?? "info",
|
|
120
|
+
redact: redactPaths ? { paths: redactPaths, censor: "[REDACTED]" } : undefined,
|
|
121
|
+
serializers: serializer,
|
|
122
|
+
...(base && { base }),
|
|
123
|
+
mixin() {
|
|
124
|
+
return mixin ? mixin() : {};
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
let logger: PinoLogger;
|
|
129
|
+
|
|
130
|
+
if (transport) {
|
|
131
|
+
const transports = Array.isArray(transport) ? transport : [transport];
|
|
132
|
+
const targets = transports.map((t) => ({
|
|
133
|
+
target: t.target,
|
|
134
|
+
options: t.options ?? {},
|
|
135
|
+
level: level ?? "info",
|
|
136
|
+
}));
|
|
137
|
+
logger = pino(pinoOptions, pino.transport({ targets }) as unknown as pino.DestinationStream);
|
|
138
|
+
} else {
|
|
139
|
+
logger = pino(pinoOptions);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const buildChild = (parentLogger: PinoLogger): Catalog => {
|
|
143
|
+
const childAdapt = (method: PinoLevel) => {
|
|
144
|
+
return (first: string | Record<string, unknown>, second?: Record<string, unknown>) => {
|
|
145
|
+
if (typeof first === "string") {
|
|
146
|
+
if (second) {
|
|
147
|
+
parentLogger[method](redactFields(second, extraRedactFields), first);
|
|
148
|
+
} else {
|
|
149
|
+
parentLogger[method](first);
|
|
150
|
+
}
|
|
151
|
+
} else {
|
|
152
|
+
parentLogger[method](redactFields(first, extraRedactFields));
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
return {
|
|
158
|
+
trace: childAdapt("trace"),
|
|
159
|
+
debug: childAdapt("debug"),
|
|
160
|
+
info: childAdapt("info"),
|
|
161
|
+
warn: childAdapt("warn"),
|
|
162
|
+
error: childAdapt("error"),
|
|
163
|
+
fatal: childAdapt("fatal"),
|
|
164
|
+
|
|
165
|
+
child(bindings: Record<string, unknown>): Catalog {
|
|
166
|
+
return buildChild(parentLogger.child(bindings));
|
|
167
|
+
},
|
|
168
|
+
|
|
169
|
+
get level(): LogLevel {
|
|
170
|
+
return parentLogger.level as LogLevel;
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const catalog: Catalog = buildChild(logger);
|
|
176
|
+
|
|
177
|
+
return catalog;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export default createCatalog;
|
package/src/security.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Catalog } from "./index";
|
|
2
|
+
|
|
3
|
+
export interface SecurityEvent {
|
|
4
|
+
action: string;
|
|
5
|
+
actor: string;
|
|
6
|
+
ip?: string;
|
|
7
|
+
userAgent?: string;
|
|
8
|
+
details?: Record<string, unknown>;
|
|
9
|
+
severity: "low" | "medium" | "high" | "critical";
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function securityLogger(catalog: Catalog) {
|
|
13
|
+
return {
|
|
14
|
+
log(event: SecurityEvent) {
|
|
15
|
+
catalog.warn("security." + event.action, {
|
|
16
|
+
security: true,
|
|
17
|
+
actor: event.actor,
|
|
18
|
+
ip: event.ip,
|
|
19
|
+
userAgent: event.userAgent,
|
|
20
|
+
details: event.details,
|
|
21
|
+
severity: event.severity,
|
|
22
|
+
});
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|