vouchington-tooling 0.1.4 → 0.1.6
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 +36 -0
- package/dist/cli/index.mjs +4 -0
- package/dist/cli/parse.d.mts +1 -1
- package/dist/cli/parse.mjs +1 -0
- package/dist/cli/usage.d.mts +1 -1
- package/dist/cli/usage.mjs +3 -1
- package/dist/gha-post-review/post.mjs +2 -9
- package/dist/gha-review-payload/index.d.mts +1 -1
- package/dist/gha-review-payload/index.mjs +1 -1
- package/dist/gha-review-payload/payload.d.mts +1 -3
- package/dist/gha-review-payload/payload.mjs +15 -31
- package/dist/gha-review-payload/remap.d.mts +1 -1
- package/dist/gha-review-payload/remap.mjs +7 -16
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +2 -1
- package/dist/retrospective-transcript/codex-messages.d.mts +8 -0
- package/dist/retrospective-transcript/codex-messages.mjs +66 -0
- package/dist/retrospective-transcript/codex.mjs +9 -4
- package/dist/session-friction/ci-failures.d.mts +11 -0
- package/dist/session-friction/ci-failures.mjs +78 -0
- package/dist/session-friction/classify.d.mts +2 -0
- package/dist/session-friction/classify.mjs +87 -0
- package/dist/session-friction/directory.d.mts +1 -0
- package/dist/session-friction/directory.mjs +71 -0
- package/dist/session-friction/index.d.mts +6 -0
- package/dist/session-friction/index.mjs +5 -0
- package/dist/session-friction/lock.d.mts +1 -0
- package/dist/session-friction/lock.mjs +193 -0
- package/dist/session-friction/log.d.mts +8 -0
- package/dist/session-friction/log.mjs +195 -0
- package/dist/session-friction/normalize.d.mts +1 -0
- package/dist/session-friction/normalize.mjs +174 -0
- package/dist/session-friction/report.d.mts +2 -0
- package/dist/session-friction/report.mjs +113 -0
- package/dist/session-friction/sandbox.d.mts +2 -0
- package/dist/session-friction/sandbox.mjs +15 -0
- package/dist/session-friction/session-id.d.mts +2 -0
- package/dist/session-friction/session-id.mjs +17 -0
- package/dist/session-friction/text.d.mts +5 -0
- package/dist/session-friction/text.mjs +45 -0
- package/dist/session-friction/types.d.mts +52 -0
- package/dist/session-friction/types.mjs +1 -0
- package/dist/session-friction/utf8.d.mts +1 -0
- package/dist/session-friction/utf8.mjs +8 -0
- package/package.json +7 -2
- package/scripts/gha/download-optional-run-artifacts.sh +126 -0
- package/scripts/gha/install-github-release.sh +17 -4
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { normalizeCommandPrefix } from './normalize.mjs';
|
|
2
|
+
import { boundedText, isWellFormedUnicode, normalizeAuditText } from './text.mjs';
|
|
3
|
+
const FAILURE_TOKENS = [
|
|
4
|
+
['Operation not permitted', /Operation not permitted/i],
|
|
5
|
+
['E2BIG', /\bE2BIG\b/i],
|
|
6
|
+
['EPERM', /\bEPERM\b/i],
|
|
7
|
+
];
|
|
8
|
+
const CONNECTION_REFUSED = /\bECONNREFUSED\b/i;
|
|
9
|
+
const URL_USERINFO = /([a-z][a-z0-9+.-]{0,31}:\/\/)[^\s/?#@]*@/gi;
|
|
10
|
+
const STDERR_INSPECTION_MAX_LENGTH = 100_000;
|
|
11
|
+
const COMMAND_INSPECTION_MAX_LENGTH = 10_000;
|
|
12
|
+
const IPV4_OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)';
|
|
13
|
+
const LOOPBACK_ADDRESSES = [
|
|
14
|
+
new RegExp(String.raw `(?<![0-9a-z_.:-])(?:127\.${IPV4_OCTET}(?:\.${IPV4_OCTET}){2}|localhost)(?![0-9a-z_.-])`, 'i'),
|
|
15
|
+
/(?<![0-9a-z_.-])\[(?:::1|0:0:0:0:0:0:0:1)(?:%[a-z0-9_.-]+)?\](?![0-9a-z_.-])/i,
|
|
16
|
+
/(?<![0-9a-z_.:\x5b\x5d-])(?:::1|0:0:0:0:0:0:0:1)(?:%[a-z0-9_.-]+)?(?::\d{1,5})?(?![0-9a-z_.:\x5b\x5d-])/i,
|
|
17
|
+
];
|
|
18
|
+
const DETAIL_MAX_LENGTH = 1_000;
|
|
19
|
+
function boundedTail(value, maximum) {
|
|
20
|
+
let start = Math.max(0, value.length - maximum);
|
|
21
|
+
const first = value.charCodeAt(start);
|
|
22
|
+
const previous = value.charCodeAt(start - 1);
|
|
23
|
+
if (first >= 0xdc00 && first <= 0xdfff && previous >= 0xd800 && previous <= 0xdbff)
|
|
24
|
+
start++;
|
|
25
|
+
return value.slice(start);
|
|
26
|
+
}
|
|
27
|
+
function boundedStderr(value) {
|
|
28
|
+
if (value.length <= STDERR_INSPECTION_MAX_LENGTH)
|
|
29
|
+
return value;
|
|
30
|
+
const headLength = Math.floor((STDERR_INSPECTION_MAX_LENGTH - 1) / 2);
|
|
31
|
+
const head = boundedText(value, headLength);
|
|
32
|
+
const tail = boundedTail(value, STDERR_INSPECTION_MAX_LENGTH - 1 - head.length);
|
|
33
|
+
return `${head}\n${tail}`;
|
|
34
|
+
}
|
|
35
|
+
function withoutUrlUserinfo(line) {
|
|
36
|
+
return line.includes('://') && line.includes('@') ? line.replace(URL_USERINFO, '$1') : line;
|
|
37
|
+
}
|
|
38
|
+
export function classifyFrictionObservation(observation) {
|
|
39
|
+
if (!observation || typeof observation !== 'object')
|
|
40
|
+
return null;
|
|
41
|
+
if (typeof observation.command !== 'string')
|
|
42
|
+
return null;
|
|
43
|
+
const command = boundedText(observation.command, COMMAND_INSPECTION_MAX_LENGTH);
|
|
44
|
+
if (!isWellFormedUnicode(command) || normalizeAuditText(command) === '')
|
|
45
|
+
return null;
|
|
46
|
+
const commandPrefix = normalizeCommandPrefix(command, observation.commandWrappers);
|
|
47
|
+
if (commandPrefix === '' || !isWellFormedUnicode(commandPrefix))
|
|
48
|
+
return null;
|
|
49
|
+
if (observation.type === 'permission-request') {
|
|
50
|
+
return { kind: 'sandbox-escalation', commandPrefix, detail: 'permission-request' };
|
|
51
|
+
}
|
|
52
|
+
if (observation.type !== 'tool-result')
|
|
53
|
+
return null;
|
|
54
|
+
if (observation.escalationDetail !== undefined &&
|
|
55
|
+
typeof observation.escalationDetail !== 'string')
|
|
56
|
+
return null;
|
|
57
|
+
const escalationDetail = normalizeAuditText(boundedText(observation.escalationDetail ?? '', DETAIL_MAX_LENGTH));
|
|
58
|
+
if (!isWellFormedUnicode(escalationDetail))
|
|
59
|
+
return null;
|
|
60
|
+
if (escalationDetail) {
|
|
61
|
+
return {
|
|
62
|
+
kind: 'sandbox-escalation',
|
|
63
|
+
commandPrefix,
|
|
64
|
+
detail: escalationDetail,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const rawStderr = observation.structuredStderr;
|
|
68
|
+
if (rawStderr !== undefined && (typeof rawStderr !== 'string' || !isWellFormedUnicode(rawStderr)))
|
|
69
|
+
return null;
|
|
70
|
+
const stderr = rawStderr ? boundedStderr(rawStderr) : rawStderr;
|
|
71
|
+
if (stderr === undefined)
|
|
72
|
+
return null;
|
|
73
|
+
const token = FAILURE_TOKENS.find(([, pattern]) => pattern.test(stderr))?.[0];
|
|
74
|
+
if (token)
|
|
75
|
+
return { kind: 'sandbox-failure', commandPrefix, detail: `stderr matched "${token}"` };
|
|
76
|
+
if (stderr.split(/\r\n|[\r\n]/).some((rawLine) => {
|
|
77
|
+
const line = withoutUrlUserinfo(rawLine);
|
|
78
|
+
return (CONNECTION_REFUSED.test(line) && LOOPBACK_ADDRESSES.some((pattern) => pattern.test(line)));
|
|
79
|
+
})) {
|
|
80
|
+
return {
|
|
81
|
+
kind: 'sandbox-failure',
|
|
82
|
+
commandPrefix,
|
|
83
|
+
detail: 'stderr matched localhost connection failure',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function ensurePrivateDirectory(directory: string, create: boolean): boolean;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { chmodSync, lstatSync, mkdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
const PRIVATE_DIRECTORY_MODE = 0o700;
|
|
4
|
+
function isCode(error, code) {
|
|
5
|
+
return Boolean(error && typeof error === 'object' && 'code' in error && error.code === code);
|
|
6
|
+
}
|
|
7
|
+
function directoryChain(directory) {
|
|
8
|
+
const chain = [directory];
|
|
9
|
+
let current = directory;
|
|
10
|
+
while (dirname(current) !== current) {
|
|
11
|
+
current = dirname(current);
|
|
12
|
+
chain.push(current);
|
|
13
|
+
}
|
|
14
|
+
return chain.reverse();
|
|
15
|
+
}
|
|
16
|
+
export function ensurePrivateDirectory(directory, create) {
|
|
17
|
+
const chain = directoryChain(directory);
|
|
18
|
+
const effectiveUserId = process.geteuid?.();
|
|
19
|
+
if (effectiveUserId === undefined)
|
|
20
|
+
throw new Error('session-friction requires POSIX directory permissions');
|
|
21
|
+
for (const [index, path] of chain.entries()) {
|
|
22
|
+
let created = false;
|
|
23
|
+
let status;
|
|
24
|
+
try {
|
|
25
|
+
status = lstatSync(path);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
/* v8 ignore next -- unexpected filesystem errors are propagated unchanged. */
|
|
29
|
+
if (!isCode(error, 'ENOENT'))
|
|
30
|
+
throw error;
|
|
31
|
+
if (!create)
|
|
32
|
+
return false;
|
|
33
|
+
try {
|
|
34
|
+
mkdirSync(path, { mode: PRIVATE_DIRECTORY_MODE });
|
|
35
|
+
created = true;
|
|
36
|
+
}
|
|
37
|
+
catch (mkdirError) {
|
|
38
|
+
/* v8 ignore next -- another process can create the directory after lstat. */
|
|
39
|
+
if (!isCode(mkdirError, 'EEXIST'))
|
|
40
|
+
throw mkdirError;
|
|
41
|
+
}
|
|
42
|
+
status = lstatSync(path);
|
|
43
|
+
}
|
|
44
|
+
const leaf = index === chain.length - 1;
|
|
45
|
+
if (status.isSymbolicLink()) {
|
|
46
|
+
if (leaf || status.uid !== 0)
|
|
47
|
+
throw new Error('session-friction log directory must be a private directory');
|
|
48
|
+
try {
|
|
49
|
+
status = statSync(path);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new Error('session-friction log directory must be a private directory');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (!status.isDirectory())
|
|
56
|
+
throw new Error('session-friction log directory must be a private directory');
|
|
57
|
+
if (created)
|
|
58
|
+
chmodSync(path, PRIVATE_DIRECTORY_MODE);
|
|
59
|
+
if (!created) {
|
|
60
|
+
const ownedByCaller = status.uid === effectiveUserId;
|
|
61
|
+
const ownedByRoot = status.uid === 0;
|
|
62
|
+
const writableByOthers = (status.mode & 0o022) !== 0;
|
|
63
|
+
const sticky = (status.mode & 0o1000) !== 0;
|
|
64
|
+
if ((leaf && ((status.mode & 0o777) !== PRIVATE_DIRECTORY_MODE || !ownedByCaller)) ||
|
|
65
|
+
(!leaf && !ownedByCaller && !ownedByRoot) ||
|
|
66
|
+
(!leaf && writableByOthers && !sticky))
|
|
67
|
+
throw new Error('session-friction log directory must be a private directory');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { classifyFrictionObservation } from './classify.mts';
|
|
2
|
+
export { normalizeCommandPrefix } from './normalize.mts';
|
|
3
|
+
export { FRICTION_LOG_MAX_EVENTS, readFrictionLog, recordFriction } from './log.mts';
|
|
4
|
+
export { buildSessionFrictionReport } from './report.mts';
|
|
5
|
+
export { isConformingCiFailureBlock } from './ci-failures.mts';
|
|
6
|
+
export type { FrictionEvent, FrictionEventKind, FrictionLogOptions, FrictionLogReadResult, FrictionObservation, JournalEntry, JournalLoadResult, JournalLoader, PermissionRequestObservation, SessionFrictionReport, SessionFrictionReportOptions, ToolResultObservation, } from './types.mts';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { classifyFrictionObservation } from './classify.mjs';
|
|
2
|
+
export { normalizeCommandPrefix } from './normalize.mjs';
|
|
3
|
+
export { FRICTION_LOG_MAX_EVENTS, readFrictionLog, recordFriction } from './log.mjs';
|
|
4
|
+
export { buildSessionFrictionReport } from './report.mjs';
|
|
5
|
+
export { isConformingCiFailureBlock } from './ci-failures.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function withFileLock<Result>(path: string, action: () => Result): Result;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
2
|
+
import { basename } from 'node:path';
|
|
3
|
+
const LOCK_ATTEMPTS = 200;
|
|
4
|
+
const STALE_LOCK_AGE_MS = 30_000;
|
|
5
|
+
const LOCK_OWNER_MAX_BYTES = 32;
|
|
6
|
+
const MAX_PID = 2_147_483_647;
|
|
7
|
+
const LOCK_CREATE_FLAGS = constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW;
|
|
8
|
+
const lockWait = new Int32Array(new SharedArrayBuffer(4));
|
|
9
|
+
function waitForLock() {
|
|
10
|
+
// Intentional synchronous backoff for CLI and hook callers.
|
|
11
|
+
Atomics.wait(lockWait, 0, 0, 5);
|
|
12
|
+
}
|
|
13
|
+
function hasCode(error, code) {
|
|
14
|
+
return Boolean(error && typeof error === 'object' && 'code' in error && error.code === code);
|
|
15
|
+
}
|
|
16
|
+
function isFresh(mtimeMs) {
|
|
17
|
+
const age = Date.now() - Math.floor(mtimeMs);
|
|
18
|
+
return age > -STALE_LOCK_AGE_MS && age < STALE_LOCK_AGE_MS;
|
|
19
|
+
}
|
|
20
|
+
function inspectLock(lockPath) {
|
|
21
|
+
let descriptor;
|
|
22
|
+
try {
|
|
23
|
+
descriptor = openSync(lockPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
/* v8 ignore next -- detects a lock that disappears or is replaced while being inspected. */
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const status = fstatSync(descriptor);
|
|
31
|
+
/* v8 ignore next -- opening a non-regular lock requires a platform-specific FIFO/device. */
|
|
32
|
+
if (!status.isFile())
|
|
33
|
+
return null;
|
|
34
|
+
if (status.size > LOCK_OWNER_MAX_BYTES)
|
|
35
|
+
return isFresh(status.mtimeMs)
|
|
36
|
+
? null
|
|
37
|
+
: { dev: status.dev, ino: status.ino, mtimeMs: status.mtimeMs, owner: null };
|
|
38
|
+
const buffer = Buffer.alloc(LOCK_OWNER_MAX_BYTES + 1);
|
|
39
|
+
let length = 0;
|
|
40
|
+
while (length < buffer.length) {
|
|
41
|
+
const bytes = readSync(descriptor, buffer, length, buffer.length - length, length);
|
|
42
|
+
if (bytes === 0)
|
|
43
|
+
break;
|
|
44
|
+
length += bytes;
|
|
45
|
+
}
|
|
46
|
+
/* v8 ignore next -- detects external growth after the descriptor metadata check. */
|
|
47
|
+
if (length > LOCK_OWNER_MAX_BYTES)
|
|
48
|
+
return null;
|
|
49
|
+
const rawOwner = buffer.subarray(0, length).toString();
|
|
50
|
+
return {
|
|
51
|
+
dev: status.dev,
|
|
52
|
+
ino: status.ino,
|
|
53
|
+
mtimeMs: status.mtimeMs,
|
|
54
|
+
owner: /^[1-9][0-9]*$/.test(rawOwner) ? Number(rawOwner) : null,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
closeSync(descriptor);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function withReaperLock(lockPath, action) {
|
|
62
|
+
const reaperPath = `${lockPath}.reap`;
|
|
63
|
+
let descriptor;
|
|
64
|
+
try {
|
|
65
|
+
descriptor = openSync(reaperPath, LOCK_CREATE_FLAGS, 0o600);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
/* v8 ignore next 2 -- requires a narrow filesystem race or platform open failure. */
|
|
69
|
+
if (hasCode(error, 'EEXIST') || hasCode(error, 'ENOENT'))
|
|
70
|
+
return false;
|
|
71
|
+
/* v8 ignore next -- unexpected platform errors must propagate. */
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return action();
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
closeSync(descriptor);
|
|
79
|
+
try {
|
|
80
|
+
unlinkSync(reaperPath);
|
|
81
|
+
}
|
|
82
|
+
catch { }
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function removeOrphanedReaper(reaperPath) {
|
|
86
|
+
try {
|
|
87
|
+
const inspected = lstatSync(reaperPath);
|
|
88
|
+
if (isFresh(inspected.mtimeMs))
|
|
89
|
+
return false;
|
|
90
|
+
const current = lstatSync(reaperPath);
|
|
91
|
+
/* v8 ignore next 5 -- requires external replacement during stale-reaper recovery. */
|
|
92
|
+
if (current.dev !== inspected.dev ||
|
|
93
|
+
current.ino !== inspected.ino ||
|
|
94
|
+
current.mtimeMs !== inspected.mtimeMs)
|
|
95
|
+
return false;
|
|
96
|
+
unlinkSync(reaperPath);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
/* v8 ignore next -- requires external removal during stale-reaper recovery. */
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function removeStaleLock(lockPath) {
|
|
105
|
+
return withReaperLock(lockPath, () => {
|
|
106
|
+
try {
|
|
107
|
+
const inspected = inspectLock(lockPath);
|
|
108
|
+
if (!inspected)
|
|
109
|
+
return false;
|
|
110
|
+
const fresh = isFresh(inspected.mtimeMs);
|
|
111
|
+
const { owner } = inspected;
|
|
112
|
+
if (typeof owner === 'number' && Number.isInteger(owner) && owner > 0 && owner <= MAX_PID) {
|
|
113
|
+
try {
|
|
114
|
+
process.kill(owner, 0);
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
if (!hasCode(error, 'ESRCH'))
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else if (fresh)
|
|
123
|
+
return false;
|
|
124
|
+
const current = lstatSync(lockPath);
|
|
125
|
+
/* v8 ignore next 5 -- requires external replacement despite the reaper protocol. */
|
|
126
|
+
if (current.dev !== inspected.dev ||
|
|
127
|
+
current.ino !== inspected.ino ||
|
|
128
|
+
current.mtimeMs !== inspected.mtimeMs)
|
|
129
|
+
return false;
|
|
130
|
+
unlinkSync(lockPath);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
export function withFileLock(path, action) {
|
|
139
|
+
const lockPath = `${path}.lock`;
|
|
140
|
+
const reaperPath = `${lockPath}.reap`;
|
|
141
|
+
for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt++) {
|
|
142
|
+
let reaperExists = false;
|
|
143
|
+
try {
|
|
144
|
+
lstatSync(reaperPath);
|
|
145
|
+
reaperExists = true;
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
/* v8 ignore next -- unexpected reaper lstat failures must propagate. */
|
|
149
|
+
if (!hasCode(error, 'ENOENT'))
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
if (reaperExists) {
|
|
153
|
+
if (removeOrphanedReaper(reaperPath))
|
|
154
|
+
continue;
|
|
155
|
+
waitForLock();
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
let descriptor;
|
|
159
|
+
try {
|
|
160
|
+
descriptor = openSync(lockPath, LOCK_CREATE_FLAGS, 0o600);
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (!hasCode(error, 'EEXIST'))
|
|
164
|
+
throw error;
|
|
165
|
+
let lockStatus;
|
|
166
|
+
try {
|
|
167
|
+
lockStatus = lstatSync(lockPath);
|
|
168
|
+
}
|
|
169
|
+
catch (statusError) {
|
|
170
|
+
/* v8 ignore next -- requires the owner to release between EEXIST and lstat. */
|
|
171
|
+
if (hasCode(statusError, 'ENOENT'))
|
|
172
|
+
continue;
|
|
173
|
+
/* v8 ignore next -- requires an unexpected lstat failure during the same race. */
|
|
174
|
+
throw statusError;
|
|
175
|
+
}
|
|
176
|
+
if (!lockStatus.isFile())
|
|
177
|
+
throw new Error('session-friction log lock must be a regular file');
|
|
178
|
+
if (removeStaleLock(lockPath))
|
|
179
|
+
continue;
|
|
180
|
+
waitForLock();
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
writeFileSync(descriptor, String(process.pid));
|
|
185
|
+
return action();
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
closeSync(descriptor);
|
|
189
|
+
unlinkSync(lockPath);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
throw new Error(`could not acquire session-friction log lock for ${basename(path)}`);
|
|
193
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { FrictionLogOptions, FrictionLogReadResult, FrictionObservation } from './types.mts';
|
|
2
|
+
export declare const FRICTION_LOG_MAX_EVENTS = 500;
|
|
3
|
+
export declare function requireDirectory(directory: string): string;
|
|
4
|
+
export declare function eventLimit(maxEvents: number | undefined): number;
|
|
5
|
+
export declare function recordFriction(sessionId: string, observation: FrictionObservation, options: FrictionLogOptions & {
|
|
6
|
+
timestamp?: string | (() => string);
|
|
7
|
+
}): void;
|
|
8
|
+
export declare function readFrictionLog(sessionId: string, options: FrictionLogOptions): FrictionLogReadResult;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { closeSync, constants, fchmodSync, fstatSync, openSync, readSync, writeSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { classifyFrictionObservation } from './classify.mjs';
|
|
4
|
+
import { ensurePrivateDirectory } from './directory.mjs';
|
|
5
|
+
import { withFileLock } from './lock.mjs';
|
|
6
|
+
import { boundedText, isSafeAuditText, isWellFormedUnicode, normalizeAuditText } from './text.mjs';
|
|
7
|
+
import { decodeUtf8 } from './utf8.mjs';
|
|
8
|
+
import { sanitizeSessionId } from './session-id.mjs';
|
|
9
|
+
export const FRICTION_LOG_MAX_EVENTS = 500;
|
|
10
|
+
const LOG_MAX_BYTES = 2_000_000;
|
|
11
|
+
const EVENT_FIELD_MAX_LENGTH = 1_000;
|
|
12
|
+
export function requireDirectory(directory) {
|
|
13
|
+
if (typeof directory !== 'string')
|
|
14
|
+
throw new Error('log directory must be a string');
|
|
15
|
+
if (Buffer.byteLength(directory) > 4096)
|
|
16
|
+
throw new Error('session-friction log directory path is too long');
|
|
17
|
+
if (!isAbsolute(directory))
|
|
18
|
+
throw new Error('session-friction log directory must be absolute');
|
|
19
|
+
return resolve(directory);
|
|
20
|
+
}
|
|
21
|
+
export function eventLimit(maxEvents) {
|
|
22
|
+
const limit = maxEvents ?? FRICTION_LOG_MAX_EVENTS;
|
|
23
|
+
if (!Number.isInteger(limit) || limit < 1)
|
|
24
|
+
throw new Error('maxEvents must be a positive integer');
|
|
25
|
+
return Math.min(limit, FRICTION_LOG_MAX_EVENTS);
|
|
26
|
+
}
|
|
27
|
+
function logPath(sessionId, directory) {
|
|
28
|
+
return join(requireDirectory(directory), `${sanitizeSessionId(sessionId)}.jsonl`);
|
|
29
|
+
}
|
|
30
|
+
function validEvent(value) {
|
|
31
|
+
if (!value || typeof value !== 'object')
|
|
32
|
+
return false;
|
|
33
|
+
const record = value;
|
|
34
|
+
return ((record.kind === 'sandbox-escalation' || record.kind === 'sandbox-failure') &&
|
|
35
|
+
isSafeAuditText(record.timestamp) &&
|
|
36
|
+
isSafeAuditText(record.commandPrefix) &&
|
|
37
|
+
isSafeAuditText(record.detail));
|
|
38
|
+
}
|
|
39
|
+
function openLogFile(path, flags) {
|
|
40
|
+
let descriptor;
|
|
41
|
+
try {
|
|
42
|
+
descriptor = openSync(path, flags | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error &&
|
|
46
|
+
typeof error === 'object' &&
|
|
47
|
+
'code' in error &&
|
|
48
|
+
(error.code === 'ELOOP' || error.code === 'EISDIR' || error.code === 'ENOTDIR'))
|
|
49
|
+
throw new Error('session-friction log must be a regular file');
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const status = fstatSync(descriptor);
|
|
54
|
+
if (!status.isFile() || status.nlink !== 1)
|
|
55
|
+
throw new Error('session-friction log must be a regular file');
|
|
56
|
+
return descriptor;
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
closeSync(descriptor);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function readLogContent(descriptor) {
|
|
64
|
+
if (fstatSync(descriptor).size > LOG_MAX_BYTES)
|
|
65
|
+
throw new Error('session-friction log is too large');
|
|
66
|
+
const buffer = Buffer.alloc(LOG_MAX_BYTES + 1);
|
|
67
|
+
let length = 0;
|
|
68
|
+
while (length < buffer.length) {
|
|
69
|
+
const bytes = readSync(descriptor, buffer, length, buffer.length - length, length);
|
|
70
|
+
if (bytes === 0)
|
|
71
|
+
break;
|
|
72
|
+
length += bytes;
|
|
73
|
+
}
|
|
74
|
+
/* v8 ignore next -- detects external growth after the descriptor size check. */
|
|
75
|
+
if (length > LOG_MAX_BYTES)
|
|
76
|
+
throw new Error('session-friction log is too large');
|
|
77
|
+
return decodeUtf8(buffer.subarray(0, length));
|
|
78
|
+
}
|
|
79
|
+
function validEventCount(content, limit) {
|
|
80
|
+
let count = 0;
|
|
81
|
+
for (const line of content.split('\n')) {
|
|
82
|
+
if (!line.trim())
|
|
83
|
+
continue;
|
|
84
|
+
try {
|
|
85
|
+
if (validEvent(JSON.parse(line)))
|
|
86
|
+
count++;
|
|
87
|
+
}
|
|
88
|
+
catch { }
|
|
89
|
+
if (count >= limit)
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
return count;
|
|
93
|
+
}
|
|
94
|
+
function atEventLimit(content, limit) {
|
|
95
|
+
return validEventCount(content, limit) >= limit;
|
|
96
|
+
}
|
|
97
|
+
function writeAll(descriptor, value) {
|
|
98
|
+
const buffer = Buffer.from(value);
|
|
99
|
+
let offset = 0;
|
|
100
|
+
while (offset < buffer.length) {
|
|
101
|
+
const written = writeSync(descriptor, buffer, offset, buffer.length - offset);
|
|
102
|
+
/* v8 ignore next -- a zero-byte synchronous file write is an external I/O failure. */
|
|
103
|
+
if (written === 0)
|
|
104
|
+
throw new Error('session-friction log write made no progress');
|
|
105
|
+
offset += written;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export function recordFriction(sessionId, observation, options) {
|
|
109
|
+
const maxEvents = eventLimit(options.maxEvents);
|
|
110
|
+
const timestamp = typeof options.timestamp === 'function' ? options.timestamp() : options.timestamp;
|
|
111
|
+
if (timestamp !== undefined && typeof timestamp !== 'string')
|
|
112
|
+
throw new Error('timestamp must be a string');
|
|
113
|
+
const rawTimestamp = timestamp ?? new Date().toISOString();
|
|
114
|
+
const normalizedTimestamp = normalizeAuditText(boundedText(rawTimestamp, EVENT_FIELD_MAX_LENGTH));
|
|
115
|
+
if (!normalizedTimestamp)
|
|
116
|
+
throw new Error('timestamp must be non-empty');
|
|
117
|
+
if (!isWellFormedUnicode(normalizedTimestamp))
|
|
118
|
+
throw new Error('timestamp must be well-formed Unicode');
|
|
119
|
+
const classified = classifyFrictionObservation(observation);
|
|
120
|
+
const path = logPath(sessionId, options.directory);
|
|
121
|
+
const directory = requireDirectory(options.directory);
|
|
122
|
+
ensurePrivateDirectory(directory, true);
|
|
123
|
+
withFileLock(path, () => {
|
|
124
|
+
/* v8 ignore next 2 -- requires the directory path to be replaced after its lock is acquired. */
|
|
125
|
+
if (!ensurePrivateDirectory(directory, false))
|
|
126
|
+
throw new Error('session-friction log directory disappeared while acquiring the lock');
|
|
127
|
+
const descriptor = openLogFile(path, constants.O_CREAT | constants.O_RDWR | constants.O_APPEND);
|
|
128
|
+
try {
|
|
129
|
+
fchmodSync(descriptor, 0o600);
|
|
130
|
+
if (fstatSync(descriptor).size > LOG_MAX_BYTES)
|
|
131
|
+
throw new Error('session-friction log is too large');
|
|
132
|
+
if (!classified)
|
|
133
|
+
return;
|
|
134
|
+
const content = readLogContent(descriptor);
|
|
135
|
+
if (atEventLimit(content, maxEvents))
|
|
136
|
+
return;
|
|
137
|
+
const event = {
|
|
138
|
+
...classified,
|
|
139
|
+
commandPrefix: normalizeAuditText(classified.commandPrefix),
|
|
140
|
+
detail: normalizeAuditText(classified.detail),
|
|
141
|
+
timestamp: normalizedTimestamp,
|
|
142
|
+
};
|
|
143
|
+
/* v8 ignore next -- normalized classified fields satisfy validEvent defensively. */
|
|
144
|
+
if (!validEvent(event))
|
|
145
|
+
return;
|
|
146
|
+
const prefix = content && !content.endsWith('\n') ? '\n' : '';
|
|
147
|
+
const addition = `${prefix}${JSON.stringify(event)}\n`;
|
|
148
|
+
if (fstatSync(descriptor).size + Buffer.byteLength(addition) > LOG_MAX_BYTES)
|
|
149
|
+
throw new Error('session-friction log is too large');
|
|
150
|
+
writeAll(descriptor, addition);
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
closeSync(descriptor);
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
export function readFrictionLog(sessionId, options) {
|
|
158
|
+
const maxEvents = eventLimit(options.maxEvents);
|
|
159
|
+
const path = logPath(sessionId, options.directory);
|
|
160
|
+
const directory = requireDirectory(options.directory);
|
|
161
|
+
if (!ensurePrivateDirectory(directory, false))
|
|
162
|
+
return { status: 'absent' };
|
|
163
|
+
try {
|
|
164
|
+
return withFileLock(path, () => {
|
|
165
|
+
/* v8 ignore next -- detects directory removal after acquiring the file lock. */
|
|
166
|
+
if (!ensurePrivateDirectory(directory, false))
|
|
167
|
+
return { status: 'absent' };
|
|
168
|
+
const descriptor = openLogFile(path, constants.O_RDONLY);
|
|
169
|
+
try {
|
|
170
|
+
const events = [];
|
|
171
|
+
for (const line of readLogContent(descriptor).split('\n')) {
|
|
172
|
+
if (!line.trim())
|
|
173
|
+
continue;
|
|
174
|
+
try {
|
|
175
|
+
const value = JSON.parse(line);
|
|
176
|
+
if (validEvent(value))
|
|
177
|
+
events.push(value);
|
|
178
|
+
}
|
|
179
|
+
catch { }
|
|
180
|
+
if (events.length >= maxEvents)
|
|
181
|
+
break;
|
|
182
|
+
}
|
|
183
|
+
return events.length ? { status: 'events', events } : { status: 'empty' };
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
closeSync(descriptor);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
|
|
192
|
+
return { status: 'absent' };
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function normalizeCommandPrefix(command: string, wrappersToStrip?: string[]): string;
|