Repository navigation
Expand file tree
/
Copy pathplatform-runtime-app-log-output.ts
More file actions
162 lines (152 loc) · 5.58 KB
/
Copy pathplatform-runtime-app-log-output.ts
File metadata and controls
162 lines (152 loc) · 5.58 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
import { AppError } from '@agent-device/kernel/errors';
import { ensureAppLogPath } from '@agent-device/capture-kit/app-log-files';
import type { AppLogOutputSink } from '@agent-device/contracts/app-log-runtime';
import fs from 'node:fs';
import type { HostEnvironment } from '@agent-device/kernel/source-value';
import { openVerifiedFileForAppend, openVerifiedFileForRead } from '@agent-device/host-kit/file';
import { requireManagedSessionArtifactPath } from '@agent-device/daemon-contracts/session-artifact-paths';
export async function openAppLogOutput(
sessionsDir: string,
pathname: string,
host: HostEnvironment,
): Promise<AppLogOutputSink> {
pathname = requireManagedOutputPath(sessionsDir, pathname);
const patterns = redactionPatterns(host.env);
ensureAppLogPath(pathname, host.env);
const descriptor = openVerifiedFileForAppend(pathname);
let stream: fs.WriteStream;
try {
stream = fs.createWriteStream(pathname, { fd: descriptor, autoClose: true });
} catch (error) {
fs.closeSync(descriptor);
throw error;
}
let streamError: Error | undefined;
stream.on('error', (error) => {
streamError ??= error;
});
let pending = '';
let writes = Promise.resolve();
let disposal: Promise<void> | undefined;
const enqueue = (work: () => Promise<void>) => {
const next = writes.then(work);
writes = next.catch(() => undefined);
return next;
};
const writeText = async (text: string) => {
const combined = `${pending}${text}`;
const lines = combined.split('\n');
pending = lines.pop() ?? '';
for (const line of lines) await writeChunk(stream, redact(`${line}\n`, patterns));
};
return {
write: async (chunk) => await enqueue(async () => await writeText(decodeAppLogChunk(chunk))),
[Symbol.asyncDispose]: async () => {
disposal ??= enqueue(async () => {
if (pending) {
await writeChunk(stream, redact(pending, patterns));
pending = '';
}
await closeStream(stream);
if (streamError) throw streamError;
});
await disposal;
},
};
}
export async function readAppLogOutputTail(
sessionsDir: string,
pathname: string,
maxBytes: number,
): Promise<string> {
pathname = requireManagedOutputPath(sessionsDir, pathname);
if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1024 * 1024) {
throw new TypeError('App-log tail size must be between 1 byte and 1 MiB');
}
const handle = openVerifiedFileForRead(pathname);
if (handle === undefined) return '';
const size = fs.fstatSync(handle).size;
const length = Math.min(size, maxBytes);
const start = size - length;
const prefixLength = start > 0 ? 1 : 0;
const buffer = Buffer.alloc(length + prefixLength);
try {
fs.readSync(handle, buffer, 0, buffer.length, start - prefixLength);
} finally {
fs.closeSync(handle);
}
const decoded = buffer.subarray(prefixLength).toString('utf8');
if (prefixLength === 0 || buffer[0] === 0x0a) return decoded;
const firstCompleteLine = decoded.indexOf('\n');
return firstCompleteLine < 0 ? '' : decoded.slice(firstCompleteLine + 1);
}
function requireManagedOutputPath(sessionsDir: string, pathname: string): string {
return requireManagedSessionArtifactPath({
sessionsDir,
pathname,
basename: 'app.log',
label: 'App-log output',
});
}
/**
* Splits `AGENT_DEVICE_APP_LOG_REDACT_PATTERNS` on commas outside groups, character classes, and
* `{m,n}` quantifiers. Write `\,` for any other literal comma.
*/
function redactionPatterns(env: NodeJS.ProcessEnv): RegExp[] {
return splitTopLevelPatternList(env.AGENT_DEVICE_APP_LOG_REDACT_PATTERNS ?? '')
.map((part) => part.trim())
.filter(Boolean)
.map((pattern, patternIndex) => {
try {
return new RegExp(pattern, 'gi');
} catch {
// The pattern text and the engine's message can quote the secret the rule protects.
throw new AppError(
'INVALID_ARGS',
`AGENT_DEVICE_APP_LOG_REDACT_PATTERNS entry ${patternIndex + 1} is not a valid regular expression`,
{ reason: 'app_log_redact_pattern_invalid', patternIndex },
);
}
});
}
/**
* One regex token: an escape, a whole character class, a `{m}`/`{m,}`/`{m,n}` quantifier, or one
* other character. Only parentheses nest; a brace that is not a quantifier is a literal.
*/
const PATTERN_TOKEN_RE = /\\[\s\S]?|\[(?:\\[\s\S]|[^\]\\])*\]?|\{\d+(?:,\d*)?\}|[\s\S]/g;
function splitTopLevelPatternList(value: string): string[] {
const parts: string[] = [''];
let depth = 0;
for (const [token] of value.matchAll(PATTERN_TOKEN_RE)) {
if (token === ',' && depth === 0) {
parts.push('');
continue;
}
if (token === '(') depth += 1;
else if (token === ')') depth = Math.max(0, depth - 1);
parts[parts.length - 1] += token;
}
return parts;
}
function redact(chunk: string, patterns: readonly RegExp[]): string {
return patterns.reduce((output, pattern) => output.replace(pattern, '[REDACTED]'), chunk);
}
function decodeAppLogChunk(chunk: string | Uint8Array): string {
return typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
}
async function writeChunk(stream: fs.WriteStream, chunk: string): Promise<void> {
if (!chunk) return;
await new Promise<void>((resolve, reject) => {
stream.write(chunk, (error) => (error ? reject(error) : resolve()));
});
}
async function closeStream(stream: fs.WriteStream): Promise<void> {
if (stream.closed) return;
await new Promise<void>((resolve, reject) => {
stream.once('error', reject);
stream.end(() => {
stream.off('error', reject);
resolve();
});
});
}