@tangen/logging 0.0.0-stage → 0.0.24
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/package.json +32 -4
- package/src/index.ts +151 -0
- package/src/redact.ts +97 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangen/logging",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.24",
|
|
4
|
+
"description": "Structured logging with redaction, used across the Tangen platform. Internal to the platform",
|
|
5
|
+
"homepage": "https://github.com/raghunathj/tangen#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/raghunathj/tangen/issues"
|
|
8
|
+
},
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/raghunathj/tangen.git",
|
|
13
|
+
"directory": "packages/logging"
|
|
14
|
+
},
|
|
15
|
+
"main": "./src/index.ts",
|
|
16
|
+
"types": "./src/index.ts",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc --noEmit",
|
|
19
|
+
"test": "bun test"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@logtape/logtape": "^0.9.0",
|
|
23
|
+
"@tangen/types": "^0.2.0"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"!**/__tests__/**",
|
|
28
|
+
"!**/*.test.ts"
|
|
29
|
+
],
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public",
|
|
32
|
+
"main": "./src/index.ts"
|
|
33
|
+
}
|
|
34
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: index.ts
|
|
3
|
+
* Purpose: Configures and exposes the Tangen structured logger built on LogTape, switching between pretty console output in dev and JSON-lines for production log aggregators.
|
|
4
|
+
*
|
|
5
|
+
* Author: Raghunath J
|
|
6
|
+
* License: MIT
|
|
7
|
+
*
|
|
8
|
+
* Dependencies/Notes: Uses @logtape/logtape for sink configuration; re-exports TangenLogger from @tangen/types.
|
|
9
|
+
* Every message and property passes through redact.ts before a sink
|
|
10
|
+
* sees it (credential keys, bearer tokens, Tangen keys, JWTs,
|
|
11
|
+
* connection-string passwords), and the installed log context (the
|
|
12
|
+
* request id, from the API's Gateway) rides every record.
|
|
13
|
+
*/
|
|
14
|
+
import {
|
|
15
|
+
configureSync,
|
|
16
|
+
resetSync,
|
|
17
|
+
getLogger as logtapeGetLogger,
|
|
18
|
+
getConsoleSink,
|
|
19
|
+
} from '@logtape/logtape'
|
|
20
|
+
import type { TangenLogger } from '@tangen/types'
|
|
21
|
+
|
|
22
|
+
export type { TangenLogger }
|
|
23
|
+
export { redactMeta, redactString, redactValue, isSecretKey, REDACTED } from './redact'
|
|
24
|
+
import { redactMeta, redactString } from './redact'
|
|
25
|
+
|
|
26
|
+
/** Properties every record carries while a context is open (the API installs the request id). */
|
|
27
|
+
type LogContextProvider = () => Record<string, unknown> | undefined
|
|
28
|
+
|
|
29
|
+
let _context: LogContextProvider | null = null
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Installs the provider whose properties ride every record: the API's Gateway
|
|
33
|
+
* hands the current request id here, so any log line written while a request
|
|
34
|
+
* runs is correlatable with the response the client saw. Idempotent by
|
|
35
|
+
* replacement; `null` removes it.
|
|
36
|
+
*/
|
|
37
|
+
export function setLogContext(provider: LogContextProvider | null): void {
|
|
38
|
+
_context = provider
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The properties the installed context would add to a record right now. */
|
|
42
|
+
export function getLogContext(): Record<string, unknown> {
|
|
43
|
+
return _context ? (_context() ?? {}) : {}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function withContext(meta: Record<string, unknown> | undefined): Record<string, unknown> {
|
|
47
|
+
return { ...getLogContext(), ...redactMeta(meta) }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type LogLevel = 'debug' | 'info' | 'warning' | 'error' | 'fatal'
|
|
51
|
+
|
|
52
|
+
let _configured = false
|
|
53
|
+
|
|
54
|
+
/** Reset internal state — only for use in tests (via resetLogging). */
|
|
55
|
+
function _reset() { _configured = false }
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Call once at server startup. Dev gets a pretty coloured sink; prod gets
|
|
59
|
+
* JSON-lines to stdout parseable by Datadog, Grafana Loki, etc.
|
|
60
|
+
*/
|
|
61
|
+
export function configureTangenLogging(options?: { level?: LogLevel }): void {
|
|
62
|
+
if (_configured) return
|
|
63
|
+
_configured = true
|
|
64
|
+
|
|
65
|
+
const isProd = process.env.NODE_ENV === 'production'
|
|
66
|
+
// TANGEN_LOG_LEVEL turns a chatty development boot down (`warn`) or a
|
|
67
|
+
// production process up (`debug`) without touching code.
|
|
68
|
+
const fromEnv = (process.env.TANGEN_LOG_LEVEL ?? '').trim().toLowerCase()
|
|
69
|
+
const envLevel = (['debug', 'info', 'warning', 'error', 'fatal'] as const).find((l) => l === fromEnv || (l === 'warning' && fromEnv === 'warn'))
|
|
70
|
+
const level: LogLevel = options?.level ?? envLevel ?? (isProd ? 'info' : 'debug')
|
|
71
|
+
|
|
72
|
+
if (isProd) {
|
|
73
|
+
const jsonSink = (record: any) => {
|
|
74
|
+
process.stdout.write(
|
|
75
|
+
JSON.stringify({
|
|
76
|
+
level: record.level,
|
|
77
|
+
category: (record.category as string[]).join('.'),
|
|
78
|
+
message: record.rawMessage,
|
|
79
|
+
timestamp: new Date(record.timestamp as number).toISOString(),
|
|
80
|
+
...record.properties,
|
|
81
|
+
}) + '\n',
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
configureSync({
|
|
86
|
+
sinks: { json: jsonSink },
|
|
87
|
+
loggers: [
|
|
88
|
+
{ category: ['logtape', 'meta'], lowestLevel: 'warning', sinks: [] },
|
|
89
|
+
{ category: ['tangen'], lowestLevel: level, sinks: ['json'] },
|
|
90
|
+
],
|
|
91
|
+
})
|
|
92
|
+
} else {
|
|
93
|
+
// Colored dev output: WRN amber, ERR/FTL red, INF green, DBG dim — so
|
|
94
|
+
// problems stand out in the tangen dev stream instead of plain white.
|
|
95
|
+
const COLORS: Record<string, string> = { debug: '2', info: '32;1', warning: '33;1', error: '31;1', fatal: '41;97;1' }
|
|
96
|
+
const TAGS: Record<string, string> = { debug: 'DBG', info: 'INF', warning: 'WRN', error: 'ERR', fatal: 'FTL' }
|
|
97
|
+
const tty = process.stdout.isTTY && !process.env.NO_COLOR
|
|
98
|
+
const paint = (code: string, text: string) => (tty ? `\x1b[${code}m${text}\x1b[0m` : text)
|
|
99
|
+
const coloredFormatter = (record: { level: string; category: readonly string[]; message: readonly unknown[]; timestamp: number }) => {
|
|
100
|
+
const ts = paint('2', new Date(record.timestamp).toISOString().replace('T', ' ').slice(0, 23))
|
|
101
|
+
const lvl = paint(COLORS[record.level] ?? '0', TAGS[record.level] ?? record.level.toUpperCase().slice(0, 3))
|
|
102
|
+
const cat = paint('1', record.category.join(paint('2', '·')))
|
|
103
|
+
const msg = record.message.map((m) => (typeof m === 'string' ? m : JSON.stringify(m))).join('')
|
|
104
|
+
const line = `${ts} ${lvl} ${cat} ${record.level === 'error' || record.level === 'fatal' ? paint('31', msg) : record.level === 'warning' ? paint('33', msg) : msg}`
|
|
105
|
+
return line + '\n'
|
|
106
|
+
}
|
|
107
|
+
configureSync({
|
|
108
|
+
sinks: { console: getConsoleSink({ formatter: coloredFormatter as never }) },
|
|
109
|
+
loggers: [
|
|
110
|
+
{ category: ['logtape', 'meta'], lowestLevel: 'warning', sinks: [] },
|
|
111
|
+
{ category: ['tangen'], lowestLevel: level, sinks: ['console'] },
|
|
112
|
+
],
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Get a structured logger for the given category path.
|
|
119
|
+
* Category convention: ['tangen', 'api', 'hooks'] etc.
|
|
120
|
+
*/
|
|
121
|
+
export function getLogger(category: string[]): TangenLogger {
|
|
122
|
+
const inner = logtapeGetLogger(category)
|
|
123
|
+
return {
|
|
124
|
+
debug(message, meta?) {
|
|
125
|
+
inner.debug(redactString(message), withContext(meta))
|
|
126
|
+
},
|
|
127
|
+
info(message, meta?) {
|
|
128
|
+
inner.info(redactString(message), withContext(meta))
|
|
129
|
+
},
|
|
130
|
+
warn(message, meta?) {
|
|
131
|
+
inner.warn(redactString(message), withContext(meta))
|
|
132
|
+
},
|
|
133
|
+
error(message, errorOrMeta?) {
|
|
134
|
+
if (errorOrMeta instanceof Error) {
|
|
135
|
+
inner.error(redactString(message), withContext({
|
|
136
|
+
errorMessage: errorOrMeta.message,
|
|
137
|
+
errorStack: errorOrMeta.stack,
|
|
138
|
+
}))
|
|
139
|
+
} else {
|
|
140
|
+
inner.error(redactString(message), withContext(errorOrMeta))
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Reset all LogTape state AND the configured flag — for use in tests only. */
|
|
147
|
+
export function resetLogging(): void {
|
|
148
|
+
resetSync()
|
|
149
|
+
_reset()
|
|
150
|
+
_context = null
|
|
151
|
+
}
|
package/src/redact.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File Name: redact.ts
|
|
3
|
+
* Purpose: Keeps credentials out of log records (closure plan Phase 2,
|
|
4
|
+
* Unit 2). Every property a logger is handed, and the message and
|
|
5
|
+
* stack of every error it is handed, pass through here before a
|
|
6
|
+
* sink sees them: a key that names a secret loses its value, and a
|
|
7
|
+
* value that LOOKS like a credential (a bearer token, a Tangen key,
|
|
8
|
+
* a JWT, the password of a connection string) is replaced wherever
|
|
9
|
+
* it sits in a string.
|
|
10
|
+
*
|
|
11
|
+
* Author: Raghunath J
|
|
12
|
+
* License: MIT
|
|
13
|
+
*
|
|
14
|
+
* Dependencies/Notes: Pure. Deliberately conservative in the other direction
|
|
15
|
+
* too: identifiers (request ids, workspace ids, UUIDs) are not
|
|
16
|
+
* secrets and must survive, or the log stops being diagnosable.
|
|
17
|
+
* Depth and size are capped so a pathological object cannot turn a
|
|
18
|
+
* log line into work. The Gateway's own access-log redaction
|
|
19
|
+
* (packages/api/src/gateway/logging.ts) is an allow-list on top of
|
|
20
|
+
* this; this is the floor under every logger.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { NO_LOG } from '@tangen/types'
|
|
24
|
+
|
|
25
|
+
export const REDACTED = '[redacted]'
|
|
26
|
+
/** What a NO_LOG object becomes in a log record. */
|
|
27
|
+
export const NO_LOG_PLACEHOLDER = '[not logged]'
|
|
28
|
+
|
|
29
|
+
/** A property whose VALUE is a credential, whatever the value looks like. */
|
|
30
|
+
const SECRET_KEY = /(^|[_\-.])(authorization|cookie|cookies|set-cookie|password|passwd|secret|secrets|token|tokens|api[_-]?key|apikey|x-tangen-key|private[_-]?key|client[_-]?secret|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?key|signing[_-]?key|jwt[_-]?secret|database[_-]?url|connection[_-]?string|redis[_-]?url|credentials?)([_\-.]|$)/i
|
|
31
|
+
|
|
32
|
+
/** Is this a property name whose value must never be written down? */
|
|
33
|
+
/** A property that names an identifier or a count OF a secret, not the secret: apiKeyId, tokenCount. */
|
|
34
|
+
const IDENTIFIER_SUFFIX = /(^|_)(id|ids|count|name|label|type|prefix|length|ttl|at)$/i
|
|
35
|
+
|
|
36
|
+
export function isSecretKey(name: string): boolean {
|
|
37
|
+
// camelCase joins the words a separator would: webhookSecret is webhook_secret.
|
|
38
|
+
const norm = name.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
39
|
+
if (IDENTIFIER_SUFFIX.test(norm)) return false
|
|
40
|
+
return SECRET_KEY.test(norm)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const PATTERNS: Array<[RegExp, string]> = [
|
|
44
|
+
// Bearer / Basic credentials wherever they appear in a string.
|
|
45
|
+
[/\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/=]{8,}/g, `$1 ${REDACTED}`],
|
|
46
|
+
// Tangen API keys, site keys, transfer tokens: every prefixed credential the platform mints.
|
|
47
|
+
[/\btgn_[A-Za-z0-9_]{8,}/g, REDACTED],
|
|
48
|
+
// A JWT: three base64url segments, the first of which decodes to a JSON header.
|
|
49
|
+
[/\beyJ[A-Za-z0-9\-_]{8,}\.[A-Za-z0-9\-_]{8,}\.[A-Za-z0-9\-_]{8,}\b/g, REDACTED],
|
|
50
|
+
// The password of a connection string: scheme://user:PASSWORD@host
|
|
51
|
+
[/\b([a-z][a-z0-9+.\-]*:\/\/[^:/\s@]+:)[^@\s]+@/gi, `$1${REDACTED}@`],
|
|
52
|
+
// key=value pairs naming a secret inside free text (query strings, error messages).
|
|
53
|
+
[/\b(password|passwd|secret|token|api[_-]?key|access[_-]?token|refresh[_-]?token)(\s*[=:]\s*)(?!\[redacted\])[^\s&,;'"]+/gi, `$1$2${REDACTED}`],
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
/** Replaces credential-shaped material inside a string; identifiers survive. */
|
|
57
|
+
export function redactString(text: string): string {
|
|
58
|
+
let out = text
|
|
59
|
+
for (const [pattern, replacement] of PATTERNS) out = out.replace(pattern, replacement)
|
|
60
|
+
return out
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const MAX_DEPTH = 6
|
|
64
|
+
const MAX_KEYS = 200
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Redacts a log property value: secret keys lose their values, strings are
|
|
68
|
+
* scrubbed, objects and arrays are walked to a bounded depth, errors keep
|
|
69
|
+
* their name and a scrubbed message and stack.
|
|
70
|
+
*/
|
|
71
|
+
export function redactValue(value: unknown, depth = 0): unknown {
|
|
72
|
+
if (typeof value === 'string') return redactString(value)
|
|
73
|
+
if (value === null || typeof value !== 'object') return value
|
|
74
|
+
// A resolved deployment or a secret accessor is marked NO_LOG: it is never
|
|
75
|
+
// written down, not even redacted (amendment C - the diagnostic projection is explicit).
|
|
76
|
+
if ((value as Record<symbol, unknown>)[NO_LOG] === true) return NO_LOG_PLACEHOLDER
|
|
77
|
+
if (depth >= MAX_DEPTH) return '[depth]'
|
|
78
|
+
if (value instanceof Error) {
|
|
79
|
+
return { name: value.name, message: redactString(value.message), ...(value.stack ? { stack: redactString(value.stack) } : {}) }
|
|
80
|
+
}
|
|
81
|
+
if (value instanceof Date) return value
|
|
82
|
+
if (Array.isArray(value)) return value.slice(0, MAX_KEYS).map((v) => redactValue(v, depth + 1))
|
|
83
|
+
const out: Record<string, unknown> = {}
|
|
84
|
+
let n = 0
|
|
85
|
+
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
|
86
|
+
if (n++ >= MAX_KEYS) { out['…'] = '[truncated]'; break }
|
|
87
|
+
out[k] = (v as Record<symbol, unknown> | null)?.[NO_LOG] === true ? NO_LOG_PLACEHOLDER
|
|
88
|
+
: isSecretKey(k) ? (v === undefined || v === null || v === '' ? v : REDACTED) : redactValue(v, depth + 1)
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The properties of one log record, redacted. */
|
|
94
|
+
export function redactMeta(meta: Record<string, unknown> | undefined): Record<string, unknown> {
|
|
95
|
+
if (!meta) return {}
|
|
96
|
+
return redactValue(meta) as Record<string, unknown>
|
|
97
|
+
}
|
package/README.md
DELETED