Repository navigation
Expand file tree
/
Copy pathlogger.ts
More file actions
205 lines (183 loc) · 7.1 KB
/
Copy pathlogger.ts
File metadata and controls
205 lines (183 loc) · 7.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { redactSecretLikeValues } from './secret_redaction';
import type { ApplicationErrorPublicRecord } from '../data/model/application_error';
let loggerDebug = false;
let loggerRemote = false;
let structuredLogging = false;
export interface LogEntry {
level: 'info' | 'warn' | 'error' | 'debug';
message: string;
timestamp: number;
metadata?: Record<string, unknown>;
}
const accumulatedLogEntries: LogEntry[] = [];
const MAX_LOG_MESSAGE_LENGTH = 8000;
const SENSITIVE_KEY_PATTERN = /(api[_-]?key|access[_-]?token|refresh[_-]?token|password|secret|authorization|private[_-]?key|(?:^|[_-])(token|credential|pat)(?:$|[_-]))/i;
const SENSITIVE_ENVIRONMENT_KEY_PATTERN = /(api[_-]?key|api[_-]?token|access[_-]?token|refresh[_-]?token|auth[_-]?token|client[_-]?secret|secret[_-]?key|password|(?:^|[_-])(?:token|pat)(?:$|[_-]))$/i;
const SENSITIVE_ENVIRONMENT_KEYS = [
'PAT',
'PERSONAL_ACCESS_TOKEN',
'GITHUB_TOKEN',
'OPENAI_API_KEY',
'OPENCODE_API_KEY',
'CURSOR_API_KEY',
'ANTHROPIC_API_KEY',
'GOOGLE_API_KEY',
'OPENROUTER_API_KEY',
];
/** Removes markdown code fences from message so log output does not break when visualized (e.g. GitHub Actions). */
function sanitizeLogMessage(message: string): string {
let sanitized = message
.replace(/```/g, '')
// GitHub Actions interprets lines beginning with :: as workflow commands.
// Keep diagnostics readable while making user/provider-controlled text inert.
.replace(/(^|[\r\n])([ \t]*)::/g, '$1$2:\u200b:');
// Do not allow terminal/control bytes to alter the rendered log stream.
sanitized = Array.from(sanitized)
.filter((character) => !isUnsafeLogControl(character))
.join('');
const environmentKeys = new Set([
...SENSITIVE_ENVIRONMENT_KEYS,
...Object.keys(process.env).filter((key) => SENSITIVE_ENVIRONMENT_KEY_PATTERN.test(key)),
]);
for (const key of environmentKeys) {
const value = process.env[key]?.trim();
if (value && value.length >= 6) {
sanitized = sanitized.split(value).join('[REDACTED]');
}
}
sanitized = redactSecretLikeValues(sanitized);
return sanitized.length > MAX_LOG_MESSAGE_LENGTH
? `${sanitized.slice(0, MAX_LOG_MESSAGE_LENGTH)}… [truncated]`
: sanitized;
}
function isUnsafeLogControl(character: string): boolean {
const codePoint = character.codePointAt(0) ?? 0;
return (codePoint >= 0 && codePoint <= 8)
|| codePoint === 11
|| codePoint === 12
|| (codePoint >= 14 && codePoint <= 31)
|| codePoint === 127;
}
function sanitizeMetadataValue(value: unknown, key?: string): unknown {
if (key && SENSITIVE_KEY_PATTERN.test(key)) return '[REDACTED]';
if (typeof value === 'string') return sanitizeLogMessage(value);
if (Array.isArray(value)) return value.map((item) => sanitizeMetadataValue(item));
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([entryKey, entryValue]) => [
entryKey,
sanitizeMetadataValue(entryValue, entryKey),
]),
);
}
return value;
}
function sanitizeMetadata(metadata?: Record<string, unknown>): Record<string, unknown> | undefined {
return metadata === undefined
? undefined
: sanitizeMetadataValue(metadata) as Record<string, unknown>;
}
function pushLogEntry(entry: LogEntry): void {
accumulatedLogEntries.push(entry);
}
export function getAccumulatedLogEntries(): LogEntry[] {
return [...accumulatedLogEntries];
}
export function getAccumulatedLogsAsText(): string {
return accumulatedLogEntries
.map((e) => {
const prefix = `[${e.level.toUpperCase()}]`;
return `${prefix} ${e.message}`;
})
.join('\n');
}
export function clearAccumulatedLogs(): void {
accumulatedLogEntries.length = 0;
}
export function setGlobalLoggerDebug(debug: boolean, isRemote: boolean = false) {
loggerDebug = debug;
loggerRemote = isRemote;
}
export function setStructuredLogging(enabled: boolean) {
structuredLogging = enabled;
}
function formatStructuredLog(entry: LogEntry): string {
return JSON.stringify(entry);
}
function emitLog(
entry: LogEntry,
writer: (message: string) => void,
previousWasSingleLine = false,
skipAccumulation = false,
): void {
if (!skipAccumulation) pushLogEntry(entry);
if (previousWasSingleLine && !loggerRemote && !structuredLogging) console.log();
writer(structuredLogging ? formatStructuredLog(entry) : entry.message);
}
export function logInfo(message: string, previousWasSingleLine: boolean = false, metadata?: Record<string, unknown>, skipAccumulation?: boolean) {
const sanitized = sanitizeLogMessage(message);
const sanitizedMetadata = sanitizeMetadata(metadata);
emitLog(
{ level: 'info', message: sanitized, timestamp: Date.now(), metadata: sanitizedMetadata },
console.log,
previousWasSingleLine,
skipAccumulation,
);
}
export function logWarn(message: string, metadata?: Record<string, unknown>) {
const sanitized = sanitizeLogMessage(message);
const sanitizedMetadata = sanitizeMetadata(metadata);
emitLog(
{ level: 'warn', message: sanitized, timestamp: Date.now(), metadata: sanitizedMetadata },
console.warn,
);
}
export function logWarning(message: string) {
logWarn(message);
}
export function logError(message: string | ApplicationErrorPublicRecord, metadata?: Record<string, unknown>) {
const errorMessage = typeof message === 'string' ? message : message.message;
const sanitized = sanitizeLogMessage(errorMessage);
const safeMetadata = sanitizeMetadata(typeof message === 'string'
? metadata
: {
...metadata,
applicationError: {
name: message.name,
message: message.message,
code: message.code,
kind: message.kind,
retryable: message.retryable,
impact: message.impact,
action: message.action,
retainedState: message.retainedState,
correlationId: message.correlationId,
...(message.recovery ? { recovery: message.recovery } : {}),
},
});
emitLog(
{ level: 'error', message: sanitized, timestamp: Date.now(), metadata: safeMetadata },
console.error,
);
}
export function logDebugInfo(message: string, previousWasSingleLine: boolean = false, metadata?: Record<string, unknown>) {
if (loggerDebug) {
const sanitized = sanitizeLogMessage(message);
const sanitizedMetadata = sanitizeMetadata(metadata);
emitLog(
{ level: 'debug', message: sanitized, timestamp: Date.now(), metadata: sanitizedMetadata },
console.log,
previousWasSingleLine,
);
}
}
export function logDebugWarning(message: string) {
if (loggerDebug) {
logWarning(message);
}
}
export function logDebugError(message: string | ApplicationErrorPublicRecord) {
if (loggerDebug) {
logError(message);
}
}