@blamejs/core 0.6.32 → 0.6.33

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/CHANGELOG.md CHANGED
@@ -8,6 +8,7 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.6.x
10
10
 
11
+ - **0.6.33** (2026-05-02) — log-stream sinks parity sweep. **`b.logStream` syslog sink (RFC 5424)** — first-class `protocol: "syslog"` for `b.logStream.init({ sinks: { ... } })`; new module `lib/log-stream-syslog.js`. URL-driven transport selection: `udp://host:514` / `tcp://host:514` / `tls://host:6514`. UDP is best-effort one-datagram-per-record; TCP / TLS use RFC 6587 octet-counting framing (`<length> <message>`) so collectors that prefer it over the older non-transparent newline framing parse cleanly. TLS is TLS 1.3 minimum; operators with private CAs pass `ca` (PEM string or array) for trust pinning, `servername` for SNI override (auto-suppressed on IP literals per the v0.6.28 redis-client convention). Outgoing records are formatted with PRI = `(facility << 3) | severity`, default facility `local0` (16), severity mapped from the framework's level field (debug=7 / info=6 / warn=4 / error=3); operators override via `facility`, `appName` (default `blamejs`), `procId` (default `process.pid`), `hostname` (default `os.hostname()`), `structuredData` (default `-`). Meta is JSON-encoded into the MSG body so the structured payload survives the wire as a single token. TCP / TLS reconnect with exponential backoff (default 250ms→30s); records buffer during the down window with `bufferLimit`-bounded oldest-drop semantics, replay on reconnect. `close()` waits up to 3s for an in-flight (re)connect to drain the buffer before tearing down — without this the slower TLS handshake raced fire-and-forget shutdown emits and silently dropped records. Operator-supplied `onDrop({reason, batch, error})` surfaces every drop class (`overflow` / `udp-send-error` / `write-error` / `sink-closed`). Removed `syslog` from `DEFERRED_PROTOCOLS`. **`b.logStream` cloudwatch sink: `autoCreate`** — pass `{ autoCreate: true }` to have the framework issue `CreateLogGroup` + `CreateLogStream` on first emit so operators provisioning collectors via env vars / runbooks don't need a separate aws-cli step. Idempotent: AWS's `ResourceAlreadyExistsException` is treated as success on both calls. Hard failures (5xx, AccessDenied, etc.) drop the batch with `onDrop` reason `autocreate-failed`. Default remains `autoCreate: false` so the AWS posture (operator pre-creates via aws / CDK / Terraform) stays the recommended path; `autoCreate` exists for ephemeral / dynamic-stream deployments where pre-provisioning is impractical. **Test suite**: 19 new framework-level cloudwatch assertions cover autoCreate fires both Create calls in order before PutLogEvents, ResourceAlreadyExists doesn't abort the post-create PutLogEvents, hard 5xx during CreateLogGroup drops the batch via `onDrop`, autoCreate=false skips Create calls entirely. Live syslog integration covers UDP / TCP wire delivery against the docker syslog-ng container (`/var/log/blamejs-test.log`) plus an in-process `tls.createServer` receiver that asserts the on-the-wire RFC 6587 octet-counting framing + RFC 5424 PRI / timestamp / structured-data slot the framework emits over TLS. **Test infrastructure fix**: `docker/init/generate-certs.sh` was overwriting an existing CA when re-run with `.complete` removed, invalidating every previously-issued leaf cert; now reuses an existing `(ca.crt, ca.key)` pair across `.complete`-only resets and only generates a fresh CA when neither file is present. Smoke 6790 / wiki e2e 178 / per-primitive integration 14 files (log-stream up from 16→18 checks, cloudwatch suite up from 39→58 assertions) / wiki integration 32 / shellcheck clean / eslint clean.
11
12
  - **0.6.32** (2026-05-02) — E1 from the v0.6.x scope plan. **`b.cache` Redis backend** — first-class `backend: "redis"` for `b.cache.create({...})`, no operator-supplied glue needed. New module `lib/cache-redis.js` consumes `lib/redis-client.js` directly; storage layout: `<namespace>:e:<key>` (STRING, JSON-encoded value, PEXPIREAT-bounded), `<namespace>:t:<tag>` (SET, cacheKeys carrying that tag — powers `invalidateTag` fan-out), `<namespace>:k:<key>:tags` (SET, tags this key carries — powers per-key tag cleanup on `del`/`set`-overwrite, expires alongside the entry). TTL is enforced by Redis itself (PEXPIREAT) so the framework's sweeper is a no-op for this backend; sliding TTL bumps the entry's expiry on every read when `slidingTtl: true` AND `ttlMs` is finite. New opts on `cache.create`: `redisUrl` (required when `backend: "redis"`), `redisPassword`, `redisUsername`, `redisTls`, `redisCa` (private-CA trust pinning per v0.6.28), `redisServername`, `redisConnectTimeoutMs`, `redisCommandTimeoutMs`, `redisMaxReconnectAttempts`. Concurrency: invalidateTag filters out ghost entries (key already PEXPIRE'd from the keyspace but lingering in a tag SET) by EXISTS-checking before del. Lazy connect — `cache.create({backend:"redis"})` stays sync-safe; first op opens the socket. Tests: 10 new live integration assertions on top of the existing memory + custom-backend coverage (set+get round-trip, has, del, complex JSON value round-trip, short-TTL Redis-side expiry, multi-tag invalidateTag fan-out + preservation of untagged entries, wrap() single-flight memoization through Redis). Smoke 6780 / wiki e2e 178 / per-primitive integration 14 files (cache up from 15→25 checks) / wiki integration green.
12
13
  - **0.6.31** (2026-05-02) — lazy-deferral cleanup wave from v0.6.27. **A1: queue-redis priority ordering** — `b.queue.enqueue({ priority })` on the Redis backend now matches queue-local's `ORDER BY priority DESC, availableAt ASC, enqueuedAt ASC` semantics. The Redis ZSET stays scored by availableAt only (so ZRANGEBYSCORE 0..nowMs cleanly filters ready vs not-yet-ready jobs), but `LEASE_LUA` now over-fetches `maxRows*5` candidates by score, HMGETs priority + availableAt + enqueuedAt for each, sorts server-side in Lua by the same triple queue-local sorts on, and leases the top `maxRows`. Closes the v0.6.27 deferral that punted priority ordering as "ZSET-incompatible". **A2: queue-redis flow `dependsOn` cascade** — `b.queue.enqueue({ flowId, flowChildName, dependsOn })` on the Redis backend now releases dependent jobs when their parents complete, mirroring queue-local's `_maybeReleaseFlowChildren`. A per-flow `<prefix>:flow:<flowId>` Redis SET tracks every job in the flow; `complete()` walks the set, looks up siblings whose `dependsOn` includes the just-completed job (by id OR `flowChildName`) AND every other dep is also satisfied, and HSET-bumps their `availableAt` to now + ZADDs them into the ready zset. The flow set persists across `complete()` calls so a later sibling's deps check can still find earlier-done parents by name; `purge()` cleans the set on queue teardown. Closes the v0.6.27 deferral. **A4: WebSocket per-message-deflate (RFC 7692)** — `b.websocket.handleUpgrade` negotiates the `permessage-deflate` extension when the client offers it, accepting `client_max_window_bits` / `server_max_window_bits` constraints (8-15 range, default 15) and always asserting `client_no_context_takeover` + `server_no_context_takeover` so every message uses a fresh zlib state. The connection's send path compresses TEXT/BINARY frames via `zlib.deflateRawSync`, strips the 4-byte `0x00 0x00 0xff 0xff` trailer per RFC 7692 §7.2.1, and sets RSV1 on the first frame of each compressed message. The receive path appends the trailer back and inflates via `zlib.inflateRawSync`. RSV1 on a continuation frame, RSV1 without negotiated extension, RSV2/RSV3 set, and decompressed payload exceeding `maxMessageBytes` all close with the appropriate RFC 6455 status (`PROTOCOL_ERROR`, `INVALID_PAYLOAD`, `MESSAGE_TOO_BIG`). Operator opt-out: pass `permessageDeflate: false` to `handleUpgrade` to refuse the extension even when offered. Tests cover the 101-handshake echo of negotiated params, real compression on a redundant payload (4000 bytes → ~30 bytes on the wire), uncompressed-frame round-trip on the same connection (mixed-mode per RFC 7692 §6), and unknown-extension graceful ignore. v0.6.27's third lazy deferral A3 (TLS-redis live test) was already covered by `test/integration/redis-client-tls.test.js` shipped in v0.6.28. Smoke 6780 / wiki e2e 178 / per-primitive integration 14 files green / wiki integration green.
13
14
  - **0.6.30** (2026-05-02) — wiki-app integration gate + framework follow-ups surfaced by it. **`scripts/test-wiki-integration.js`** boots `examples/wiki` against the docker-compose fixture stack (real Redis / MinIO / Mailpit / CoreDNS / NTP / mtls-ca) and drives every backend through the wiki's HTTP surface AND the underlying framework primitives — validates that each primitive routes through the configured backend (cache → custom backend, queue → Redis Streams, mail → Mailpit SMTP, object-store → MinIO sigv4, log-stream → webhook receiver) AND that every fix shipped in v0.6.28 holds in a real-app context, not just in unit-test isolation. **Wiki gains test-only routes** under `/test/*` (gated by `WIKI_INTEGRATION_TEST=1`, mounted before CSRF/staticServe so test POSTs don't have to round-trip a token cookie) covering cache get/set/del, queue enqueue/size, mail send, object-store put/get, http-client fetch, log-stream emit, mtls-ca issue, ntp query, dns lookup, ssrf classify+check, plus `/test/diagnostic` that surfaces the active backend posture (network snapshot, queue backends, log sinks, mtls algorithm). **External-integration two-gate rule** — when a release diff touches a primitive that talks to an external service (`lib/redis-client.js`, `lib/queue-redis.js`, `lib/mail.js`, `lib/network-dns.js`, `lib/object-store/*`, `lib/log-stream*.js`, `lib/external-db.js`, `lib/cluster-*.js`, `lib/mtls-ca.js`, `lib/ssrf-guard.js`, `lib/http-client.js`, `lib/ntp-check.js`, `lib/cache.js`, `lib/webhook.js`), operators MUST run BOTH `scripts/test-integration.js` (per-primitive against real backends) AND `scripts/test-wiki-integration.js` (wiki app exercising the same backends end-to-end) before pushing. Documented in CONTRIBUTING.md's pre-push gate list and CLAUDE.md's release workflow as step 4a. The smoke + wiki-e2e gates above stay PURE (no docker dependency, runs in CI / on a developer laptop / inside prepack-guard); the two-gate is operator-run, opt-in, and surfaces bugs that mocks miss — fire-and-forget races, shutdown drains, TLS pinning, real DNS resolution, real protocol handshakes. **Framework fixes surfaced by the new gate**: `b.mtlsCa.create` now auto-creates `opts.dataDir` with `mode: 0o700` if it doesn't exist (matches `b.logStream`'s local sink, `b.backup`, `b.restoreBundle` — without it the first `initCA()` call hit `ENOENT` writing `ca.key.tmp`); `b.logStream` webhook-sink `close()` now waits for the in-flight `_flush()` before draining the buffer (the v0.6.28 drain fix only tracked emit-time wrapper promises, not the actual HTTP POST in flight; a record arriving mid-flush would buffer + the emit-time `_flush` early-returned on `if (inFlight) return`, and shutdown would then strand it). `b.queue.bootFromEnv()` is now wired in the wiki app's `build-app.js` unconditionally so the wiki picks up `BLAMEJS_QUEUE_PROTOCOL=redis` from env without code changes (was previously a documented-but-commented call site). **Test architecture rule (extends the v0.6.28 rule)** — live tests for the framework's primitives go under `test/integration/`; live tests for the wiki app exercising the framework end-to-end go under `examples/wiki/test/integration.js`. Smoke (`test/smoke.js`) and the existing wiki e2e (`examples/wiki/test/e2e.js`) stay pure. Smoke / wiki-e2e green; per-primitive integration suite green; wiki integration green. Eslint pin alignment + shellcheck added to the documented gate list (carry-over from v0.6.29).
package/README.md CHANGED
@@ -47,7 +47,7 @@ The framework bundles the surface a typical Node app reaches for. Every primitiv
47
47
  - **HTTP** — router with schema-validated routes + OpenAPI publication; full middleware stack (CSRF, CORS, rate-limit, security headers, CSP nonce, body parser, compression, SSE, request log, request-time DB role binding via `b.middleware.dbRoleFor`, in-process CIDR fence via `b.middleware.networkAllowlist`) wired by `createApp`; HTTP/1.1 + HTTP/2 outbound client with SSRF gate (cloud-metadata IPs hard-denied unconditionally; private / loopback / link-local overridable per call), scheme + userinfo + per-host (wildcard / per-method) destination allowlist, redirects, multipart, interceptors, progress, encrypted cookie jar (`b.httpClient`, `b.ssrfGuard`, `b.safeUrl`); operator-tunable network configurability — env-driven NTP / NTS (RFC 8915 authenticated time), IPv4-or-IPv6 NTP servers, DNS with IPv6 / DoH / DoT (private-CA trust pinning via `opts.ca`) / cache / lookup timeout, outbound HTTP proxy (`HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`), runtime DPI trust-store CA additions, application-level heartbeats, TCP socket defaults (`b.network`).
48
48
  - **Defensive parsers** — `b.safeJson`, `b.safeBuffer`, `b.safeSql`, `b.safeSchema`, `b.parsers` (XML / TOML / YAML / .env), `b.config` (schema-validated env), `b.fileType` magic-byte content classification with deny-on-upload categories (image / document / archive / executable / etc.).
49
49
  - **Communication** — WebSockets with channel/room fan-out across cluster replicas (`b.websocket`, `b.websocketChannels`); mail with multipart + attachments + DKIM + calendar invites + bounce intake (`b.mail`, `b.mailBounce`); generic notification dispatcher with operator-supplied transports (`b.notify`).
50
- - **Observability** — tamper-evident audit chain with SLH-DSA-signed checkpoints, metrics, tracing (OTel pass-through when wired), PII redaction, log-stream sinks (local file rotation, generic webhook, OTLP/HTTP-JSON to an OTel collector, AWS CloudWatch Logs via SigV4), OTLP/HTTP-JSON exporter for traces + metrics (`b.audit`, `b.metrics`, `b.tracing`, `b.redact`, `b.logStream`, `b.otelExport`); operator-callable boot-time security policy assertions (`b.security.assertProduction`) and tamper-evident config-baseline drift detection signed with the audit-signing key (`b.configDrift`).
50
+ - **Observability** — tamper-evident audit chain with SLH-DSA-signed checkpoints, metrics, tracing (OTel pass-through when wired), PII redaction, log-stream sinks (local file rotation, generic webhook, OTLP/HTTP-JSON to an OTel collector, AWS CloudWatch Logs via SigV4 with optional autoCreate, RFC 5424 syslog over UDP/TCP/TLS), OTLP/HTTP-JSON exporter for traces + metrics (`b.audit`, `b.metrics`, `b.tracing`, `b.redact`, `b.logStream`, `b.otelExport`); operator-callable boot-time security policy assertions (`b.security.assertProduction`) and tamper-evident config-baseline drift detection signed with the audit-signing key (`b.configDrift`).
51
51
  - **i18n** — CLDR plural rules, Accept-Language negotiation, Intl formatters, RTL (`b.i18n`).
52
52
  - **Format helpers** — RFC 4180 CSV with Excel formula-injection prevention (`b.csv`), RFC 9562 UUID v4 + v7 (`b.uuid`), URL-safe slugs (`b.slug`), TZ-aware datetime (`b.time`), ZIP creation (`b.archive`), HMAC-signed cursor pagination (`b.pagination`), HTML form rendering + validation + CSRF (`b.forms`).
53
53
  - **Production** — cluster leader election with fenced leases over Postgres/SQLite (`b.cluster`); cron + interval scheduler that runs exactly-once globally (`b.scheduler`); retry with full-jitter backoff + circuit breaker (`b.retry`); graceful shutdown (`b.appShutdown`); NTP boot check (`b.ntpCheck`); end-to-end-encrypted backup bundles with pre-flush fail-closed mode (`b.backup`); restore with pulled-bundle footprint preflight (`b.restore`); GDPR / PCI / HIPAA-shaped retention rules with multi-stage warn → archive → erase, legal-hold exemptions, dry-run preview, cross-table cascade (`b.retention`).
@@ -87,12 +87,13 @@ function _serializeBatch(events, cfg, sequenceToken) {
87
87
  return Buffer.from(JSON.stringify(body), "utf8");
88
88
  }
89
89
 
90
- function _signedHeaders(cfg, body) {
90
+ function _signedHeaders(cfg, body, target) {
91
+ target = target || "Logs_20140328.PutLogEvents";
91
92
  var url = _resolveEndpoint(cfg);
92
93
  var payloadHash = nodeCrypto.createHash("sha256").update(body).digest("hex");
93
94
  var unsigned = {
94
95
  "Content-Type": "application/x-amz-json-1.1",
95
- "X-Amz-Target": "Logs_20140328.PutLogEvents",
96
+ "X-Amz-Target": target,
96
97
  };
97
98
  var signed = sigv4.signRequest({
98
99
  method: "POST",
@@ -108,6 +109,41 @@ function _signedHeaders(cfg, body) {
108
109
  return signed.headers;
109
110
  }
110
111
 
112
+ // CloudWatch CreateLogGroup / CreateLogStream wrappers. Operator opts in
113
+ // via cfg.autoCreate = true; default stays "operator pre-creates via
114
+ // Terraform / CDK / aws cli" so the framework doesn't paper over an
115
+ // IAM-misconfigured deployment with surprising side effects.
116
+ async function _ensureLogGroupAndStream(cfg) {
117
+ // CreateLogGroup — idempotent on the wire (we treat
118
+ // ResourceAlreadyExistsException as success).
119
+ var groupBody = Buffer.from(JSON.stringify({ logGroupName: cfg.logGroupName }), "utf8");
120
+ var groupHeaders = _signedHeaders(cfg, groupBody, "Logs_20140328.CreateLogGroup");
121
+ try {
122
+ await _post(cfg, groupBody, groupHeaders);
123
+ } catch (e) {
124
+ var msg = (e && e.message) || "";
125
+ if (!/ResourceAlreadyExistsException/.test(msg)) {
126
+ throw _err("AUTOCREATE_FAILED",
127
+ "log-stream cloudwatch autoCreate: CreateLogGroup failed: " + msg);
128
+ }
129
+ }
130
+ // CreateLogStream — same idempotency treatment.
131
+ var streamBody = Buffer.from(JSON.stringify({
132
+ logGroupName: cfg.logGroupName,
133
+ logStreamName: cfg.logStreamName,
134
+ }), "utf8");
135
+ var streamHeaders = _signedHeaders(cfg, streamBody, "Logs_20140328.CreateLogStream");
136
+ try {
137
+ await _post(cfg, streamBody, streamHeaders);
138
+ } catch (e) {
139
+ var msg2 = (e && e.message) || "";
140
+ if (!/ResourceAlreadyExistsException/.test(msg2)) {
141
+ throw _err("AUTOCREATE_FAILED",
142
+ "log-stream cloudwatch autoCreate: CreateLogStream failed: " + msg2);
143
+ }
144
+ }
145
+ }
146
+
111
147
  function _post(cfg, body, headers) {
112
148
  return httpClient.request({
113
149
  method: "POST",
@@ -144,9 +180,11 @@ function create(config) {
144
180
  }
145
181
  if (!config.logGroupName || !config.logStreamName) {
146
182
  throw _err("BAD_OPT",
147
- "log-stream cloudwatch requires { logGroupName, logStreamName } " +
148
- "(operator pre-creates both via aws logs create-log-group / create-log-stream " +
149
- "or CDK / Terraform; the framework does NOT auto-create)");
183
+ "log-stream cloudwatch requires { logGroupName, logStreamName }. " +
184
+ "Operator pre-creates both via aws / CDK / Terraform by default; " +
185
+ "pass { autoCreate: true } to have the framework issue " +
186
+ "CreateLogGroup + CreateLogStream on first emit (idempotent — " +
187
+ "ResourceAlreadyExistsException treated as success).");
150
188
  }
151
189
  var cfg = Object.assign({}, DEFAULTS, config);
152
190
  var onDrop = typeof cfg.onDrop === "function" ? cfg.onDrop : null;
@@ -186,11 +224,32 @@ function create(config) {
186
224
  return batch;
187
225
  }
188
226
 
227
+ // autoCreate handshake — runs once per process before the first
228
+ // PutLogEvents. Promise cached so concurrent emits don't fire
229
+ // duplicate CreateLogGroup / CreateLogStream calls.
230
+ var autoCreatePromise = null;
231
+ function _ensureAutoCreated() {
232
+ if (!cfg.autoCreate) return Promise.resolve();
233
+ if (!autoCreatePromise) autoCreatePromise = _ensureLogGroupAndStream(cfg);
234
+ return autoCreatePromise;
235
+ }
236
+
189
237
  async function _flush() {
190
238
  if (inFlight) return;
191
239
  if (buffer.length === 0) return;
192
240
  inFlight = true;
193
241
  try {
242
+ try { await _ensureAutoCreated(); }
243
+ catch (acErr) {
244
+ // autoCreate failure is permanent — every subsequent batch
245
+ // would hit the same error. Drop the queue with the
246
+ // operator-supplied onDrop callback so they see exactly which
247
+ // events were lost AND why, then bail.
248
+ var allBuffered = buffer.splice(0, buffer.length);
249
+ dropCount += allBuffered.length;
250
+ _emitDrop("autocreate-failed", allBuffered, acErr);
251
+ return;
252
+ }
194
253
  while (buffer.length > 0 && !closed) {
195
254
  var batch = _takeBatch();
196
255
  if (batch.length === 0) break;
@@ -0,0 +1,297 @@
1
+ "use strict";
2
+ /**
3
+ * Syslog log-stream sink — RFC 5424 framing over UDP / TCP / TLS.
4
+ *
5
+ * Wire format (RFC 5424 §6):
6
+ * <PRI>VERSION SP TIMESTAMP SP HOSTNAME SP APP-NAME SP PROCID SP MSGID SP STRUCTURED-DATA SP MSG
7
+ *
8
+ * PRI = (facility * 8) + severity
9
+ * facility (default 16 = local0; 1 = user — operators commonly pick
10
+ * local0..local7 for app-emitted records)
11
+ * severity is mapped from the framework's level field:
12
+ * debug → 7, info → 6, warn → 4, error → 3
13
+ *
14
+ * Transport:
15
+ * udp — single datagram per record (no framing)
16
+ * tcp — octet-counting framing (RFC 6587 §3.4.1):
17
+ * "<length> <message>" with a SPACE between
18
+ * length and the rfc5424 message bytes
19
+ * tls — same octet-counting framing on a TLS socket
20
+ * (RFC 5425). Standard port 6514.
21
+ *
22
+ * Defaults match RFC 3164/5424 conventions: appName = "blamejs",
23
+ * facility = local0 (16), hostname = os.hostname(), structuredData = "-".
24
+ *
25
+ * Flow control:
26
+ * The TCP / TLS variants buffer pending writes during socket
27
+ * reconnect and replay them on the new connection. UDP is best-effort
28
+ * (datagrams that race a closed socket are dropped to onDrop).
29
+ */
30
+ var dgram = require("dgram");
31
+ var net = require("net");
32
+ var os = require("os");
33
+ var tls = require("tls");
34
+ var C = require("./constants");
35
+ var { LogStreamError } = require("./framework-error");
36
+
37
+ var _err = LogStreamError.factory;
38
+
39
+ var DEFAULT_FACILITY = 16; // local0
40
+ var DEFAULT_APP_NAME = "blamejs";
41
+ var DEFAULT_PROC_ID = String(process.pid);
42
+ var DEFAULT_MSG_ID = "-";
43
+ var DEFAULT_STRUCT_DATA = "-";
44
+ var TCP_DEFAULT_PORT = 514;
45
+ var TLS_DEFAULT_PORT = 6514;
46
+ var UDP_DEFAULT_PORT = 514;
47
+ var DEFAULT_TIMEOUT_MS = C.TIME.seconds(10);
48
+ var DEFAULT_RECONNECT_BASE_MS = 250;
49
+ var DEFAULT_RECONNECT_MAX_MS = 30000;
50
+ var DEFAULT_BUFFER_LIMIT = 10000;
51
+
52
+ // RFC 5424 severity codes from the framework's level names.
53
+ var LEVEL_TO_SEVERITY = {
54
+ debug: 7,
55
+ info: 6,
56
+ warn: 4,
57
+ error: 3,
58
+ };
59
+
60
+ function _toRfc3339(tsMs) {
61
+ return new Date(tsMs).toISOString();
62
+ }
63
+
64
+ function _formatRfc5424(record, cfg) {
65
+ var severity = LEVEL_TO_SEVERITY[record.level] != null
66
+ ? LEVEL_TO_SEVERITY[record.level] : 6;
67
+ var pri = (cfg.facility * 8) + severity;
68
+ var ts = _toRfc3339(record.ts || Date.now());
69
+ // Body — JSON-encode meta + message together so the structured
70
+ // payload survives the wire as a single MSG token. Operators with
71
+ // their own RFC 5424 STRUCTURED-DATA producers pass cfg.structuredData
72
+ // (string) to override the default "-".
73
+ var body = record.message || "";
74
+ if (record.meta && Object.keys(record.meta).length > 0) {
75
+ try { body += " " + JSON.stringify(record.meta); }
76
+ catch (_e) { /* best-effort */ }
77
+ }
78
+ return "<" + pri + ">1 " + ts + " " + cfg.hostname + " " +
79
+ cfg.appName + " " + cfg.procId + " " + cfg.msgId + " " +
80
+ (cfg.structuredData || "-") + " " + body;
81
+ }
82
+
83
+ function create(config) {
84
+ if (!config) throw _err("BAD_OPT", "log-stream syslog requires { url } (e.g. udp://host:514, tcp://host:514, tls://host:6514)");
85
+ var url = config.url;
86
+ if (typeof url !== "string" || url.length === 0) {
87
+ throw _err("BAD_OPT", "log-stream syslog requires { url } (string)");
88
+ }
89
+ // Parse URL — accept udp://, tcp://, tls://. safeUrl rejects http://
90
+ // by default; allow these explicit transports.
91
+ var parsed;
92
+ try {
93
+ parsed = new URL(url);
94
+ } catch (e) {
95
+ throw _err("BAD_URL", "log-stream syslog: bad url '" + url + "': " +
96
+ ((e && e.message) || String(e)));
97
+ }
98
+ var transport = parsed.protocol.replace(/:$/, "").toLowerCase();
99
+ if (transport !== "udp" && transport !== "tcp" && transport !== "tls") {
100
+ throw _err("BAD_URL",
101
+ "log-stream syslog: protocol must be udp / tcp / tls, got " +
102
+ JSON.stringify(parsed.protocol));
103
+ }
104
+ var defaultPort = transport === "tls" ? TLS_DEFAULT_PORT
105
+ : transport === "tcp" ? TCP_DEFAULT_PORT
106
+ : UDP_DEFAULT_PORT;
107
+ var host = parsed.hostname;
108
+ var port = parsed.port ? parseInt(parsed.port, 10) : defaultPort;
109
+
110
+ var cfg = {
111
+ transport: transport,
112
+ host: host,
113
+ port: port,
114
+ facility: (typeof config.facility === "number" && config.facility >= 0 && config.facility <= 23)
115
+ ? Math.floor(config.facility) : DEFAULT_FACILITY,
116
+ appName: config.appName || DEFAULT_APP_NAME,
117
+ procId: config.procId || DEFAULT_PROC_ID,
118
+ msgId: config.msgId || DEFAULT_MSG_ID,
119
+ hostname: config.hostname || os.hostname(),
120
+ structuredData: config.structuredData || DEFAULT_STRUCT_DATA,
121
+ timeoutMs: config.timeoutMs || DEFAULT_TIMEOUT_MS,
122
+ bufferLimit: config.bufferLimit || DEFAULT_BUFFER_LIMIT,
123
+ reconnectBaseMs: config.reconnectBaseMs || DEFAULT_RECONNECT_BASE_MS,
124
+ reconnectMaxMs: config.reconnectMaxMs || DEFAULT_RECONNECT_MAX_MS,
125
+ ca: config.ca || null,
126
+ rejectUnauthorized: config.rejectUnauthorized !== false,
127
+ servername: config.servername || null,
128
+ };
129
+ // safeUrl-style guard for the URL — reject userinfo (no auth in
130
+ // syslog wire) so a stray "syslog://user:pw@host" doesn't silently
131
+ // get through.
132
+ if (parsed.username || parsed.password) {
133
+ throw _err("BAD_URL",
134
+ "log-stream syslog: url must not contain userinfo");
135
+ }
136
+ // Track the operator's onDrop so dropped events surface.
137
+ var onDrop = typeof config.onDrop === "function" ? config.onDrop : null;
138
+ function _emitDrop(reason, batch, err) {
139
+ if (!onDrop) return;
140
+ try { onDrop({ reason: reason, batch: batch, error: err || null }); }
141
+ catch (_e) {}
142
+ }
143
+
144
+ // ---- UDP transport ----
145
+ if (transport === "udp") {
146
+ var udpFamily = host.indexOf(":") !== -1 ? "udp6" : "udp4";
147
+ var udpSock = dgram.createSocket(udpFamily);
148
+ udpSock.unref && udpSock.unref();
149
+ var udpClosed = false;
150
+ udpSock.on("error", function () { /* non-fatal — datagrams race */ });
151
+
152
+ return {
153
+ protocol: "syslog-udp",
154
+ emit: function (record) {
155
+ if (udpClosed) {
156
+ _emitDrop("sink-closed", [record], null);
157
+ return Promise.resolve({ accepted: false, reason: "closed" });
158
+ }
159
+ var msg = _formatRfc5424(record, cfg);
160
+ var buf = Buffer.from(msg, "utf8");
161
+ return new Promise(function (resolve) {
162
+ udpSock.send(buf, 0, buf.length, cfg.port, cfg.host, function (err) {
163
+ if (err) _emitDrop("udp-send-error", [record], err);
164
+ resolve({ accepted: !err, queued: 0 });
165
+ });
166
+ });
167
+ },
168
+ close: function () {
169
+ udpClosed = true;
170
+ try { udpSock.close(); } catch (_e) {}
171
+ return Promise.resolve();
172
+ },
173
+ };
174
+ }
175
+
176
+ // ---- TCP / TLS transport — octet-counting framing (RFC 6587) ----
177
+ // Buffer outgoing records during socket-down windows; replay on
178
+ // reconnect. Operator opts: bufferLimit caps the queue; oldest
179
+ // dropped first with the onDrop "overflow" reason.
180
+ var sock = null;
181
+ var sockReady = false;
182
+ var connecting = false;
183
+ var queue = [];
184
+ var closed = false;
185
+ var reconnectAttempt = 0;
186
+
187
+ function _writeFramed(record) {
188
+ var msg = _formatRfc5424(record, cfg);
189
+ var msgBuf = Buffer.from(msg, "utf8");
190
+ var prefix = Buffer.from(msgBuf.length + " ", "utf8");
191
+ sock.write(Buffer.concat([prefix, msgBuf]));
192
+ }
193
+
194
+ function _connect() {
195
+ if (closed || connecting) return;
196
+ connecting = true;
197
+ sockReady = false;
198
+ var connectOpts = { host: cfg.host, port: cfg.port };
199
+ var onConnect = function () {
200
+ connecting = false;
201
+ sockReady = true;
202
+ reconnectAttempt = 0;
203
+ // Drain queue in arrival order on (re)connect.
204
+ while (queue.length > 0 && sockReady) {
205
+ try { _writeFramed(queue.shift()); }
206
+ catch (e) { _emitDrop("write-error", [/* drained */], e); break; }
207
+ }
208
+ };
209
+ if (transport === "tls") {
210
+ var tlsOpts = Object.assign({}, connectOpts, {
211
+ rejectUnauthorized: cfg.rejectUnauthorized,
212
+ minVersion: "TLSv1.3",
213
+ });
214
+ if (cfg.ca) tlsOpts.ca = cfg.ca;
215
+ if (cfg.servername) tlsOpts.servername = cfg.servername;
216
+ sock = tls.connect(tlsOpts, onConnect);
217
+ } else {
218
+ sock = net.connect(connectOpts, onConnect);
219
+ }
220
+ sock.unref && sock.unref();
221
+ sock.on("error", function () { /* defer to 'close' for reconnect */ });
222
+ sock.on("close", function () {
223
+ sockReady = false;
224
+ connecting = false;
225
+ try { sock.destroy(); } catch (_e) {}
226
+ sock = null;
227
+ if (closed) return;
228
+ reconnectAttempt += 1;
229
+ var delay = Math.min(cfg.reconnectMaxMs,
230
+ cfg.reconnectBaseMs * Math.pow(2, reconnectAttempt - 1));
231
+ var t = setTimeout(_connect, delay);
232
+ t.unref && t.unref();
233
+ });
234
+ }
235
+ _connect();
236
+
237
+ return {
238
+ protocol: "syslog-" + transport,
239
+ emit: function (record) {
240
+ if (closed) {
241
+ _emitDrop("sink-closed", [record], null);
242
+ return Promise.resolve({ accepted: false, reason: "closed" });
243
+ }
244
+ if (sockReady) {
245
+ try { _writeFramed(record); }
246
+ catch (e) {
247
+ _emitDrop("write-error", [record], e);
248
+ return Promise.resolve({ accepted: false, reason: "write-error" });
249
+ }
250
+ return Promise.resolve({ accepted: true, queued: 0 });
251
+ }
252
+ // Socket not yet up — buffer with overflow-by-oldest semantics.
253
+ if (queue.length >= cfg.bufferLimit) {
254
+ var dropped = queue.shift();
255
+ _emitDrop("overflow", [dropped], null);
256
+ }
257
+ queue.push(record);
258
+ return Promise.resolve({ accepted: true, queued: queue.length });
259
+ },
260
+ close: function () {
261
+ // Give an in-flight (re)connect a brief window to complete and
262
+ // drain the buffer. Without this, records emitted just before
263
+ // shutdown race the slower TLS handshake and surface as
264
+ // "sink-closed" drops even though the framework had a viable
265
+ // connection in progress.
266
+ var DRAIN_TIMEOUT_MS = 3000;
267
+ var started = Date.now();
268
+ return new Promise(function (resolve) {
269
+ function _finish() {
270
+ closed = true;
271
+ var pending = queue.splice(0, queue.length);
272
+ if (pending.length > 0) _emitDrop("sink-closed", pending, null);
273
+ try { if (sock) sock.end(); } catch (_e) {}
274
+ try { if (sock) sock.destroy(); } catch (_e) {}
275
+ sock = null;
276
+ resolve();
277
+ }
278
+ function _tick() {
279
+ if (queue.length === 0 || Date.now() - started > DRAIN_TIMEOUT_MS) {
280
+ return _finish();
281
+ }
282
+ // Keep the timer ref'd — close() is being awaited; if we
283
+ // unref the drain-tick timer the event loop can exit between
284
+ // ticks (UDP/TCP socket are also unref'd) and the close
285
+ // promise pends forever silently.
286
+ setTimeout(_tick, 25);
287
+ }
288
+ _tick();
289
+ });
290
+ },
291
+ // Test-only: returns the in-flight queue size for assertions.
292
+ _queueSizeForTest: function () { return queue.length; },
293
+ _formatRfc5424ForTest: function (rec) { return _formatRfc5424(rec, cfg); },
294
+ };
295
+ }
296
+
297
+ module.exports = { create: create };
package/lib/log-stream.js CHANGED
@@ -15,15 +15,15 @@
15
15
  * (k8s, cloud) get standard log forwarding without a
16
16
  * vendor-specific adapter.
17
17
  * cloudwatch — AWS CloudWatch Logs (PutLogEvents) over HTTPS with
18
- * SigV4. Operator pre-creates the log group + log stream;
19
- * the framework signs and POSTs batches respecting the
20
- * 10K-event / 1 MiB / 256 KiB-per-event AWS caps. Honors
21
- * IAM role + STS session tokens.
22
- *
23
- * Adapters listed as deferred and surfacing a clear error when
24
- * selected:
25
- *
26
- * syslog RFC 5424 syslog over TLS
18
+ * SigV4. Pass { autoCreate: true } to have the framework
19
+ * issue CreateLogGroup + CreateLogStream on first emit
20
+ * (idempotent ResourceAlreadyExistsException treated as
21
+ * success). Honors IAM role + STS session tokens. Respects
22
+ * the 10K-event / 1 MiB / 256 KiB-per-event AWS caps.
23
+ * syslog — RFC 5424 with octet-counting framing over UDP / TCP /
24
+ * TLS. UDP is best-effort; TCP/TLS buffer during socket
25
+ * reconnect and replay on connect. Default ports 514
26
+ * (UDP/TCP) and 6514 (TLS).
27
27
  *
28
28
  * Every emit goes through lib/redact.js BEFORE any sink sees it. PHI/PCI
29
29
  * never reaches operational logs even on a misconfigured field name —
@@ -50,6 +50,7 @@ var localProto = require("./log-stream-local");
50
50
  var webhookProto = require("./log-stream-webhook");
51
51
  var otlpProto = require("./log-stream-otlp");
52
52
  var cloudwatchProto = require("./log-stream-cloudwatch");
53
+ var syslogProto = require("./log-stream-syslog");
53
54
  var redactor = require("./redact");
54
55
  var lazyRequire = require("./lazy-require");
55
56
  var protocolDispatcher = require("./protocol-dispatcher");
@@ -63,10 +64,9 @@ var dispatcher = protocolDispatcher.create({
63
64
  "webhook": webhookProto,
64
65
  "otlp": otlpProto,
65
66
  "cloudwatch": cloudwatchProto,
67
+ "syslog": syslogProto,
66
68
  },
67
- deferred: {
68
- "syslog": { description: "RFC 5424 syslog over TLS" },
69
- },
69
+ deferred: {},
70
70
  fallbackProtocol: "local",
71
71
  });
72
72
 
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * Three framework modules ship a "pick a backend by protocol name" surface:
7
7
  * - lib/queue.js (local, deferred: redis/sqs/amqp/nats)
8
- * - lib/log-stream.js (local + webhook, deferred: syslog/otlp/cloudwatch)
8
+ * - lib/log-stream.js (local + webhook + otlp + cloudwatch + syslog)
9
9
  * - lib/object-store/index.js (local + http-put + sigv4 + gcs + azure-blob)
10
10
  *
11
11
  * Each previously copied a ~30-line dispatch block: validate config has a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/core",
3
- "version": "0.6.32",
3
+ "version": "0.6.33",
4
4
  "description": "The Node framework that owns its stack.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:bf737d55-37d5-49a4-95fb-c1149d627468",
5
+ "serialNumber": "urn:uuid:c1b1caea-6dd0-463e-8c6d-2490abcb0c2e",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-05-02T19:10:22.247Z",
8
+ "timestamp": "2026-05-02T19:44:37.593Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/core@0.6.32",
22
+ "bom-ref": "@blamejs/core@0.6.33",
23
23
  "type": "library",
24
24
  "name": "blamejs",
25
- "version": "0.6.32",
25
+ "version": "0.6.33",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "The Node framework that owns its stack.",
29
- "purl": "pkg:npm/%40blamejs/core@0.6.32",
29
+ "purl": "pkg:npm/%40blamejs/core@0.6.33",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/core@0.6.32",
57
+ "ref": "@blamejs/core@0.6.33",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]