@venturekit/runtime 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -0
- package/dist/handler/context.d.ts +41 -2
- package/dist/handler/context.d.ts.map +1 -1
- package/dist/handler/context.js +28 -4
- package/dist/handler/context.js.map +1 -1
- package/dist/handler/errors.d.ts +11 -0
- package/dist/handler/errors.d.ts.map +1 -1
- package/dist/handler/errors.js +25 -1
- package/dist/handler/errors.js.map +1 -1
- package/dist/handler/handler.d.ts.map +1 -1
- package/dist/handler/handler.js +59 -28
- package/dist/handler/handler.js.map +1 -1
- package/dist/handler/health.d.ts +67 -0
- package/dist/handler/health.d.ts.map +1 -0
- package/dist/handler/health.js +87 -0
- package/dist/handler/health.js.map +1 -0
- package/dist/index.d.ts +7 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/logging/logger.d.ts +39 -2
- package/dist/logging/logger.d.ts.map +1 -1
- package/dist/logging/logger.js +79 -9
- package/dist/logging/logger.js.map +1 -1
- package/dist/middleware/middleware.d.ts +73 -2
- package/dist/middleware/middleware.d.ts.map +1 -1
- package/dist/middleware/middleware.js +160 -7
- package/dist/middleware/middleware.js.map +1 -1
- package/dist/middleware/rate-limit-store.d.ts.map +1 -1
- package/dist/middleware/rate-limit-store.js +12 -0
- package/dist/middleware/rate-limit-store.js.map +1 -1
- package/dist/patterns/idempotency.d.ts +61 -3
- package/dist/patterns/idempotency.d.ts.map +1 -1
- package/dist/patterns/idempotency.js +120 -17
- package/dist/patterns/idempotency.js.map +1 -1
- package/dist/patterns/invoke.d.ts.map +1 -1
- package/dist/patterns/invoke.js +4 -2
- package/dist/patterns/invoke.js.map +1 -1
- package/dist/patterns/saga.d.ts +22 -1
- package/dist/patterns/saga.d.ts.map +1 -1
- package/dist/patterns/saga.js +35 -3
- package/dist/patterns/saga.js.map +1 -1
- package/dist/patterns.d.ts +2 -2
- package/dist/patterns.d.ts.map +1 -1
- package/dist/patterns.js +1 -1
- package/dist/patterns.js.map +1 -1
- package/dist/security/internal-hmac.d.ts +36 -5
- package/dist/security/internal-hmac.d.ts.map +1 -1
- package/dist/security/internal-hmac.js +138 -10
- package/dist/security/internal-hmac.js.map +1 -1
- package/dist/ws/ws.d.ts.map +1 -1
- package/dist/ws/ws.js +49 -10
- package/dist/ws/ws.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Health / readiness endpoint.
|
|
3
|
+
*
|
|
4
|
+
* `GET /health` is what uptime monitors, load balancers and the deploy
|
|
5
|
+
* smoke test hit. It must be public, cheap, and honest: `200` only when
|
|
6
|
+
* the dependencies the service cannot work without answer; `503` with a
|
|
7
|
+
* per-check breakdown otherwise — without leaking connection strings or
|
|
8
|
+
* stack traces to whoever is polling.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* // src/routes/health/get.ts
|
|
12
|
+
* import { createHealthHandler } from '@venturekit/runtime';
|
|
13
|
+
* import { query } from '@venturekit/data';
|
|
14
|
+
*
|
|
15
|
+
* export const main = createHealthHandler({
|
|
16
|
+
* checks: {
|
|
17
|
+
* database: () => query('SELECT 1'),
|
|
18
|
+
* // anything returning / resolving is healthy; throwing or timing out is not
|
|
19
|
+
* },
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* A liveness probe (is the process up at all?) is the same handler with
|
|
24
|
+
* no checks — it answers `200` immediately.
|
|
25
|
+
*/
|
|
26
|
+
function exposeByDefault(env) {
|
|
27
|
+
return env.VENTURE_LOCAL === 'true' || ['1', 'true', 'on', 'yes'].includes((env.VK_EXPOSE_ERROR_DETAIL ?? '').toLowerCase());
|
|
28
|
+
}
|
|
29
|
+
async function runCheck(name, check, timeoutMs) {
|
|
30
|
+
const started = Date.now();
|
|
31
|
+
let timer;
|
|
32
|
+
try {
|
|
33
|
+
await Promise.race([
|
|
34
|
+
Promise.resolve().then(check),
|
|
35
|
+
new Promise((_, reject) => {
|
|
36
|
+
timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
37
|
+
}),
|
|
38
|
+
]);
|
|
39
|
+
return { status: 'ok', durationMs: Date.now() - started };
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
return { status: 'fail', durationMs: Date.now() - started, error: err instanceof Error ? err.message : String(err) };
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
if (timer)
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Run the checks and build the report — the handler minus the HTTP envelope. */
|
|
50
|
+
export async function runHealthChecks(options = {}) {
|
|
51
|
+
const timeoutMs = options.timeoutMs ?? 2_000;
|
|
52
|
+
const optional = new Set(options.optional ?? []);
|
|
53
|
+
const expose = options.exposeErrors ?? exposeByDefault(process.env);
|
|
54
|
+
const entries = Object.entries(options.checks ?? {});
|
|
55
|
+
const results = await Promise.all(entries.map(([name, check]) => runCheck(name, check, timeoutMs)));
|
|
56
|
+
const checks = {};
|
|
57
|
+
let degraded = false;
|
|
58
|
+
entries.forEach(([name], i) => {
|
|
59
|
+
const r = results[i];
|
|
60
|
+
const isOptional = optional.has(name);
|
|
61
|
+
if (r.status === 'fail' && !isOptional)
|
|
62
|
+
degraded = true;
|
|
63
|
+
checks[name] = {
|
|
64
|
+
status: r.status,
|
|
65
|
+
durationMs: r.durationMs,
|
|
66
|
+
...(isOptional ? { optional: true } : {}),
|
|
67
|
+
...(r.error && expose ? { error: r.error } : {}),
|
|
68
|
+
};
|
|
69
|
+
});
|
|
70
|
+
return { ...(options.info ?? {}), status: degraded ? 'degraded' : 'ok', checks, timestamp: new Date().toISOString() };
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A Lambda handler for `GET /health`: `200` + report when every required
|
|
74
|
+
* check passes, `503` otherwise. `Cache-Control: no-store` so no proxy
|
|
75
|
+
* serves a stale "ok".
|
|
76
|
+
*/
|
|
77
|
+
export function createHealthHandler(options = {}) {
|
|
78
|
+
return async (_event) => {
|
|
79
|
+
const report = await runHealthChecks(options);
|
|
80
|
+
return {
|
|
81
|
+
statusCode: report.status === 'ok' ? 200 : 503,
|
|
82
|
+
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
|
|
83
|
+
body: JSON.stringify(report),
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=health.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"health.js","sourceRoot":"","sources":["../../src/handler/health.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAwCH,SAAS,eAAe,CAAC,GAAsB;IAC7C,OAAO,GAAG,CAAC,aAAa,KAAK,MAAM,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,sBAAsB,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAC/H,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,IAAY,EAAE,KAAkB,EAAE,SAAiB;IACzE,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC3B,IAAI,KAAiC,CAAC;IACtC,IAAI,CAAC;QACH,MAAM,OAAO,CAAC,IAAI,CAAC;YACjB,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC;YAC7B,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;gBACxB,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,mBAAmB,SAAS,IAAI,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;YAC3F,CAAC,CAAC;SACH,CAAC,CAAC;QACH,OAA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;AACJ,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -24,17 +24,19 @@ export { taskHandler, TaskValidationError } from './handler/task-handler.js';
|
|
|
24
24
|
export { queueBatchHandler } from './handler/queue-batch.js';
|
|
25
25
|
export type { QueueBatchHandlerConfig, QueueMessageContext, QueueMessageHandlerFn, QueueMessageParser, QueueRawMessage, } from './handler/queue-batch.js';
|
|
26
26
|
export type { TaskHandlerFn, TaskContext, TaskHandlerConfig, } from './handler/task-handler.js';
|
|
27
|
-
export { buildContext, extractUserContext, extractLocale, setCookie, getRequestHost, } from './handler/context.js';
|
|
28
|
-
export type { BaseContext, RequestContext, UserContext, TenantContext, Transaction } from './handler/context.js';
|
|
27
|
+
export { buildContext, extractUserContext, extractLocale, setCookie, getRequestHost, isAllowedHost, } from './handler/context.js';
|
|
28
|
+
export type { BaseContext, RequestContext, UserContext, TenantContext, Transaction, GetRequestHostOptions, } from './handler/context.js';
|
|
29
|
+
export { createHealthHandler, runHealthChecks } from './handler/health.js';
|
|
30
|
+
export type { HealthCheck, HealthHandlerOptions, HealthCheckResult, HealthReport } from './handler/health.js';
|
|
29
31
|
export { success, created, noContent, error, errorResponse, redirect, rawResult, isRawResult, } from './handler/response.js';
|
|
30
32
|
export type { SuccessResponse, ErrorResponse, RawResult } from './handler/response.js';
|
|
31
|
-
export { VentureError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PayloadTooLargeError, ValidationError, RateLimitError, InternalError, ServiceUnavailableError, isVentureError, } from './handler/errors.js';
|
|
33
|
+
export { VentureError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PayloadTooLargeError, ValidationError, RateLimitError, InternalError, ServiceUnavailableError, isVentureError, VENTURE_ERROR_MARKER, } from './handler/errors.js';
|
|
32
34
|
export { Logger, createLogger, logger, } from './logging/logger.js';
|
|
33
35
|
export type { LogLevel, LogEntry, LoggerConfig } from './logging/logger.js';
|
|
34
36
|
export { createMetrics } from './logging/metrics.js';
|
|
35
37
|
export type { MetricsClient, MetricsOptions, MetricUnit, StorageResolution, } from './logging/metrics.js';
|
|
36
|
-
export { compose, loggingMiddleware, corsMiddleware, timeoutMiddleware, errorBoundaryMiddleware, rateLimitMiddleware, requestIdMiddleware, timingMiddleware, apiKeyAuthMiddleware, } from './middleware/middleware.js';
|
|
37
|
-
export type { MiddlewareFn, Middleware, RateLimitCheck, RateLimitOptions } from './middleware/middleware.js';
|
|
38
|
+
export { compose, loggingMiddleware, corsMiddleware, timeoutMiddleware, errorBoundaryMiddleware, rateLimitMiddleware, requestIdMiddleware, timingMiddleware, apiKeyAuthMiddleware, originCheckMiddleware, securityHeadersMiddleware, } from './middleware/middleware.js';
|
|
39
|
+
export type { MiddlewareFn, Middleware, RateLimitCheck, RateLimitOptions, OriginCheckOptions, SecurityHeadersOptions, } from './middleware/middleware.js';
|
|
38
40
|
export { createMemoryRateLimitStore, createDefaultRateLimiter, RATE_LIMIT_PRESETS, } from './middleware/rate-limit-store.js';
|
|
39
41
|
export type { RateLimitPreset, RateLimitPresetConfig, DefaultRateLimiterOptions, } from './middleware/rate-limit-store.js';
|
|
40
42
|
export { httpToLambdaEvent, createLocalContext, lambdaResultToHttp, adaptHandler, } from './handler/adapter.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,EACL,OAAO,EACP,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAChG,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAGjF,OAAO,EAAE,WAAW,EAAE,mBAA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C,CAAC;AAC1C,YAAY,EACV,eAAe,EACf,qBAAqB,EACrB,yBAAyB,GAC1B,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,YAAY,GACb,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,UAAU,EACV,aAAa,GACd,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAGzD,OAAO,EACL,eAAe,EACf,GAAG,GACJ,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACV,aAAa,EACb,SAAS,GACV,MAAM,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -23,17 +23,19 @@ export { createHandler } from './handler/create-handler.js';
|
|
|
23
23
|
export { taskHandler, TaskValidationError } from './handler/task-handler.js';
|
|
24
24
|
export { queueBatchHandler } from './handler/queue-batch.js';
|
|
25
25
|
// Context
|
|
26
|
-
export { buildContext, extractUserContext, extractLocale, setCookie, getRequestHost, } from './handler/context.js';
|
|
26
|
+
export { buildContext, extractUserContext, extractLocale, setCookie, getRequestHost, isAllowedHost, } from './handler/context.js';
|
|
27
|
+
// Health / readiness endpoint
|
|
28
|
+
export { createHealthHandler, runHealthChecks } from './handler/health.js';
|
|
27
29
|
// Response utilities
|
|
28
30
|
export { success, created, noContent, error, errorResponse, redirect, rawResult, isRawResult, } from './handler/response.js';
|
|
29
31
|
// Errors
|
|
30
|
-
export { VentureError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PayloadTooLargeError, ValidationError, RateLimitError, InternalError, ServiceUnavailableError, isVentureError, } from './handler/errors.js';
|
|
32
|
+
export { VentureError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PayloadTooLargeError, ValidationError, RateLimitError, InternalError, ServiceUnavailableError, isVentureError, VENTURE_ERROR_MARKER, } from './handler/errors.js';
|
|
31
33
|
// Logger
|
|
32
34
|
export { Logger, createLogger, logger, } from './logging/logger.js';
|
|
33
35
|
// Metrics (CloudWatch EMF)
|
|
34
36
|
export { createMetrics } from './logging/metrics.js';
|
|
35
37
|
// Middleware (core — no heavy deps)
|
|
36
|
-
export { compose, loggingMiddleware, corsMiddleware, timeoutMiddleware, errorBoundaryMiddleware, rateLimitMiddleware, requestIdMiddleware, timingMiddleware, apiKeyAuthMiddleware, } from './middleware/middleware.js';
|
|
38
|
+
export { compose, loggingMiddleware, corsMiddleware, timeoutMiddleware, errorBoundaryMiddleware, rateLimitMiddleware, requestIdMiddleware, timingMiddleware, apiKeyAuthMiddleware, originCheckMiddleware, securityHeadersMiddleware, } from './middleware/middleware.js';
|
|
37
39
|
// Rate limiting (no static AWS deps — the DynamoDB backend is lazy-imported,
|
|
38
40
|
// so `createDefaultRateLimiter` is safe to expose on the core entry)
|
|
39
41
|
export { createMemoryRateLimitStore, createDefaultRateLimiter, RATE_LIMIT_PRESETS, } from './middleware/rate-limit-store.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,wBAAwB;AACxB,OAAO,EACL,OAAO,EACP,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAG5D,0CAA0C;AAC1C,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAc7D,UAAU;AACV,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,SAAS,EACT,cAAc,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":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;AAC7E,qEAAqE;AACrE,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAO1C,qDAAqD;AACrD,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,EAClB,YAAY,GACb,MAAM,sBAAsB,CAAC;AAE9B,UAAU;AACV,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,UAAU,EACV,aAAa,GACd,MAAM,sBAAsB,CAAC;AAG9B,sCAAsC;AACtC,OAAO,EACL,eAAe,EACf,GAAG,GACJ,MAAM,iBAAiB,CAAC"}
|
package/dist/logging/logger.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* - Child logger support with bound fields
|
|
11
11
|
* - Lambda-optimized (no worker threads, synchronous output)
|
|
12
12
|
*/
|
|
13
|
+
import pino from 'pino';
|
|
13
14
|
import { RequestContext } from '../handler/context.js';
|
|
14
15
|
/**
|
|
15
16
|
* Log levels
|
|
@@ -46,6 +47,21 @@ export interface LoggerConfig {
|
|
|
46
47
|
*/
|
|
47
48
|
infoSampleRate?: number;
|
|
48
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Log-field paths that are censored before a line is written.
|
|
52
|
+
*
|
|
53
|
+
* The runtime itself only logs method / path / ip, but a handler that does
|
|
54
|
+
* `log.info('request', { event: ctx.rawEvent })` — the natural debugging
|
|
55
|
+
* move — would otherwise ship the `Authorization` header and every session
|
|
56
|
+
* cookie to CloudWatch, where log readers are a far larger group than
|
|
57
|
+
* secret readers. Redaction happens inside pino (fast-redact) at
|
|
58
|
+
* serialization time, so it costs nothing when the keys are absent.
|
|
59
|
+
*
|
|
60
|
+
* Paths follow pino's redact syntax: a leading `*` matches any top-level
|
|
61
|
+
* key, so `*.headers.authorization` covers `event.headers.authorization`,
|
|
62
|
+
* `rawEvent.headers.authorization`, `req.headers.authorization`, …
|
|
63
|
+
*/
|
|
64
|
+
export declare const REDACTED_LOG_PATHS: readonly string[];
|
|
49
65
|
/**
|
|
50
66
|
* Logger instance — thin wrapper over pino
|
|
51
67
|
*/
|
|
@@ -61,11 +77,32 @@ export declare class Logger {
|
|
|
61
77
|
private rootPinoLogger;
|
|
62
78
|
private context;
|
|
63
79
|
private config;
|
|
64
|
-
constructor(config?: Partial<LoggerConfig>);
|
|
65
80
|
/**
|
|
66
|
-
*
|
|
81
|
+
* @param config Logger configuration.
|
|
82
|
+
* @param root Internal — share an existing pino root instead of building
|
|
83
|
+
* one. Used by {@link forRequest} / {@link child}, which are
|
|
84
|
+
* called per request and must not pay for a fresh pino
|
|
85
|
+
* instance (with its redaction compiler) each time.
|
|
86
|
+
*/
|
|
87
|
+
constructor(config?: Partial<LoggerConfig>, root?: pino.Logger);
|
|
88
|
+
/**
|
|
89
|
+
* Set request context for all subsequent logs.
|
|
90
|
+
*
|
|
91
|
+
* **Mutates this instance.** Safe only where one logger serves one
|
|
92
|
+
* request at a time — the Lambda model. Under `vk dev`, a container
|
|
93
|
+
* adapter, or anything else that overlaps requests, two calls race
|
|
94
|
+
* and every line of request A is stamped with request B's ids. Prefer
|
|
95
|
+
* {@link forRequest}, which returns a bound copy and leaves this
|
|
96
|
+
* instance untouched; `handler()` does exactly that.
|
|
67
97
|
*/
|
|
68
98
|
setContext(context: RequestContext): void;
|
|
99
|
+
/**
|
|
100
|
+
* A NEW logger bound to `context`'s request fields (`requestId`,
|
|
101
|
+
* `userId`, `tenantId`). This instance is not modified, so one shared
|
|
102
|
+
* module-level logger can fan out to any number of concurrent
|
|
103
|
+
* requests without their fields bleeding into each other.
|
|
104
|
+
*/
|
|
105
|
+
forRequest(context: RequestContext): Logger;
|
|
69
106
|
/**
|
|
70
107
|
* Clear request context. Restores the original unbound logger instead of
|
|
71
108
|
* minting a brand-new pino root — that way log-level / formatter tweaks
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logging/logger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;;;;;;OASG;IACH,UAAU,CAAC,OAAO,EAAE,cAAc,GAAG,IAAI;IAOzC;;;;;OAKG;IACH,UAAU,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM;IAO3C;;;;OAIG;IACH,YAAY,IAAI,IAAI;IAKpB;;OAEG;IACH,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM;IAO9C,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAI5D,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAU3D,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAI3D,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;CAG7D;AAED;;GAEG;AACH,eAAO,MAAM,MAAM,QAAe,CAAC;AAEnC;;GAEG;AACH,wBAAgB,YAAY,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAAG,MAAM,CAEnE"}
|
package/dist/logging/logger.js
CHANGED
|
@@ -28,6 +28,45 @@ function resolveSampleRate(raw) {
|
|
|
28
28
|
return 1;
|
|
29
29
|
return n;
|
|
30
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Log-field paths that are censored before a line is written.
|
|
33
|
+
*
|
|
34
|
+
* The runtime itself only logs method / path / ip, but a handler that does
|
|
35
|
+
* `log.info('request', { event: ctx.rawEvent })` — the natural debugging
|
|
36
|
+
* move — would otherwise ship the `Authorization` header and every session
|
|
37
|
+
* cookie to CloudWatch, where log readers are a far larger group than
|
|
38
|
+
* secret readers. Redaction happens inside pino (fast-redact) at
|
|
39
|
+
* serialization time, so it costs nothing when the keys are absent.
|
|
40
|
+
*
|
|
41
|
+
* Paths follow pino's redact syntax: a leading `*` matches any top-level
|
|
42
|
+
* key, so `*.headers.authorization` covers `event.headers.authorization`,
|
|
43
|
+
* `rawEvent.headers.authorization`, `req.headers.authorization`, …
|
|
44
|
+
*/
|
|
45
|
+
export const REDACTED_LOG_PATHS = [
|
|
46
|
+
// Credentials in transit.
|
|
47
|
+
'authorization',
|
|
48
|
+
'cookie',
|
|
49
|
+
'headers.authorization',
|
|
50
|
+
'headers.cookie',
|
|
51
|
+
'headers["set-cookie"]',
|
|
52
|
+
'*.headers.authorization',
|
|
53
|
+
'*.headers.cookie',
|
|
54
|
+
'*.headers["set-cookie"]',
|
|
55
|
+
// API Gateway v2 carries request cookies as an array beside `headers`.
|
|
56
|
+
'cookies',
|
|
57
|
+
'*.cookies',
|
|
58
|
+
// Tokens and secrets that end up in `data` objects.
|
|
59
|
+
'password',
|
|
60
|
+
'accessToken',
|
|
61
|
+
'refreshToken',
|
|
62
|
+
'idToken',
|
|
63
|
+
'clientSecret',
|
|
64
|
+
'*.password',
|
|
65
|
+
'*.accessToken',
|
|
66
|
+
'*.refreshToken',
|
|
67
|
+
'*.idToken',
|
|
68
|
+
'*.clientSecret',
|
|
69
|
+
];
|
|
31
70
|
/**
|
|
32
71
|
* Build a fresh root pino logger with Lambda-friendly defaults.
|
|
33
72
|
*
|
|
@@ -44,6 +83,7 @@ function buildRootPino(config) {
|
|
|
44
83
|
// Drop default `pid` and `hostname` fields. In Lambda they're constant
|
|
45
84
|
// per container and just bloat every log line with no operational value.
|
|
46
85
|
base: null,
|
|
86
|
+
redact: { paths: [...REDACTED_LOG_PATHS], censor: '[REDACTED]' },
|
|
47
87
|
formatters: {
|
|
48
88
|
level(label) {
|
|
49
89
|
return { level: label };
|
|
@@ -51,6 +91,14 @@ function buildRootPino(config) {
|
|
|
51
91
|
},
|
|
52
92
|
});
|
|
53
93
|
}
|
|
94
|
+
/** Request-scoped fields bound onto every line logged for one request. */
|
|
95
|
+
function requestFields(context) {
|
|
96
|
+
return {
|
|
97
|
+
requestId: context.requestId,
|
|
98
|
+
...(context.user?.id && { userId: context.user.id }),
|
|
99
|
+
...(context.tenant?.id && { tenantId: context.tenant.id }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
54
102
|
/**
|
|
55
103
|
* Logger instance — thin wrapper over pino
|
|
56
104
|
*/
|
|
@@ -66,27 +114,49 @@ export class Logger {
|
|
|
66
114
|
rootPinoLogger;
|
|
67
115
|
context = null;
|
|
68
116
|
config;
|
|
69
|
-
|
|
117
|
+
/**
|
|
118
|
+
* @param config Logger configuration.
|
|
119
|
+
* @param root Internal — share an existing pino root instead of building
|
|
120
|
+
* one. Used by {@link forRequest} / {@link child}, which are
|
|
121
|
+
* called per request and must not pay for a fresh pino
|
|
122
|
+
* instance (with its redaction compiler) each time.
|
|
123
|
+
*/
|
|
124
|
+
constructor(config = {}, root) {
|
|
70
125
|
this.config = {
|
|
71
126
|
minLevel: config.minLevel ?? 'info',
|
|
72
127
|
includeContext: config.includeContext ?? true,
|
|
73
128
|
infoSampleRate: config.infoSampleRate ?? resolveSampleRate(process.env.LOG_SAMPLE_RATE),
|
|
74
129
|
};
|
|
75
|
-
this.rootPinoLogger = buildRootPino(this.config);
|
|
130
|
+
this.rootPinoLogger = root ?? buildRootPino(this.config);
|
|
76
131
|
this.pinoLogger = this.rootPinoLogger;
|
|
77
132
|
}
|
|
78
133
|
/**
|
|
79
|
-
* Set request context for all subsequent logs
|
|
134
|
+
* Set request context for all subsequent logs.
|
|
135
|
+
*
|
|
136
|
+
* **Mutates this instance.** Safe only where one logger serves one
|
|
137
|
+
* request at a time — the Lambda model. Under `vk dev`, a container
|
|
138
|
+
* adapter, or anything else that overlaps requests, two calls race
|
|
139
|
+
* and every line of request A is stamped with request B's ids. Prefer
|
|
140
|
+
* {@link forRequest}, which returns a bound copy and leaves this
|
|
141
|
+
* instance untouched; `handler()` does exactly that.
|
|
80
142
|
*/
|
|
81
143
|
setContext(context) {
|
|
82
144
|
this.context = context;
|
|
83
145
|
// Bind a child off the root (not off the previous binding) so we never
|
|
84
146
|
// accumulate fields from a stale request on warm-container reuse.
|
|
85
|
-
this.pinoLogger = this.rootPinoLogger.child(
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
147
|
+
this.pinoLogger = this.rootPinoLogger.child(requestFields(context));
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* A NEW logger bound to `context`'s request fields (`requestId`,
|
|
151
|
+
* `userId`, `tenantId`). This instance is not modified, so one shared
|
|
152
|
+
* module-level logger can fan out to any number of concurrent
|
|
153
|
+
* requests without their fields bleeding into each other.
|
|
154
|
+
*/
|
|
155
|
+
forRequest(context) {
|
|
156
|
+
const bound = new Logger(this.config, this.rootPinoLogger);
|
|
157
|
+
bound.pinoLogger = this.rootPinoLogger.child(requestFields(context));
|
|
158
|
+
bound.context = context;
|
|
159
|
+
return bound;
|
|
90
160
|
}
|
|
91
161
|
/**
|
|
92
162
|
* Clear request context. Restores the original unbound logger instead of
|
|
@@ -101,7 +171,7 @@ export class Logger {
|
|
|
101
171
|
* Create a child logger with additional default fields
|
|
102
172
|
*/
|
|
103
173
|
child(fields) {
|
|
104
|
-
const childLogger = new Logger(this.config);
|
|
174
|
+
const childLogger = new Logger(this.config, this.rootPinoLogger);
|
|
105
175
|
childLogger.pinoLogger = this.pinoLogger.child(fields);
|
|
106
176
|
childLogger.context = this.context;
|
|
107
177
|
return childLogger;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logging/logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,IAAI,MAAM,MAAM,CAAC;AAyCxB;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,GAAuB;IAChD,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,CAAC,CAAC;IACh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CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,OAAe,EAAE,IAA8B;QACnD,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/E,CAAC;CACF;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;AAEnC;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,MAA8B;IACzD,OAAO,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC"}
|
|
@@ -40,9 +40,14 @@ export interface Middleware<TCtx extends BaseContext = BaseContext> {
|
|
|
40
40
|
*/
|
|
41
41
|
export declare function compose(middlewares: Middleware<RequestContext>[]): MiddlewareFn<RequestContext>;
|
|
42
42
|
/**
|
|
43
|
-
* Logging middleware - logs request/response
|
|
43
|
+
* Logging middleware - logs request/response.
|
|
44
|
+
*
|
|
45
|
+
* Logs through `ctx.logger` (the request-bound logger `handler()` installs)
|
|
46
|
+
* when present, so lines carry this request's ids even when several
|
|
47
|
+
* requests share the process; `fallback` is used for contexts built
|
|
48
|
+
* without one.
|
|
44
49
|
*/
|
|
45
|
-
export declare function loggingMiddleware(
|
|
50
|
+
export declare function loggingMiddleware(fallback: Logger): Middleware<RequestContext>;
|
|
46
51
|
/**
|
|
47
52
|
* CORS middleware - adds CORS headers
|
|
48
53
|
*/
|
|
@@ -120,4 +125,70 @@ export declare function apiKeyAuthMiddleware(options: {
|
|
|
120
125
|
/** Validate the API key. Return true if valid. */
|
|
121
126
|
validate: (apiKey: string) => Promise<boolean> | boolean;
|
|
122
127
|
}): Middleware<RequestContext>;
|
|
128
|
+
export interface OriginCheckOptions {
|
|
129
|
+
/**
|
|
130
|
+
* Origins (scheme + host[:port], e.g. `https://app.example.com`) allowed
|
|
131
|
+
* to make state-changing requests, or a predicate over the normalized
|
|
132
|
+
* origin. A `.apex` entry (`.example.com`) matches every https subdomain.
|
|
133
|
+
*/
|
|
134
|
+
allowedOrigins: readonly string[] | ((origin: string) => boolean);
|
|
135
|
+
/** Methods that are checked. Default: everything but GET / HEAD / OPTIONS. */
|
|
136
|
+
protectMethods?: readonly string[];
|
|
137
|
+
/**
|
|
138
|
+
* Allow a cookie-bearing request that carries neither `Origin` nor
|
|
139
|
+
* `Referer`. Every current browser sends `Origin` on cross-origin and
|
|
140
|
+
* same-origin POSTs, so the safe default is `false`; set `true` only for
|
|
141
|
+
* a WebView / native client known to strip both.
|
|
142
|
+
*/
|
|
143
|
+
allowMissingOrigin?: boolean;
|
|
144
|
+
/**
|
|
145
|
+
* Header that marks a request as cookie-authenticated. Default: the
|
|
146
|
+
* presence of any `Cookie` header. A bearer-only API never needs this
|
|
147
|
+
* middleware — browsers do not attach `Authorization` on their own.
|
|
148
|
+
*/
|
|
149
|
+
isCookieRequest?: (ctx: RequestContext) => boolean;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* CSRF protection for cookie-authenticated APIs.
|
|
153
|
+
*
|
|
154
|
+
* A browser attaches session cookies to any request a third-party page
|
|
155
|
+
* triggers, so a cookie-based API must know WHERE a state-changing request
|
|
156
|
+
* came from. `SameSite=Lax` covers most cases but not all (same-site
|
|
157
|
+
* sibling apps, older clients, `SameSite=None` deployments behind a
|
|
158
|
+
* cross-site proxy). This middleware closes the gap the standard way:
|
|
159
|
+
*
|
|
160
|
+
* - Methods outside `protectMethods` (default GET/HEAD/OPTIONS) pass.
|
|
161
|
+
* - Requests without cookies pass — nothing to forge.
|
|
162
|
+
* - `Sec-Fetch-Site: same-origin` / `none` pass (the browser vouches).
|
|
163
|
+
* - Otherwise `Origin` (falling back to `Referer`) must be in
|
|
164
|
+
* `allowedOrigins`; a missing header is rejected unless
|
|
165
|
+
* `allowMissingOrigin`.
|
|
166
|
+
* - Internal HMAC-verified calls (`ctx.isInternal`) pass.
|
|
167
|
+
*
|
|
168
|
+
* Rejections throw {@link ForbiddenError} (`403 FORBIDDEN`) so the handler's
|
|
169
|
+
* error boundary renders the standard envelope. Put it BEFORE auth so a
|
|
170
|
+
* forged request never reaches the token verifier.
|
|
171
|
+
*/
|
|
172
|
+
export declare function originCheckMiddleware(options: OriginCheckOptions): Middleware<RequestContext>;
|
|
173
|
+
export interface SecurityHeadersOptions {
|
|
174
|
+
/** Override or disable (`null`) any default header; add new ones. */
|
|
175
|
+
headers?: Record<string, string | null>;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Baseline security response headers for an API. Defaults:
|
|
179
|
+
*
|
|
180
|
+
* - `Strict-Transport-Security: max-age=63072000; includeSubDomains`
|
|
181
|
+
* - `X-Content-Type-Options: nosniff`
|
|
182
|
+
* - `Referrer-Policy: strict-origin-when-cross-origin`
|
|
183
|
+
* - `X-Frame-Options: DENY`
|
|
184
|
+
* - `Cache-Control: no-store` — API responses carry per-user data and
|
|
185
|
+
* must not land in a shared cache; a handler that serves cacheable
|
|
186
|
+
* content sets its own `Cache-Control`, which wins.
|
|
187
|
+
* - `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`
|
|
188
|
+
* — inert for JSON, and the right policy for the odd `rawResult` HTML
|
|
189
|
+
* page (handoff, OAuth completion) that should never load scripts.
|
|
190
|
+
*
|
|
191
|
+
* Headers already present on the response are never overwritten.
|
|
192
|
+
*/
|
|
193
|
+
export declare function securityHeadersMiddleware(options?: SecurityHeadersOptions): Middleware<RequestContext>;
|
|
123
194
|
//# sourceMappingURL=middleware.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/middleware/middleware.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAA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