osuite 2.14.2 → 2.15.0
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/BUSINESS_EVIDENCE.md +77 -0
- package/GOVERNED_TOOLS.md +6 -0
- package/README.md +4 -0
- package/business-evidence.mjs +139 -0
- package/cli.js +71 -23
- package/codexExec.mjs +120 -0
- package/codexTrust.mjs +107 -0
- package/credentials.js +1 -238
- package/governed-tools/executor.mjs +19 -11
- package/nativeDoctor.mjs +5 -6
- package/package.json +8 -1
- package/projectHooks.js +21 -4
- package/runtime/admission.mjs +27 -15
- package/runtime/coding-agent-facts.mjs +192 -0
- package/runtime/config.mjs +21 -12
- package/runtime/context.mjs +12 -3
- package/runtime/credentials.mjs +314 -0
- package/runtime/hook.mjs +30 -3
- package/runtime/outcome.mjs +17 -6
- package/runtime/shell.mjs +16 -2
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { posix as path } from 'node:path';
|
|
2
|
+
import { isObject } from './protocol.mjs';
|
|
3
|
+
import { isStdoutPrintf, parseShell, unwrapShellArgv } from './shell.mjs';
|
|
4
|
+
|
|
5
|
+
const FILE_READERS = new Set(['cat', 'head', 'tail', 'less', 'more', 'sed', 'awk', 'jq', 'rg', 'grep', 'base64', 'xxd', 'od', 'openssl', 'sort', 'diff']);
|
|
6
|
+
const FILE_WRITERS = new Set(['rm', 'mv', 'cp', 'install', 'chmod', 'chown', 'touch', 'mkdir', 'rmdir', 'tee', 'truncate']);
|
|
7
|
+
const FILE_COPIERS = new Set(['cp', 'install']);
|
|
8
|
+
const NETWORK_COMMANDS = new Set(['curl', 'wget', 'http', 'https', 'ftp', 'sftp', 'scp', 'ssh', 'rsync', 'nc', 'ncat']);
|
|
9
|
+
const SHELLS = new Set(['sh', 'bash', 'dash', 'zsh']);
|
|
10
|
+
const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'apply_patch']);
|
|
11
|
+
const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'ViewImage']);
|
|
12
|
+
const OPAQUE_COMMANDS = new Set(['eval', 'xargs', 'source', '.']);
|
|
13
|
+
const SECRET_PATH = /(?:^|\/)(?:\.env(?:\.(?!(?:example|sample|template)(?:\.|$))[\w.-]+)?|\.git-credentials|\.netrc|\.npmrc|\.aws\/(?:credentials|sso\/cache(?:\/.*)?)|\.ssh\/[^/]+(?<!\.pub)|\.codex\/auth\.json|\.claude\/\.credentials\.json|\.osuite-project-credentials\/.*|id_(?:rsa|ed25519|ecdsa)|[^/]+\.(?:key|p12)|etc\/(?:shadow|gshadow))(?:$|\/)/i;
|
|
14
|
+
const PROJECT_MANAGED = /(?:^|\/)(?:CLAUDE\.md|AGENTS\.md|\.claude\.md|\.mcp\.json|\.claude\/(?:CLAUDE\.md|settings(?:\.local)?\.json|hooks\/.*|rules\/.*)|\.codex\/(?:config\.toml|hooks\.json|hooks\/.*|rules\/.*)|\.cursor\/(?:hooks\.json|hooks\/.*|rules\/.*)|\.osuite\/(?:hooks\/.*|rules\/.*|config\.json))$/i;
|
|
15
|
+
const MCP_ID = /^mcp__[a-zA-Z0-9_.-]+__[a-zA-Z0-9_.-]+$/;
|
|
16
|
+
|
|
17
|
+
function strings(values) {
|
|
18
|
+
return values.filter(value => typeof value === 'string' && value.length > 0 && value.length <= 512);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function targets(argv) {
|
|
22
|
+
return strings(argv).filter(arg => !arg.startsWith('-') && !arg.includes('://'));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function copyOperands(args, operands) {
|
|
26
|
+
const flag = args.findIndex(arg => arg === '-t' || arg === '--target-directory' || arg.startsWith('--target-directory='));
|
|
27
|
+
if (flag < 0) {
|
|
28
|
+
const destination = operands.at(-1);
|
|
29
|
+
const destinationIsDirectory = operands.length > 2 || /(?:\/|\.(?:claude|codex|cursor|osuite))$/.test(destination || '');
|
|
30
|
+
return { sources: operands.slice(0, -1), destination, destinationIsDirectory };
|
|
31
|
+
}
|
|
32
|
+
const option = args[flag];
|
|
33
|
+
const inline = option.startsWith('--target-directory=');
|
|
34
|
+
const remaining = args.filter((_, index) => index !== flag && (inline || index !== flag + 1));
|
|
35
|
+
return { sources: targets(remaining), destination: inline ? option.slice('--target-directory='.length) : args[flag + 1],
|
|
36
|
+
destinationIsDirectory: true };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function readHost(value) {
|
|
40
|
+
if (typeof value !== 'string') return null;
|
|
41
|
+
try {
|
|
42
|
+
const url = new URL(value.includes('://') ? value : `https://${value}`);
|
|
43
|
+
if (!['http:', 'https:', 'ftp:', 'ssh:', 'sftp:'].includes(url.protocol) || !url.hostname) return null;
|
|
44
|
+
return { host: url.hostname.toLowerCase().replace(/\.$/, ''), pathname: url.pathname.toLowerCase() };
|
|
45
|
+
} catch { return null; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function networkFacts(values, facts) {
|
|
49
|
+
const decoded = values.map(readHost).filter(Boolean);
|
|
50
|
+
for (const { host, pathname } of decoded) {
|
|
51
|
+
facts.egress_domains.add(host);
|
|
52
|
+
if (host === 'gist.github.com' || host === 'gist.githubusercontent.com' || host === 'pastebin.com'
|
|
53
|
+
|| (host === 'api.github.com' && /^\/gists?(?:\/|$)/.test(pathname))) facts.public_relay = true;
|
|
54
|
+
}
|
|
55
|
+
if (!decoded.length || decoded.length !== values.length) facts.unresolved_egress = true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function networkArguments(executable, args, scope, facts) {
|
|
59
|
+
if (args.length === 1 && /^(?:--help|--version|-h|-V)$/.test(args[0])) return;
|
|
60
|
+
const curl = executable === 'curl';
|
|
61
|
+
const switches = curl ? /^-[fsShIiNvq]+$|^--(?:fail|silent|show-error|head|include|verbose|globoff)$/
|
|
62
|
+
: /^-[qSNv]+$|^--(?:quiet|server-response|no-verbose|spider|no-config)$/;
|
|
63
|
+
const withValue = curl ? new Set(['-X', '--request', '-o', '--output', '--max-time', '--connect-timeout', '-d', '--data', '--data-binary', '--data-raw', '--url'])
|
|
64
|
+
: new Set(['-O', '--output-document', '--timeout', '--method', '--body-data', '--max-redirect']);
|
|
65
|
+
const locations = [];
|
|
66
|
+
if (!['curl', 'wget'].includes(executable)) facts.unresolved_egress = true;
|
|
67
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
68
|
+
const arg = args[index];
|
|
69
|
+
if (!arg.startsWith('-')) { locations.push(arg); continue; }
|
|
70
|
+
if (arg === '--') { locations.push(...args.slice(index + 1)); break; }
|
|
71
|
+
if (switches.test(arg)) continue;
|
|
72
|
+
const separator = arg.indexOf('=');
|
|
73
|
+
const option = separator < 0 ? arg : arg.slice(0, separator);
|
|
74
|
+
if (!withValue.has(option)) { facts.unresolved_egress = true; continue; }
|
|
75
|
+
const value = separator < 0 ? args[++index] : arg.slice(separator + 1);
|
|
76
|
+
if (!value) { facts.unresolved_egress = true; continue; }
|
|
77
|
+
if (option === '--url') locations.push(value);
|
|
78
|
+
if (['-d', '--data', '--data-binary'].includes(option) && value.startsWith('@')) trackFile(value.slice(1), scope, facts);
|
|
79
|
+
if (['-o', '-O', '--output', '--output-document'].includes(option) && value !== '-') trackFile(value, scope, facts, true);
|
|
80
|
+
}
|
|
81
|
+
// wget follows redirects by default. Require the explicit zero-redirect posture.
|
|
82
|
+
if (executable === 'wget' && !args.includes('--max-redirect=0')) facts.unresolved_egress = true;
|
|
83
|
+
networkFacts(locations, facts);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function trackFile(raw, scope, facts, write = false) {
|
|
87
|
+
if (typeof raw !== 'string' || !raw || raw.length > 512 || raw.includes('\0') || raw.includes('://')) return;
|
|
88
|
+
const file = raw.replaceAll('\\', '/');
|
|
89
|
+
const relative = scope.root && !file.startsWith('~')
|
|
90
|
+
? path.relative(scope.root, path.resolve(scope.cwd || scope.root, file))
|
|
91
|
+
: path.normalize(file).replace(/^\.\//, '');
|
|
92
|
+
if (!write) {
|
|
93
|
+
if (SECRET_PATH.test(path.normalize(file)) || SECRET_PATH.test(relative)) facts.credential_read = true;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (PROJECT_MANAGED.test(relative) || /^~?\/(?:[^/]+\/)*\.(?:claude|codex|cursor)\/(?:settings(?:\.local)?\.json|config\.toml|hooks\.json|(?:rules|hooks)\/.*)$/i.test(file)) {
|
|
97
|
+
facts.managed_write = true;
|
|
98
|
+
}
|
|
99
|
+
if (relative && relative !== '..' && !relative.startsWith('../') && !path.isAbsolute(relative)) facts.write_paths.add(relative);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function shellFacts(command, scope, facts, depth = 0) {
|
|
103
|
+
if (!command || isStdoutPrintf(command)) return;
|
|
104
|
+
const parsed = parseShell(command);
|
|
105
|
+
for (const segment of parsed.segments) {
|
|
106
|
+
const argv = unwrapShellArgv(segment);
|
|
107
|
+
const executable = path.basename(argv[0] || '').toLowerCase();
|
|
108
|
+
const args = argv.slice(1);
|
|
109
|
+
const operands = targets(args);
|
|
110
|
+
if (!executable || OPAQUE_COMMANDS.has(executable)) facts.opaque_dispatch = true;
|
|
111
|
+
if (SHELLS.has(executable)) {
|
|
112
|
+
const flag = args.findIndex(arg => /^-[a-z]*c$/.test(arg));
|
|
113
|
+
if (flag >= 0 && args[flag + 1] && depth < 4) shellFacts(args[flag + 1], scope, facts, depth + 1);
|
|
114
|
+
else if (args.length || parsed.segments.length > 1) facts.opaque_dispatch = true;
|
|
115
|
+
}
|
|
116
|
+
if ((/^(?:python[23]?|node|ruby|perl|deno)$/.test(executable) && args.some(arg => /^-(?:c|e|p|E)$|^--eval(?:=|$)/.test(arg)))
|
|
117
|
+
|| (executable === 'find' && args.some(arg => /^-exec(?:dir)?$/.test(arg)))) facts.opaque_dispatch = true;
|
|
118
|
+
if ((executable === 'cd' || executable === 'pushd') && parsed.segments.length > 1) facts.opaque_dispatch = true;
|
|
119
|
+
if (NETWORK_COMMANDS.has(executable)) networkArguments(executable, args, scope, facts);
|
|
120
|
+
if (NETWORK_COMMANDS.has(executable) && parsed.errors.length > 0) facts.unresolved_egress = true;
|
|
121
|
+
if (executable === 'gh' && (args[0] === 'gist' || args[0] === 'api' && args.some(arg => /(?:^|\/)gists?(?:\b|\/)/.test(arg)))) {
|
|
122
|
+
facts.public_relay = true;
|
|
123
|
+
}
|
|
124
|
+
if (executable === 'git' && args.some(arg => ['clone', 'fetch', 'pull', 'push'].includes(arg))) {
|
|
125
|
+
const locations = args.filter(arg => /^(?:https?|ssh):\/\//i.test(arg));
|
|
126
|
+
if (locations.length) networkFacts(locations, facts);
|
|
127
|
+
}
|
|
128
|
+
if (FILE_READERS.has(executable)) {
|
|
129
|
+
for (const operand of operands) trackFile(operand.split(/[<>]/)[0], scope, facts);
|
|
130
|
+
if (parsed.errors.includes('unsupported_glob_expansion') && args.some(arg => /(?:^|\/)\.(?:env|aws|ssh)[\w.*?/-]*/.test(arg))) {
|
|
131
|
+
facts.credential_read = true;
|
|
132
|
+
}
|
|
133
|
+
if (args.some(arg => arg.includes('$'))) facts.opaque_dispatch = true;
|
|
134
|
+
}
|
|
135
|
+
const inPlace = executable === 'sed' && args.some(arg => /^-i|^--in-place(?:=|$)/.test(arg));
|
|
136
|
+
if (FILE_COPIERS.has(executable) && !(executable === 'install' && args.some(arg => arg === '-d' || arg === '--directory'))) {
|
|
137
|
+
const { sources, destination, destinationIsDirectory } = copyOperands(args, operands);
|
|
138
|
+
for (const source of sources) trackFile(source, scope, facts);
|
|
139
|
+
trackFile(destination, scope, facts, true);
|
|
140
|
+
if (destination && destinationIsDirectory) {
|
|
141
|
+
for (const source of sources) trackFile(path.join(destination, path.basename(source)), scope, facts, true);
|
|
142
|
+
}
|
|
143
|
+
} else if (FILE_WRITERS.has(executable) || inPlace) {
|
|
144
|
+
for (const operand of operands) trackFile(operand, scope, facts, true);
|
|
145
|
+
}
|
|
146
|
+
// Redirect operands appear as ordinary tokens in the conservative shell parser.
|
|
147
|
+
if (parsed.errors.includes('unsupported_shell_syntax')) {
|
|
148
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
149
|
+
const redirect = /^[0-9]*([<>]+)(.*)$/.exec(args[index]) || /([<>]+)(.*)$/.exec(args[index]);
|
|
150
|
+
if (redirect) trackFile(redirect[2] || args[index + 1], scope, facts, redirect[1].startsWith('>'));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const rmFlags = args.slice(0, args.includes('--') ? args.indexOf('--') : undefined);
|
|
154
|
+
const recursive = rmFlags.some(arg => arg === '--recursive' || /^-[^-]*[rR]/.test(arg));
|
|
155
|
+
const force = rmFlags.some(arg => arg === '--force' || /^-[^-]*f/.test(arg));
|
|
156
|
+
if (executable === 'rm' && recursive && force && operands.some(file => {
|
|
157
|
+
if (!scope.root || file.startsWith('~') || /[\$*`?\[]/.test(file)) return true;
|
|
158
|
+
const target = path.relative(scope.root, path.resolve(scope.cwd || scope.root, file));
|
|
159
|
+
return !target || target === '..' || target.startsWith('../');
|
|
160
|
+
})) facts.destructive = true;
|
|
161
|
+
const globalOptions = new Set(['-n', '--namespace', '--context', '--kubeconfig', '--server', '--cluster', '--user']);
|
|
162
|
+
const op = args.find((arg, index) => !arg.startsWith('-') && !globalOptions.has(args[index - 1]));
|
|
163
|
+
if ((executable === 'kubectl' && op === 'delete') || (executable === 'terraform' && op === 'destroy')) facts.destructive = true;
|
|
164
|
+
}
|
|
165
|
+
if (parsed.errors.includes('unsupported_expansion') && /\$\(|`|<\(|>\(/.test(command)) facts.opaque_dispatch = true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function extractCodingAgentFacts({ tool_name: tool, tool_input: value, cwd }, workspaceRoot) {
|
|
169
|
+
const input = isObject(value) ? value : {};
|
|
170
|
+
const facts = { schema_version: 'osuite.coding_agent_facts.v1', egress_domains: new Set(), write_paths: new Set() };
|
|
171
|
+
const scope = { root: typeof workspaceRoot === 'string' && path.isAbsolute(workspaceRoot) ? path.normalize(workspaceRoot) : '', cwd };
|
|
172
|
+
if (['Bash', 'Shell', 'exec_command'].includes(tool)) shellFacts(typeof input.command === 'string' ? input.command : '', scope, facts);
|
|
173
|
+
if (typeof tool === 'string' && tool.startsWith('mcp__')) {
|
|
174
|
+
facts.mcp_tool = MCP_ID.test(tool) ? tool : 'unresolved';
|
|
175
|
+
for (const target of strings([input.path, input.file_path, input.notebook_path])) trackFile(target, scope, facts);
|
|
176
|
+
}
|
|
177
|
+
if (['WebFetch', 'WebSearch', 'web.fetch', 'web.post', 'HttpRequest'].includes(tool)) {
|
|
178
|
+
networkFacts(strings([input.url, input.uri, ...(Array.isArray(input.allowed_domains) ? input.allowed_domains : [])]), facts);
|
|
179
|
+
} else if (facts.mcp_tool && (typeof input.url === 'string' || typeof input.uri === 'string')) {
|
|
180
|
+
networkFacts(strings([input.url, input.uri]), facts);
|
|
181
|
+
}
|
|
182
|
+
if (READ_TOOLS.has(tool) || WRITE_TOOLS.has(tool)) {
|
|
183
|
+
for (const target of strings([input.path, input.file_path, input.notebook_path])) trackFile(target, scope, facts, WRITE_TOOLS.has(tool));
|
|
184
|
+
}
|
|
185
|
+
if (tool === 'apply_patch') {
|
|
186
|
+
const patch = [value, input.patch, input.input, input.diff, input.command].find(item => typeof item === 'string') || '';
|
|
187
|
+
for (const match of patch.matchAll(/^\*\*\* (?:Update File|Delete File|Add File|Move to): (.+)$/gm)) trackFile(match[1].trim(), scope, facts, true);
|
|
188
|
+
}
|
|
189
|
+
if (facts.egress_domains.size > 32) facts.unresolved_egress = true;
|
|
190
|
+
if (facts.write_paths.size > 32) facts.opaque_dispatch = true;
|
|
191
|
+
return { ...facts, egress_domains: [...facts.egress_domains].sort().slice(0, 32), write_paths: [...facts.write_paths].sort().slice(0, 32) };
|
|
192
|
+
}
|
package/runtime/config.mjs
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
|
|
4
|
+
import { readCredentialFile } from './credentials.mjs';
|
|
5
|
+
|
|
6
|
+
function parseDotenv(body) {
|
|
7
|
+
const values = {};
|
|
8
|
+
for (const line of (body || '').split(/\r?\n/)) {
|
|
9
|
+
const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
10
|
+
if (!match) continue;
|
|
11
|
+
let value = match[2];
|
|
12
|
+
if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
|
|
13
|
+
else value = value.replace(/\s+#.*$/, '');
|
|
14
|
+
values[match[1]] = value;
|
|
15
|
+
}
|
|
16
|
+
return values;
|
|
17
|
+
}
|
|
4
18
|
|
|
5
19
|
function readDotenv(installDir, filename = '.env') {
|
|
6
20
|
let fd;
|
|
@@ -8,16 +22,7 @@ function readDotenv(installDir, filename = '.env') {
|
|
|
8
22
|
fd = openSync(path.join(installDir, filename), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | constants.O_NONBLOCK);
|
|
9
23
|
const stat = fstatSync(fd);
|
|
10
24
|
if (!stat.isFile() || stat.size > 65536) return {};
|
|
11
|
-
|
|
12
|
-
for (const line of readFileSync(fd, 'utf8').split(/\r?\n/)) {
|
|
13
|
-
const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
14
|
-
if (!match) continue;
|
|
15
|
-
let value = match[2];
|
|
16
|
-
if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
|
|
17
|
-
else value = value.replace(/\s+#.*$/, '');
|
|
18
|
-
values[match[1]] = value;
|
|
19
|
-
}
|
|
20
|
-
return values;
|
|
25
|
+
return parseDotenv(readFileSync(fd, 'utf8'));
|
|
21
26
|
} catch { return {}; }
|
|
22
27
|
finally { if (fd !== undefined) closeSync(fd); }
|
|
23
28
|
}
|
|
@@ -25,7 +30,11 @@ function readDotenv(installDir, filename = '.env') {
|
|
|
25
30
|
export function loadRuntimeConfig({ installDir, env = process.env, host = 'claude', runtimeId } = {}) {
|
|
26
31
|
const plugin = runtimeId === 'codex_plugin';
|
|
27
32
|
const hardened = plugin || host === 'cursor';
|
|
28
|
-
const
|
|
33
|
+
const directory = installDir && path.basename(path.resolve(installDir));
|
|
34
|
+
const project = !plugin && directory === `.${host}`;
|
|
35
|
+
const dotenv = project ? parseDotenv(readCredentialFile(path.dirname(path.resolve(installDir)), `${directory}/.env`, { maxBytes: 65536, checkGit: false }))
|
|
36
|
+
: installDir ? readDotenv(installDir) : {};
|
|
37
|
+
const source = { ...dotenv, ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
|
|
29
38
|
const get = (name, fallback = '') => source[`OSUITE_${name}`] ?? source[`DASHCLAW_${name}`] ?? fallback;
|
|
30
39
|
const number = (name, fallback, min, max) => {
|
|
31
40
|
const value = Number(get(name, fallback));
|
|
@@ -34,7 +43,7 @@ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claud
|
|
|
34
43
|
const requestedMode = get('HOOK_MODE', host === 'cursor' ? 'observe' : 'enforce');
|
|
35
44
|
const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
|
|
36
45
|
return {
|
|
37
|
-
host,
|
|
46
|
+
host, projectRoot: project ? path.dirname(path.resolve(installDir)) : undefined,
|
|
38
47
|
ruleRolloutCapability: get('SCOPED_RULE_ROLLOUT') === '1' ? RULE_ROLLOUT_CAPABILITY : undefined,
|
|
39
48
|
runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
|
|
40
49
|
agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
|
package/runtime/context.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { canonicalJson, isObject, safeId, sha256, toolInputDigest } from './protocol.mjs';
|
|
2
|
-
import { classifyShell } from './shell.mjs';
|
|
2
|
+
import { classifyShell, isStdoutPrintf } from './shell.mjs';
|
|
3
3
|
import { collectGitPublication } from './git.mjs';
|
|
4
|
+
import { extractCodingAgentFacts } from './coding-agent-facts.mjs';
|
|
4
5
|
|
|
5
6
|
const contentKeys = new Set(['content', 'new_string', 'old_string', 'new_source', 'old_source', 'file_text', 'patch', 'diff', 'input']);
|
|
6
7
|
const publicHosts = new Set(['file.io', 'transfer.sh', '0x0.st', 'pastebin.com', 'gofile.io', 'wetransfer.com', 'tmpfiles.org']);
|
|
@@ -91,7 +92,7 @@ export function buildActionContext(data, config) {
|
|
|
91
92
|
if (publication) mapped.summary.git_publication = publication;
|
|
92
93
|
// Keep the reference externality hints in addition to structural shell semantics.
|
|
93
94
|
const external = genericContext(tool, input, config.captureToolInput);
|
|
94
|
-
if (external.summary.destination_type || external.sensitive_data_categories?.length) {
|
|
95
|
+
if (!isStdoutPrintf(objectInput.command) && (external.summary.destination_type || external.sensitive_data_categories?.length)) {
|
|
95
96
|
mapped = { ...external, ...mapped, risk_score: Math.max(mapped.risk_score, external.risk_score), summary: { ...external.summary, ...mapped.summary } };
|
|
96
97
|
}
|
|
97
98
|
} else if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch'].includes(tool)) {
|
|
@@ -110,13 +111,21 @@ export function buildActionContext(data, config) {
|
|
|
110
111
|
}
|
|
111
112
|
if (goal.length > 2000) throw new Error('Tool evidence exceeds declared_goal schema; not truncated');
|
|
112
113
|
const { summary, reversible, ...fields } = mapped;
|
|
114
|
+
const facts = extractCodingAgentFacts({ ...data, cwd: objectInput.workdir || objectInput.working_directory || data.cwd }, config.projectRoot || data.cwd);
|
|
113
115
|
const signal = autonomySignal(data, config);
|
|
114
116
|
const context = { ...fields, ...(typeof reversible === 'boolean' ? { reversible } : {}), agent_id: config.agentId, declared_goal: goal,
|
|
115
117
|
runtime_session_id: deriveSessionId(data, config), tool_use_id: deriveToolUseId(data), tool_input_digest: toolInputDigest(tool, input),
|
|
116
118
|
runtime_family: 'tool_hook_runtime', adapter_mode: 'hook', install_channel: config.installChannel, settings_scope: config.settingsScope,
|
|
117
119
|
trusted_project_required: config.trustedProjectRequired === true, ...signal,
|
|
118
|
-
input_summary: JSON.stringify({ ...summary, ...signal,
|
|
120
|
+
input_summary: JSON.stringify({ ...summary, ...signal, coding_agent_facts: facts,
|
|
121
|
+
runtime_adapter_id: config.runtimeId, runtime_family: 'tool_hook_runtime', adapter_mode: 'hook' }) };
|
|
119
122
|
if (context.input_summary.length > 4000 || context.tool_use_id.length > 128 || !safeId(context.tool_use_id)) throw new Error('Tool evidence exceeds action schema; not truncated');
|
|
123
|
+
if (data.business_authority_assertion !== undefined) {
|
|
124
|
+
if (!isObject(data.business_authority_assertion) || Buffer.byteLength(canonicalJson(data.business_authority_assertion)) > 8192) {
|
|
125
|
+
throw new Error('Invalid business authority evidence');
|
|
126
|
+
}
|
|
127
|
+
context.business_authority_assertion = data.business_authority_assertion;
|
|
128
|
+
}
|
|
120
129
|
if (config.installCheck) context.health_check = true;
|
|
121
130
|
return context;
|
|
122
131
|
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
|
|
7
|
+
export const CREDENTIAL_PATHS = ['.codex/.env', '.claude/.env', '.cursor/.env', '.osuite/.env'];
|
|
8
|
+
const POSIX = process.platform !== 'win32';
|
|
9
|
+
const NOFOLLOW = fs.constants.O_NOFOLLOW || 0;
|
|
10
|
+
|
|
11
|
+
function metadata(file) {
|
|
12
|
+
try { return fs.lstatSync(file); } catch (error) {
|
|
13
|
+
if (error.code === 'ENOENT') return null;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function sameFile(a, b) {
|
|
19
|
+
return !a && !b || Boolean(a && b && a.dev === b.dev && a.ino === b.ino && a.size === b.size
|
|
20
|
+
&& a.mode === b.mode && a.uid === b.uid && a.nlink === b.nlink
|
|
21
|
+
&& a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function owned(stat) {
|
|
25
|
+
return !POSIX || typeof process.getuid !== 'function' || stat.uid === process.getuid();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function credentialPathError(code, message) {
|
|
29
|
+
return Object.assign(new Error(message), { code });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function projectPath(root, relativePath) {
|
|
33
|
+
const absolute = path.resolve(root, relativePath);
|
|
34
|
+
const relative = path.relative(root, absolute);
|
|
35
|
+
if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
|
|
36
|
+
throw credentialPathError('CREDENTIAL_PATH_UNSAFE', 'Credential path must stay inside the project.');
|
|
37
|
+
}
|
|
38
|
+
return relative;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function checkDirectory(directory, { create = false, privateMode = false, allowGroupWrite = false } = {}) {
|
|
42
|
+
let stat = metadata(directory);
|
|
43
|
+
if (!stat && create) {
|
|
44
|
+
try {
|
|
45
|
+
fs.mkdirSync(directory, { mode: 0o700 });
|
|
46
|
+
syncDirectory(path.dirname(directory));
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error.code !== 'EEXIST') throw error;
|
|
49
|
+
}
|
|
50
|
+
stat = metadata(directory);
|
|
51
|
+
}
|
|
52
|
+
if (!stat) return null;
|
|
53
|
+
if (!stat.isDirectory()) throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Expected a real directory (no symlinks): ${directory}`);
|
|
54
|
+
if (!owned(stat) || POSIX && (stat.mode & (allowGroupWrite ? 0o002 : 0o022))) {
|
|
55
|
+
throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Unsafe credential directory ownership or write permissions: ${directory}. Use a user-owned workspace and remove write access for others from credential storage.`);
|
|
56
|
+
}
|
|
57
|
+
if (POSIX && privateMode && (stat.mode & 0o777) !== 0o700) {
|
|
58
|
+
throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Private credential directory must have mode 0700: ${directory}`);
|
|
59
|
+
}
|
|
60
|
+
return stat;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function sharedProjectRoot(root, stat, relative, create) {
|
|
64
|
+
// A group-writable parent can rename even a 0700 child. Keep the secrets in
|
|
65
|
+
// a different, user-controlled tree and bind that slot to this project inode.
|
|
66
|
+
let current = root;
|
|
67
|
+
for (const part of relative.split(path.sep).slice(0, -1)) {
|
|
68
|
+
current = path.join(current, part);
|
|
69
|
+
if (!checkDirectory(current, { allowGroupWrite: true })) break;
|
|
70
|
+
}
|
|
71
|
+
if (metadata(path.join(root, relative))) {
|
|
72
|
+
throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Existing credential path in a group-writable project: ${relative}. Secure the project directory before inspecting the file, or remove it and reconnect to rotate the credentials.`);
|
|
73
|
+
}
|
|
74
|
+
if (!/^\.(?:codex|claude|cursor|osuite)\//.test(relative.split(path.sep).join('/'))) {
|
|
75
|
+
if (create) throw credentialPathError('CREDENTIAL_PATH_UNSAFE', 'Use osuite connect to save credentials in private storage for this team project.');
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
const home = fs.realpathSync(os.homedir());
|
|
79
|
+
checkDirectory(home);
|
|
80
|
+
for (let parent = path.dirname(home); parent !== home; parent = path.dirname(parent)) {
|
|
81
|
+
const ancestor = metadata(parent);
|
|
82
|
+
const trustedSticky = ancestor?.uid === 0 && (ancestor.mode & 0o1000);
|
|
83
|
+
if (!ancestor?.isDirectory() || (!owned(ancestor) && ancestor.uid !== 0) || (ancestor.mode & 0o022) && !trustedSticky) {
|
|
84
|
+
throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Private credential storage requires a protected home directory: ${home}`);
|
|
85
|
+
}
|
|
86
|
+
if (parent === path.dirname(parent)) break;
|
|
87
|
+
}
|
|
88
|
+
const storage = path.join(home, '.osuite-project-credentials');
|
|
89
|
+
const identity = crypto.createHash('sha256').update(JSON.stringify([root, stat.dev, stat.ino])).digest('hex');
|
|
90
|
+
const privateRoot = path.join(storage, identity);
|
|
91
|
+
if (!checkDirectory(storage, { create, privateMode: true }) || !checkDirectory(privateRoot, { create, privateMode: true })) return null;
|
|
92
|
+
return privateRoot;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function safePath(projectRoot, relativePath, { create = false } = {}) {
|
|
96
|
+
const project = fs.realpathSync(projectRoot);
|
|
97
|
+
const relative = projectPath(project, relativePath);
|
|
98
|
+
const projectStat = checkDirectory(project, { allowGroupWrite: true });
|
|
99
|
+
const shared = POSIX && (projectStat.mode & 0o020) !== 0;
|
|
100
|
+
const root = shared ? sharedProjectRoot(project, projectStat, relative, create) : project;
|
|
101
|
+
const logicalPath = relative.split(path.sep).join('/');
|
|
102
|
+
if (!root) return { project, relativePath: logicalPath, stat: null };
|
|
103
|
+
const absolute = path.join(root, relative);
|
|
104
|
+
let directory = root;
|
|
105
|
+
for (const part of relative.split(path.sep).slice(0, -1)) {
|
|
106
|
+
directory = path.join(directory, part);
|
|
107
|
+
if (!checkDirectory(directory, { create, privateMode: shared })) break;
|
|
108
|
+
}
|
|
109
|
+
const stat = metadata(absolute);
|
|
110
|
+
if (stat?.isSymbolicLink()) throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Refusing a symlinked credential file: ${logicalPath}`);
|
|
111
|
+
if (stat && (!stat.isFile() || stat.nlink !== 1 || !owned(stat))) {
|
|
112
|
+
throw credentialPathError('CREDENTIAL_PATH_UNSAFE', `Unsafe credential file type, links, or ownership: ${logicalPath}`);
|
|
113
|
+
}
|
|
114
|
+
return { root, project, absolute, relativePath: logicalPath, stat };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function runGit(cwd, args) {
|
|
118
|
+
// Inherited GIT_DIR/INDEX_FILE must not hide a tracked project credential.
|
|
119
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
|
|
120
|
+
// Metadata inspection must not execute repository-configured fsmonitor commands.
|
|
121
|
+
return spawnSync('git', ['-c', 'core.fsmonitor=false', '-C', cwd, ...args], {
|
|
122
|
+
encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'],
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function repositoryRoots(root, absolute) {
|
|
127
|
+
const roots = new Set();
|
|
128
|
+
let current = root;
|
|
129
|
+
for (const part of ['', ...path.relative(root, path.dirname(absolute)).split(path.sep).filter(Boolean)]) {
|
|
130
|
+
if (part) current = path.join(current, part);
|
|
131
|
+
if (!metadata(current)) continue;
|
|
132
|
+
const result = runGit(current, ['rev-parse', '--show-toplevel']);
|
|
133
|
+
if (result.error) throw new Error('Git is required to check whether the credential path is tracked.');
|
|
134
|
+
if (result.status === 0) roots.add(result.stdout.trim());
|
|
135
|
+
else if (!result.stderr.includes('not a git repository')) throw new Error('Unable to verify Git credential protection.');
|
|
136
|
+
}
|
|
137
|
+
return [...roots];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function isTracked(root, absolute) {
|
|
141
|
+
return repositoryRoots(root, absolute).some((repository) => {
|
|
142
|
+
// A tracked .ENV aliases .env on common macOS/Windows filesystems.
|
|
143
|
+
const result = runGit(repository, ['ls-files', '--error-unmatch', '--', `:(icase,literal)${path.relative(repository, absolute)}`]);
|
|
144
|
+
if (result.status !== 0 && result.status !== 1) throw new Error('Unable to inspect the Git index for credentials.');
|
|
145
|
+
return result.status === 0;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function assertUntracked(target) {
|
|
150
|
+
if (isTracked(target.root, target.absolute)) throw new Error('Refusing to write credentials to a tracked path. Remove it from Git and rotate any exposed credentials first.');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function syncDirectory(directory) {
|
|
154
|
+
if (!POSIX) return;
|
|
155
|
+
const fd = fs.openSync(directory, fs.constants.O_RDONLY | (fs.constants.O_DIRECTORY || 0) | NOFOLLOW);
|
|
156
|
+
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function atomicWrite(target, body, mode, { credential = false } = {}) {
|
|
160
|
+
const temporary = `${target.absolute}.osuite-tmp-${crypto.randomBytes(12).toString('hex')}`;
|
|
161
|
+
let fd;
|
|
162
|
+
try {
|
|
163
|
+
fd = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, mode);
|
|
164
|
+
if (POSIX) fs.fchmodSync(fd, mode);
|
|
165
|
+
fs.writeFileSync(fd, body, 'utf8');
|
|
166
|
+
fs.fsyncSync(fd);
|
|
167
|
+
fs.closeSync(fd);
|
|
168
|
+
fd = undefined;
|
|
169
|
+
const latest = safePath(target.project, target.relativePath);
|
|
170
|
+
if (latest.absolute !== target.absolute || !sameFile(target.stat, latest.stat)) throw new Error('Credential destination changed during the write; refusing to replace it.');
|
|
171
|
+
if (credential) assertUntracked(latest);
|
|
172
|
+
fs.renameSync(temporary, target.absolute);
|
|
173
|
+
syncDirectory(path.dirname(target.absolute));
|
|
174
|
+
} finally {
|
|
175
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
176
|
+
try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function protectIgnore(target) {
|
|
181
|
+
const directory = path.dirname(target.absolute);
|
|
182
|
+
const ignorePath = path.join(path.dirname(target.relativePath), '.gitignore');
|
|
183
|
+
const ignore = safePath(target.root, ignorePath);
|
|
184
|
+
const body = ignore.stat ? fs.readFileSync(ignore.absolute, 'utf8') : '';
|
|
185
|
+
const name = path.basename(target.absolute);
|
|
186
|
+
// A rule in the credential's own directory works in monorepos and nested repos.
|
|
187
|
+
const rules = [`/${name}`, `/${name}.osuite-tmp-*`];
|
|
188
|
+
const missing = rules.filter((rule) => !body.split(/\r?\n/).includes(rule));
|
|
189
|
+
if (missing.length) {
|
|
190
|
+
atomicWrite(ignore, `${body}${body && !body.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`, ignore.stat ? ignore.stat.mode & 0o777 : 0o644);
|
|
191
|
+
}
|
|
192
|
+
if (repositoryRoots(target.root, target.absolute).length) {
|
|
193
|
+
const result = runGit(directory, ['check-ignore', '--no-index', '--', target.absolute]);
|
|
194
|
+
if (result.status !== 0) throw new Error('Credential path is not ignored by Git; check conflicting ignore rules.');
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function inspectCredentialFile(projectRoot, relativePath) {
|
|
199
|
+
const result = { relativePath, exists: false, safe: false, problems: [], mode: null, storagePath: relativePath };
|
|
200
|
+
try {
|
|
201
|
+
const target = safePath(projectRoot, relativePath);
|
|
202
|
+
result.storagePath = target.root && target.root !== target.project ? target.absolute : relativePath;
|
|
203
|
+
result.exists = Boolean(target.stat);
|
|
204
|
+
if (target.stat) {
|
|
205
|
+
result.mode = POSIX ? (target.stat.mode & 0o7777).toString(8).padStart(4, '0') : null;
|
|
206
|
+
if (POSIX && (target.stat.mode & 0o7777) !== 0o600) result.problems.push(`unsafe mode ${result.mode}; expected 0600. Set mode 0600 and rotate if the credential was exposed`);
|
|
207
|
+
}
|
|
208
|
+
if (target.absolute && isTracked(target.root, target.absolute)) result.problems.push('tracked by Git');
|
|
209
|
+
if (target.stat) {
|
|
210
|
+
const roots = repositoryRoots(target.root, target.absolute);
|
|
211
|
+
if (roots.length && runGit(path.dirname(target.absolute), ['check-ignore', '--no-index', '--', target.absolute]).status !== 0) result.problems.push('not ignored by Git');
|
|
212
|
+
}
|
|
213
|
+
result.safe = result.problems.length === 0;
|
|
214
|
+
} catch (error) {
|
|
215
|
+
result.problems.push(error.message);
|
|
216
|
+
}
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function prepareCredentialFile(projectRoot, relativePath) {
|
|
221
|
+
let target = safePath(projectRoot, relativePath);
|
|
222
|
+
if (target.absolute) assertUntracked(target);
|
|
223
|
+
target = safePath(projectRoot, relativePath, { create: true });
|
|
224
|
+
assertUntracked(target);
|
|
225
|
+
if (target.stat && POSIX && (target.stat.mode & 0o022)) {
|
|
226
|
+
throw credentialPathError('CREDENTIAL_FILE_PERMISSIONS', 'Credential file is writable by others: set mode 0600 and rotate the credential.');
|
|
227
|
+
}
|
|
228
|
+
protectIgnore(target);
|
|
229
|
+
return target;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function writeCredentialFile(projectRoot, relativePath, body, options = {}) {
|
|
233
|
+
const target = prepareCredentialFile(projectRoot, relativePath);
|
|
234
|
+
// Interactive callers must not adopt a newer operator edit at this handoff.
|
|
235
|
+
if (Object.hasOwn(options, 'expectedStat') && !sameFile(options.expectedStat, target.stat)) {
|
|
236
|
+
throw new Error('Credential destination changed since it was read; refusing to replace it.');
|
|
237
|
+
}
|
|
238
|
+
atomicWrite(target, String(body), 0o600, { credential: true });
|
|
239
|
+
return { relativePath: target.root === target.project ? target.relativePath : target.absolute, status: 'written' };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function assertPrivateFile(stat) {
|
|
243
|
+
if (stat && POSIX && (stat.mode & 0o7777) !== 0o600) {
|
|
244
|
+
throw credentialPathError('CREDENTIAL_FILE_PERMISSIONS', 'Unsafe credential file mode: set mode 0600 and rotate if the credential was exposed.');
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function readCredentialFile(projectRoot, relativePath, { maxBytes = Infinity, checkGit = true } = {}) {
|
|
249
|
+
const target = safePath(projectRoot, relativePath);
|
|
250
|
+
if (!target.stat) return null;
|
|
251
|
+
assertPrivateFile(target.stat);
|
|
252
|
+
if (checkGit) {
|
|
253
|
+
const inspection = inspectCredentialFile(projectRoot, relativePath);
|
|
254
|
+
if (!inspection.safe) throw credentialPathError('CREDENTIAL_FILE_UNSAFE', `Unsafe credential file: ${relativePath} (${inspection.problems.join('; ')}).`);
|
|
255
|
+
}
|
|
256
|
+
const fd = fs.openSync(target.absolute, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | NOFOLLOW);
|
|
257
|
+
try {
|
|
258
|
+
const stat = fs.fstatSync(fd);
|
|
259
|
+
if (!sameFile(target.stat, stat)) throw credentialPathError('CREDENTIAL_FILE_CHANGED', 'Credential changed before reading.');
|
|
260
|
+
if (stat.size > maxBytes) throw credentialPathError('INVALID_CREDENTIAL_FILE', 'Credential exceeds the maximum file size.');
|
|
261
|
+
return fs.readFileSync(fd, 'utf8');
|
|
262
|
+
} finally { fs.closeSync(fd); }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function removeCredentialFile(projectRoot, relativePath) {
|
|
266
|
+
const target = safePath(projectRoot, relativePath);
|
|
267
|
+
if (!target.stat) return;
|
|
268
|
+
assertUntracked(target);
|
|
269
|
+
fs.unlinkSync(target.absolute);
|
|
270
|
+
syncDirectory(path.dirname(target.absolute));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function acquireCredentialLock(projectRoot, relativePath) {
|
|
274
|
+
prepareCredentialFile(projectRoot, relativePath);
|
|
275
|
+
const lockPath = `${relativePath}.connect.lock`;
|
|
276
|
+
let target = prepareCredentialFile(projectRoot, lockPath);
|
|
277
|
+
if (target.stat) {
|
|
278
|
+
let lock;
|
|
279
|
+
try { lock = JSON.parse(readCredentialFile(projectRoot, lockPath)); } catch {
|
|
280
|
+
throw new Error('Unsafe or unreadable credential lock; inspect its metadata before reconnecting.');
|
|
281
|
+
}
|
|
282
|
+
if (!Number.isSafeInteger(lock?.pid) || lock.pid < 1) throw new Error('Invalid credential lock.');
|
|
283
|
+
let running = true;
|
|
284
|
+
try { process.kill(lock.pid, 0); } catch (error) { if (error.code === 'ESRCH') running = false; }
|
|
285
|
+
if (running) throw new Error('Another connect process owns this credential file. Wait for it to finish.');
|
|
286
|
+
const latest = safePath(projectRoot, lockPath);
|
|
287
|
+
if (!sameFile(target.stat, latest.stat)) throw new Error('Credential lock changed during recovery.');
|
|
288
|
+
removeCredentialFile(projectRoot, lockPath);
|
|
289
|
+
target = prepareCredentialFile(projectRoot, lockPath);
|
|
290
|
+
}
|
|
291
|
+
let fd;
|
|
292
|
+
let lockStat;
|
|
293
|
+
try {
|
|
294
|
+
fd = fs.openSync(target.absolute, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW, 0o600);
|
|
295
|
+
if (POSIX) fs.fchmodSync(fd, 0o600);
|
|
296
|
+
fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid })}\n`, 'utf8');
|
|
297
|
+
fs.fsyncSync(fd);
|
|
298
|
+
lockStat = fs.fstatSync(fd);
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (error.code === 'EEXIST') throw new Error('Another connect process owns this credential file.');
|
|
301
|
+
throw error;
|
|
302
|
+
} finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
303
|
+
syncDirectory(path.dirname(target.absolute));
|
|
304
|
+
let released = false;
|
|
305
|
+
const release = () => {
|
|
306
|
+
if (released) return;
|
|
307
|
+
released = true;
|
|
308
|
+
process.removeListener('exit', release);
|
|
309
|
+
const latest = safePath(projectRoot, lockPath);
|
|
310
|
+
if (sameFile(lockStat, latest.stat)) removeCredentialFile(projectRoot, lockPath);
|
|
311
|
+
};
|
|
312
|
+
process.once('exit', release);
|
|
313
|
+
return release;
|
|
314
|
+
}
|