@causyne/agent 1.20.118 → 1.20.121
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 +1 -1
- package/src/agent/errorClassifier.js +113 -0
- package/src/agent/errorClassifier.ts +161 -0
- package/src/agent/promptIntent.js +200 -0
- package/src/agent/promptIntent.ts +203 -0
- package/src/agent/toolArgValidator.js +97 -0
- package/src/agent/toolArgValidator.ts +112 -0
- package/src/agentLoop.js +51 -351
- package/src/agentLoop.ts +69 -363
- package/src/autoUpdate.js +111 -8
- package/src/autoUpdate.ts +144 -8
- package/src/browser/causyneBrowser.js +231 -136
- package/src/browser/causyneBrowser.ts +229 -140
- package/src/browser/searchProviders.js +41 -30
- package/src/browser/searchProviders.ts +24 -14
- package/src/browser/workspacePathSafety.js +50 -0
- package/src/browser/workspacePathSafety.ts +50 -0
- package/src/browser/workspacePreview.js +27 -4
- package/src/browser/workspacePreview.ts +28 -4
- package/src/cliMode.js +17 -3
- package/src/commands.js +15 -22
- package/src/config.js +42 -63
- package/src/configVault.js +204 -0
- package/src/configVault.ts +213 -0
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/creative/liveBridge.js +34 -1
- package/src/creative/liveBridge.ts +28 -1
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +304 -0
- package/src/headlessCli.ts +380 -0
- package/src/mcp/mcpClient.js +38 -11
- package/src/mcp/mcpClient.ts +44 -11
- package/src/mcp/mcpRegistry.js +2 -5
- package/src/mcp/mcpRegistry.ts +2 -5
- package/src/mcp/mcpSecurity.js +189 -0
- package/src/mcp/mcpSecurity.ts +190 -0
- package/src/observer/evidence.js +23 -0
- package/src/observer/evidence.ts +21 -0
- package/src/osKeychain.js +209 -0
- package/src/osKeychain.ts +245 -0
- package/src/providers/anthropic.js +61 -28
- package/src/providers/base.js +14 -0
- package/src/providers/byokHttp.js +354 -0
- package/src/providers/byokHttp.ts +454 -0
- package/src/providers/byokStream.js +657 -0
- package/src/providers/byokStream.ts +759 -0
- package/src/providers/dashscope-byok.js +47 -32
- package/src/providers/deepseek.js +43 -39
- package/src/providers/gemini.js +73 -38
- package/src/providers/moonshot.js +43 -33
- package/src/providers/muse.js +10 -10
- package/src/providers/ollama.js +46 -31
- package/src/providers/openai-compatible.js +57 -32
- package/src/providers/openrouter.js +77 -113
- package/src/providers/openrouter.ts +99 -118
- package/src/providers/qwen-byok.js +46 -23
- package/src/providers/toolContracts.js +9 -3
- package/src/providers/toolContracts.ts +9 -3
- package/src/providers/wireNormalizer.js +238 -0
- package/src/providers/wireNormalizer.ts +279 -0
- package/src/providers/xai.js +43 -33
- package/src/sandbox.js +77 -56
- package/src/sandboxPolicy.js +1208 -0
- package/src/sandboxPolicy.ts +1300 -0
- package/src/sessionJournal.js +47 -0
- package/src/sessionJournal.ts +49 -0
- package/src/tools/browserAutomator.js +13 -1
- package/src/tools/browserAutomator.ts +13 -0
- package/src/tools/creativeApps.js +2 -1
- package/src/tools/creativeApps.ts +2 -1
- package/src/tools/gameAssetFetcher.js +130 -26
- package/src/tools/gameAssetHarvester.js +80 -58
- package/src/tools/nativeEngine.js +1 -1
- package/src/tools/nativeEngine.ts +1 -1
- package/src/tools/osSandbox.js +473 -0
- package/src/tools/osSandbox.ts +554 -0
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/registry.js +13 -0
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +39 -6
- package/src/tools/sysRun.ts +53 -7
- package/src/tools/toolScanner.js +596 -140
- package/src/tools/toolScanner.ts +665 -147
- package/src/tools/toolSelfRepair.js +243 -114
- package/src/tools/toolSelfRepair.ts +262 -111
- package/src/tools/webFetch.js +161 -24
- package/src/tools/webFetch.ts +157 -22
- package/src/tools/webSearch.js +33 -4
- package/src/tools/webSearch.ts +27 -4
- package/src/tui/sessionPicker.js +132 -35
- package/src/tui/sessionPicker.ts +153 -32
- package/src/tui/sessionPickerView.js +277 -34
- package/src/tui/sessionPickerView.ts +328 -34
- package/src/tui/statusLine.js +3 -0
- package/src/tui/statusLine.ts +5 -0
- package/src/tui/workspaceIdentity.js +133 -0
- package/src/tui/workspaceIdentity.ts +146 -0
package/src/config.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
import os from 'os';
|
|
4
|
-
import crypto from 'crypto';
|
|
5
3
|
import { canonicalModelId } from './modelIds.js';
|
|
6
4
|
import { DEFAULT_MODEL_BY_PROVIDER } from './modelCatalogue.js';
|
|
7
5
|
import { causyneHome } from './utils/paths.js';
|
|
6
|
+
import {
|
|
7
|
+
ensureVaultDir,
|
|
8
|
+
atomicWriteSecretFileSync,
|
|
9
|
+
encryptVaultSecret,
|
|
10
|
+
decryptVaultSecret,
|
|
11
|
+
isEncryptedVaultSecret
|
|
12
|
+
} from './configVault.js';
|
|
8
13
|
|
|
9
14
|
function configDir() {
|
|
10
15
|
return causyneHome();
|
|
@@ -17,54 +22,15 @@ function keyFile() {
|
|
|
17
22
|
}
|
|
18
23
|
|
|
19
24
|
function ensureConfigDir() {
|
|
20
|
-
|
|
21
|
-
if (!fs.existsSync(dir)) {
|
|
22
|
-
// SECURITY: Directory must only be accessible by the owner
|
|
23
|
-
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function getVaultKey() {
|
|
28
|
-
ensureConfigDir();
|
|
29
|
-
const kf = keyFile();
|
|
30
|
-
if (!fs.existsSync(kf)) {
|
|
31
|
-
const key = crypto.randomBytes(32);
|
|
32
|
-
fs.writeFileSync(kf, key, { mode: 0o600 });
|
|
33
|
-
return key;
|
|
34
|
-
}
|
|
35
|
-
return fs.readFileSync(kf);
|
|
25
|
+
ensureVaultDir(configDir());
|
|
36
26
|
}
|
|
37
27
|
|
|
38
28
|
function encryptString(text) {
|
|
39
|
-
|
|
40
|
-
if (text.startsWith('ENC:')) return text; // Already encrypted
|
|
41
|
-
const key = getVaultKey();
|
|
42
|
-
const iv = crypto.randomBytes(16);
|
|
43
|
-
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
44
|
-
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
45
|
-
encrypted += cipher.final('hex');
|
|
46
|
-
const authTag = cipher.getAuthTag().toString('hex');
|
|
47
|
-
return `ENC:${iv.toString('hex')}:${authTag}:${encrypted}`;
|
|
29
|
+
return encryptVaultSecret(text, keyFile());
|
|
48
30
|
}
|
|
49
31
|
|
|
50
32
|
function decryptString(encryptedText) {
|
|
51
|
-
|
|
52
|
-
try {
|
|
53
|
-
const parts = encryptedText.split(':');
|
|
54
|
-
if (parts.length !== 4) return '';
|
|
55
|
-
const iv = Buffer.from(parts[1], 'hex');
|
|
56
|
-
const authTag = Buffer.from(parts[2], 'hex');
|
|
57
|
-
const encrypted = parts[3];
|
|
58
|
-
const key = getVaultKey();
|
|
59
|
-
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
60
|
-
decipher.setAuthTag(authTag);
|
|
61
|
-
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
|
|
62
|
-
decrypted += decipher.final('utf8');
|
|
63
|
-
return decrypted;
|
|
64
|
-
} catch (e) {
|
|
65
|
-
console.error('Failed to decrypt API key:', e);
|
|
66
|
-
return '';
|
|
67
|
-
}
|
|
33
|
+
return decryptVaultSecret(encryptedText, keyFile());
|
|
68
34
|
}
|
|
69
35
|
|
|
70
36
|
export function loadConfig() {
|
|
@@ -73,28 +39,34 @@ export function loadConfig() {
|
|
|
73
39
|
if (fs.existsSync(file)) {
|
|
74
40
|
try {
|
|
75
41
|
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
parsed.apiKey = encryptString(plaintext);
|
|
83
|
-
saveConfig(parsed); // Re-saves safely encrypted
|
|
84
|
-
parsed.apiKey = plaintext; // Keep plaintext in memory for this session
|
|
42
|
+
let needsEncryptedResave = false;
|
|
43
|
+
|
|
44
|
+
// Decrypt API key into memory; flag legacy plaintext keys for immediate encrypted re-save.
|
|
45
|
+
if (typeof parsed.apiKey === 'string' && parsed.apiKey) {
|
|
46
|
+
if (!isEncryptedVaultSecret(parsed.apiKey)) {
|
|
47
|
+
needsEncryptedResave = true;
|
|
85
48
|
} else {
|
|
86
49
|
parsed.apiKey = decryptString(parsed.apiKey);
|
|
87
50
|
}
|
|
88
51
|
}
|
|
89
52
|
|
|
90
|
-
// Decrypt provider-specific API keys if stored
|
|
53
|
+
// Decrypt provider-specific API keys if stored; also re-encrypt any legacy plaintext entries.
|
|
91
54
|
if (parsed.providerKeys && typeof parsed.providerKeys === 'object') {
|
|
92
55
|
for (const [provider, keyVal] of Object.entries(parsed.providerKeys)) {
|
|
93
56
|
if (typeof keyVal === 'string' && keyVal) {
|
|
94
|
-
|
|
57
|
+
if (!isEncryptedVaultSecret(keyVal)) {
|
|
58
|
+
needsEncryptedResave = true;
|
|
59
|
+
} else {
|
|
60
|
+
parsed.providerKeys[provider] = decryptString(keyVal);
|
|
61
|
+
}
|
|
95
62
|
}
|
|
96
63
|
}
|
|
97
64
|
}
|
|
65
|
+
|
|
66
|
+
if (needsEncryptedResave) {
|
|
67
|
+
saveConfig(parsed);
|
|
68
|
+
}
|
|
69
|
+
|
|
98
70
|
if (parsed.apiKey && parsed.provider) {
|
|
99
71
|
parsed.providerKeys = parsed.providerKeys || {};
|
|
100
72
|
if (!parsed.providerKeys[parsed.provider]) {
|
|
@@ -111,18 +83,23 @@ export function loadConfig() {
|
|
|
111
83
|
|
|
112
84
|
// Self-heal legacy unconfigured DashScope bug:
|
|
113
85
|
// If config was written with provider 'dashscope' or 'dashscope-byok' but without an apiKey,
|
|
114
|
-
// it was an unintended default from older builds. Heal to an environment key
|
|
86
|
+
// it was an unintended default from older builds. Heal to an environment key (in-memory only,
|
|
87
|
+
// never persisting transient env secrets to disk) or unconfigured.
|
|
115
88
|
if ((parsed.provider === 'dashscope' || parsed.provider === 'dashscope-byok') && !parsed.apiKey) {
|
|
116
89
|
const envDetected = detectEnvironmentProvider();
|
|
117
|
-
if (envDetected) {
|
|
90
|
+
if (envDetected && envDetected.apiKey) {
|
|
118
91
|
parsed.provider = envDetected.provider;
|
|
119
92
|
parsed.model = envDetected.model;
|
|
120
93
|
parsed.apiKey = envDetected.apiKey;
|
|
94
|
+
} else if (envDetected) {
|
|
95
|
+
parsed.provider = envDetected.provider;
|
|
96
|
+
parsed.model = envDetected.model;
|
|
97
|
+
saveConfig(parsed);
|
|
121
98
|
} else {
|
|
122
99
|
parsed.provider = '';
|
|
123
100
|
parsed.model = '';
|
|
101
|
+
saveConfig(parsed);
|
|
124
102
|
}
|
|
125
|
-
saveConfig(parsed);
|
|
126
103
|
}
|
|
127
104
|
|
|
128
105
|
return parsed;
|
|
@@ -131,7 +108,8 @@ export function loadConfig() {
|
|
|
131
108
|
}
|
|
132
109
|
}
|
|
133
110
|
|
|
134
|
-
// Default config: auto-detect from environment if available, otherwise unconfigured
|
|
111
|
+
// Default config: auto-detect from environment if available, otherwise unconfigured.
|
|
112
|
+
// Transient environment API keys stay strictly in memory and are NEVER persisted to disk.
|
|
135
113
|
const envDetected = detectEnvironmentProvider();
|
|
136
114
|
const defaultConfig = {
|
|
137
115
|
provider: envDetected ? envDetected.provider : '',
|
|
@@ -147,7 +125,9 @@ export function loadConfig() {
|
|
|
147
125
|
hardStop: true
|
|
148
126
|
}
|
|
149
127
|
};
|
|
150
|
-
|
|
128
|
+
if (!envDetected || !envDetected.apiKey) {
|
|
129
|
+
saveConfig(defaultConfig);
|
|
130
|
+
}
|
|
151
131
|
return defaultConfig;
|
|
152
132
|
}
|
|
153
133
|
|
|
@@ -297,8 +277,7 @@ export function saveConfig(config) {
|
|
|
297
277
|
}
|
|
298
278
|
}
|
|
299
279
|
|
|
300
|
-
// SECURITY: Config file contains encrypted keys,
|
|
280
|
+
// SECURITY: Config file contains encrypted keys, written atomically with 0600 permissions
|
|
301
281
|
const file = configFile();
|
|
302
|
-
|
|
303
|
-
fs.chmodSync(file, 0o600); // Enforce on existing files
|
|
282
|
+
atomicWriteSecretFileSync(file, JSON.stringify(configToSave, null, 2));
|
|
304
283
|
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Atomic Config Vault & AES-256-GCM Secret Protection
|
|
3
|
+
*
|
|
4
|
+
* Hardens local BYOK credential storage (`~/.causyne/config.json` & `.vault_key`):
|
|
5
|
+
* 1. Atomic write-temp-chmod-rename (`atomicWriteSecretFileSync`) to prevent
|
|
6
|
+
* truncated/corrupted config files on crash or concurrent writes.
|
|
7
|
+
* 2. Strict `0o700` vault directory and `0o600` secret file permissions on POSIX.
|
|
8
|
+
* 3. NIST SP 800-38D standard 12-byte (96-bit) IV for new AES-256-GCM ciphertexts,
|
|
9
|
+
* while preserving full decryption compatibility with legacy 16-byte IV records.
|
|
10
|
+
*/
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { loadVaultKeyFromKeychain, resolveKeychainMode, saveVaultKeyToKeychain } from './osKeychain.js';
|
|
15
|
+
export const VAULT_KEY_BYTES = 32;
|
|
16
|
+
export const VAULT_GCM_IV_BYTES = 12;
|
|
17
|
+
export const VAULT_LEGACY_GCM_IV_BYTES = 16;
|
|
18
|
+
export const VAULT_GCM_AUTH_TAG_BYTES = 16;
|
|
19
|
+
export const VAULT_ENC_PREFIX = 'ENC:';
|
|
20
|
+
export function isEncryptedVaultSecret(value) {
|
|
21
|
+
return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
|
|
22
|
+
}
|
|
23
|
+
export function ensureVaultDir(dir) {
|
|
24
|
+
const resolved = path.resolve(dir);
|
|
25
|
+
if (!fs.existsSync(resolved)) {
|
|
26
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
27
|
+
}
|
|
28
|
+
if (process.platform !== 'win32') {
|
|
29
|
+
try {
|
|
30
|
+
fs.chmodSync(resolved, 0o700);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Best-effort permission tightening on platforms that restrict chmod
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Atomically writes a secret-bearing file (`config.json` or `.vault_key`) using
|
|
39
|
+
* a unique sibling temporary file with mode `0o600` followed by atomic rename.
|
|
40
|
+
*/
|
|
41
|
+
export function atomicWriteSecretFileSync(targetPath, content) {
|
|
42
|
+
const resolved = path.resolve(targetPath);
|
|
43
|
+
const dir = path.dirname(resolved);
|
|
44
|
+
ensureVaultDir(dir);
|
|
45
|
+
const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
|
46
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
|
|
47
|
+
try {
|
|
48
|
+
if (typeof content === 'string') {
|
|
49
|
+
fs.writeFileSync(tempPath, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
fs.writeFileSync(tempPath, content, { mode: 0o600, flag: 'wx' });
|
|
53
|
+
}
|
|
54
|
+
if (process.platform !== 'win32') {
|
|
55
|
+
try {
|
|
56
|
+
fs.chmodSync(tempPath, 0o600);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
fs.renameSync(tempPath, resolved);
|
|
63
|
+
if (process.platform !== 'win32') {
|
|
64
|
+
try {
|
|
65
|
+
fs.chmodSync(resolved, 0o600);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
try {
|
|
74
|
+
if (fs.existsSync(tempPath))
|
|
75
|
+
fs.unlinkSync(tempPath);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// Ignore temp cleanup failure
|
|
79
|
+
}
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Loads or atomically initializes the 256-bit local vault key with `0o600` permissions.
|
|
85
|
+
* When `CAUSYNE_KEYCHAIN=on|auto|strict` is enabled, uses the OS Keychain backend
|
|
86
|
+
* first (migrating an existing file key if present) and fails closed on `strict`.
|
|
87
|
+
*/
|
|
88
|
+
export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
|
|
89
|
+
const resolved = path.resolve(keyFilePath);
|
|
90
|
+
const vaultDir = path.dirname(resolved);
|
|
91
|
+
ensureVaultDir(vaultDir);
|
|
92
|
+
const keychainMode = resolveKeychainMode(keychainOptions?.env ?? process.env);
|
|
93
|
+
if (keychainMode !== 'off') {
|
|
94
|
+
const fromKeychain = loadVaultKeyFromKeychain(vaultDir, keychainOptions);
|
|
95
|
+
if (fromKeychain && fromKeychain.length === VAULT_KEY_BYTES) {
|
|
96
|
+
return fromKeychain;
|
|
97
|
+
}
|
|
98
|
+
// If a file key already exists, migrate it cleanly into the OS Keychain
|
|
99
|
+
if (fs.existsSync(resolved)) {
|
|
100
|
+
const existingFileKey = fs.readFileSync(resolved);
|
|
101
|
+
if (existingFileKey.length === VAULT_KEY_BYTES) {
|
|
102
|
+
const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
|
|
103
|
+
if (stored || keychainMode !== 'strict') {
|
|
104
|
+
return existingFileKey;
|
|
105
|
+
}
|
|
106
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but storing the vault key failed.');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// Generate a fresh key and persist into OS Keychain
|
|
110
|
+
const generated = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
111
|
+
if (saveVaultKeyToKeychain(vaultDir, generated, keychainOptions)) {
|
|
112
|
+
return generated;
|
|
113
|
+
}
|
|
114
|
+
if (keychainMode === 'strict') {
|
|
115
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but OS keychain storage is unavailable.');
|
|
116
|
+
}
|
|
117
|
+
// Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
|
|
118
|
+
}
|
|
119
|
+
if (fs.existsSync(resolved)) {
|
|
120
|
+
if (process.platform !== 'win32') {
|
|
121
|
+
try {
|
|
122
|
+
fs.chmodSync(resolved, 0o600);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const existing = fs.readFileSync(resolved);
|
|
129
|
+
if (existing.length !== VAULT_KEY_BYTES) {
|
|
130
|
+
throw new Error(`Invalid vault key length (${existing.length} bytes; expected ${VAULT_KEY_BYTES}).`);
|
|
131
|
+
}
|
|
132
|
+
return existing;
|
|
133
|
+
}
|
|
134
|
+
const freshKey = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
135
|
+
try {
|
|
136
|
+
// Exclusive create first so concurrent startups do not clobber each other's key
|
|
137
|
+
fs.writeFileSync(resolved, freshKey, { mode: 0o600, flag: 'wx' });
|
|
138
|
+
if (process.platform !== 'win32') {
|
|
139
|
+
try {
|
|
140
|
+
fs.chmodSync(resolved, 0o600);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
// Ignore chmod errors
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return freshKey;
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
150
|
+
if (code === 'EEXIST') {
|
|
151
|
+
const raced = fs.readFileSync(resolved);
|
|
152
|
+
if (raced.length === VAULT_KEY_BYTES)
|
|
153
|
+
return raced;
|
|
154
|
+
}
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
|
|
160
|
+
*/
|
|
161
|
+
export function encryptVaultSecret(text, keyFilePath) {
|
|
162
|
+
if (!text)
|
|
163
|
+
return text;
|
|
164
|
+
if (isEncryptedVaultSecret(text))
|
|
165
|
+
return text;
|
|
166
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
167
|
+
const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
|
|
168
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
169
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
170
|
+
encrypted += cipher.final('hex');
|
|
171
|
+
const authTag = cipher.getAuthTag().toString('hex');
|
|
172
|
+
return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
|
|
176
|
+
* or legacy 16-byte GCM IV. Returns empty string on authentication failure.
|
|
177
|
+
*/
|
|
178
|
+
export function decryptVaultSecret(encryptedText, keyFilePath) {
|
|
179
|
+
if (!encryptedText || !isEncryptedVaultSecret(encryptedText))
|
|
180
|
+
return encryptedText;
|
|
181
|
+
try {
|
|
182
|
+
const parts = encryptedText.split(':');
|
|
183
|
+
if (parts.length !== 4)
|
|
184
|
+
return '';
|
|
185
|
+
const ivHex = parts[1] ?? '';
|
|
186
|
+
const authTagHex = parts[2] ?? '';
|
|
187
|
+
const ciphertextHex = parts[3] ?? '';
|
|
188
|
+
const iv = Buffer.from(ivHex, 'hex');
|
|
189
|
+
const authTag = Buffer.from(authTagHex, 'hex');
|
|
190
|
+
if ((iv.length !== VAULT_GCM_IV_BYTES && iv.length !== VAULT_LEGACY_GCM_IV_BYTES) ||
|
|
191
|
+
authTag.length !== VAULT_GCM_AUTH_TAG_BYTES) {
|
|
192
|
+
return '';
|
|
193
|
+
}
|
|
194
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
195
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
196
|
+
decipher.setAuthTag(authTag);
|
|
197
|
+
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
|
198
|
+
decrypted += decipher.final('utf8');
|
|
199
|
+
return decrypted;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return '';
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Atomic Config Vault & AES-256-GCM Secret Protection
|
|
3
|
+
*
|
|
4
|
+
* Hardens local BYOK credential storage (`~/.causyne/config.json` & `.vault_key`):
|
|
5
|
+
* 1. Atomic write-temp-chmod-rename (`atomicWriteSecretFileSync`) to prevent
|
|
6
|
+
* truncated/corrupted config files on crash or concurrent writes.
|
|
7
|
+
* 2. Strict `0o700` vault directory and `0o600` secret file permissions on POSIX.
|
|
8
|
+
* 3. NIST SP 800-38D standard 12-byte (96-bit) IV for new AES-256-GCM ciphertexts,
|
|
9
|
+
* while preserving full decryption compatibility with legacy 16-byte IV records.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import {
|
|
16
|
+
loadVaultKeyFromKeychain,
|
|
17
|
+
resolveKeychainMode,
|
|
18
|
+
saveVaultKeyToKeychain,
|
|
19
|
+
type KeychainSpawnOptions
|
|
20
|
+
} from './osKeychain.js';
|
|
21
|
+
|
|
22
|
+
export const VAULT_KEY_BYTES = 32;
|
|
23
|
+
export const VAULT_GCM_IV_BYTES = 12;
|
|
24
|
+
export const VAULT_LEGACY_GCM_IV_BYTES = 16;
|
|
25
|
+
export const VAULT_GCM_AUTH_TAG_BYTES = 16;
|
|
26
|
+
export const VAULT_ENC_PREFIX = 'ENC:';
|
|
27
|
+
|
|
28
|
+
export function isEncryptedVaultSecret(value: unknown): value is string {
|
|
29
|
+
return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function ensureVaultDir(dir: string): void {
|
|
33
|
+
const resolved = path.resolve(dir);
|
|
34
|
+
if (!fs.existsSync(resolved)) {
|
|
35
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
36
|
+
}
|
|
37
|
+
if (process.platform !== 'win32') {
|
|
38
|
+
try {
|
|
39
|
+
fs.chmodSync(resolved, 0o700);
|
|
40
|
+
} catch {
|
|
41
|
+
// Best-effort permission tightening on platforms that restrict chmod
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Atomically writes a secret-bearing file (`config.json` or `.vault_key`) using
|
|
48
|
+
* a unique sibling temporary file with mode `0o600` followed by atomic rename.
|
|
49
|
+
*/
|
|
50
|
+
export function atomicWriteSecretFileSync(targetPath: string, content: string | Buffer): void {
|
|
51
|
+
const resolved = path.resolve(targetPath);
|
|
52
|
+
const dir = path.dirname(resolved);
|
|
53
|
+
ensureVaultDir(dir);
|
|
54
|
+
|
|
55
|
+
const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
|
56
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
if (typeof content === 'string') {
|
|
60
|
+
fs.writeFileSync(tempPath, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
61
|
+
} else {
|
|
62
|
+
fs.writeFileSync(tempPath, content, { mode: 0o600, flag: 'wx' });
|
|
63
|
+
}
|
|
64
|
+
if (process.platform !== 'win32') {
|
|
65
|
+
try {
|
|
66
|
+
fs.chmodSync(tempPath, 0o600);
|
|
67
|
+
} catch {
|
|
68
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
fs.renameSync(tempPath, resolved);
|
|
72
|
+
if (process.platform !== 'win32') {
|
|
73
|
+
try {
|
|
74
|
+
fs.chmodSync(resolved, 0o600);
|
|
75
|
+
} catch {
|
|
76
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
} catch (err: unknown) {
|
|
80
|
+
try {
|
|
81
|
+
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
|
|
82
|
+
} catch {
|
|
83
|
+
// Ignore temp cleanup failure
|
|
84
|
+
}
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Loads or atomically initializes the 256-bit local vault key with `0o600` permissions.
|
|
91
|
+
* When `CAUSYNE_KEYCHAIN=on|auto|strict` is enabled, uses the OS Keychain backend
|
|
92
|
+
* first (migrating an existing file key if present) and fails closed on `strict`.
|
|
93
|
+
*/
|
|
94
|
+
export function getOrCreateVaultKey(
|
|
95
|
+
keyFilePath: string,
|
|
96
|
+
keychainOptions?: KeychainSpawnOptions
|
|
97
|
+
): Buffer {
|
|
98
|
+
const resolved = path.resolve(keyFilePath);
|
|
99
|
+
const vaultDir = path.dirname(resolved);
|
|
100
|
+
ensureVaultDir(vaultDir);
|
|
101
|
+
|
|
102
|
+
const keychainMode = resolveKeychainMode(keychainOptions?.env ?? process.env);
|
|
103
|
+
if (keychainMode !== 'off') {
|
|
104
|
+
const fromKeychain = loadVaultKeyFromKeychain(vaultDir, keychainOptions);
|
|
105
|
+
if (fromKeychain && fromKeychain.length === VAULT_KEY_BYTES) {
|
|
106
|
+
return fromKeychain;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// If a file key already exists, migrate it cleanly into the OS Keychain
|
|
110
|
+
if (fs.existsSync(resolved)) {
|
|
111
|
+
const existingFileKey = fs.readFileSync(resolved);
|
|
112
|
+
if (existingFileKey.length === VAULT_KEY_BYTES) {
|
|
113
|
+
const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
|
|
114
|
+
if (stored || keychainMode !== 'strict') {
|
|
115
|
+
return existingFileKey;
|
|
116
|
+
}
|
|
117
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but storing the vault key failed.');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Generate a fresh key and persist into OS Keychain
|
|
122
|
+
const generated = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
123
|
+
if (saveVaultKeyToKeychain(vaultDir, generated, keychainOptions)) {
|
|
124
|
+
return generated;
|
|
125
|
+
}
|
|
126
|
+
if (keychainMode === 'strict') {
|
|
127
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but OS keychain storage is unavailable.');
|
|
128
|
+
}
|
|
129
|
+
// Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (fs.existsSync(resolved)) {
|
|
133
|
+
if (process.platform !== 'win32') {
|
|
134
|
+
try {
|
|
135
|
+
fs.chmodSync(resolved, 0o600);
|
|
136
|
+
} catch {
|
|
137
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const existing = fs.readFileSync(resolved);
|
|
141
|
+
if (existing.length !== VAULT_KEY_BYTES) {
|
|
142
|
+
throw new Error(`Invalid vault key length (${existing.length} bytes; expected ${VAULT_KEY_BYTES}).`);
|
|
143
|
+
}
|
|
144
|
+
return existing;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const freshKey = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
148
|
+
try {
|
|
149
|
+
// Exclusive create first so concurrent startups do not clobber each other's key
|
|
150
|
+
fs.writeFileSync(resolved, freshKey, { mode: 0o600, flag: 'wx' });
|
|
151
|
+
if (process.platform !== 'win32') {
|
|
152
|
+
try {
|
|
153
|
+
fs.chmodSync(resolved, 0o600);
|
|
154
|
+
} catch {
|
|
155
|
+
// Ignore chmod errors
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return freshKey;
|
|
159
|
+
} catch (err: unknown) {
|
|
160
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
161
|
+
if (code === 'EEXIST') {
|
|
162
|
+
const raced = fs.readFileSync(resolved);
|
|
163
|
+
if (raced.length === VAULT_KEY_BYTES) return raced;
|
|
164
|
+
}
|
|
165
|
+
throw err;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
|
|
171
|
+
*/
|
|
172
|
+
export function encryptVaultSecret(text: string, keyFilePath: string): string {
|
|
173
|
+
if (!text) return text;
|
|
174
|
+
if (isEncryptedVaultSecret(text)) return text;
|
|
175
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
176
|
+
const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
|
|
177
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
178
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
179
|
+
encrypted += cipher.final('hex');
|
|
180
|
+
const authTag = cipher.getAuthTag().toString('hex');
|
|
181
|
+
return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
|
|
186
|
+
* or legacy 16-byte GCM IV. Returns empty string on authentication failure.
|
|
187
|
+
*/
|
|
188
|
+
export function decryptVaultSecret(encryptedText: string, keyFilePath: string): string {
|
|
189
|
+
if (!encryptedText || !isEncryptedVaultSecret(encryptedText)) return encryptedText;
|
|
190
|
+
try {
|
|
191
|
+
const parts = encryptedText.split(':');
|
|
192
|
+
if (parts.length !== 4) return '';
|
|
193
|
+
const ivHex = parts[1] ?? '';
|
|
194
|
+
const authTagHex = parts[2] ?? '';
|
|
195
|
+
const ciphertextHex = parts[3] ?? '';
|
|
196
|
+
const iv = Buffer.from(ivHex, 'hex');
|
|
197
|
+
const authTag = Buffer.from(authTagHex, 'hex');
|
|
198
|
+
if (
|
|
199
|
+
(iv.length !== VAULT_GCM_IV_BYTES && iv.length !== VAULT_LEGACY_GCM_IV_BYTES) ||
|
|
200
|
+
authTag.length !== VAULT_GCM_AUTH_TAG_BYTES
|
|
201
|
+
) {
|
|
202
|
+
return '';
|
|
203
|
+
}
|
|
204
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
205
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
206
|
+
decipher.setAuthTag(authTag);
|
|
207
|
+
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
|
208
|
+
decrypted += decipher.final('utf8');
|
|
209
|
+
return decrypted;
|
|
210
|
+
} catch {
|
|
211
|
+
return '';
|
|
212
|
+
}
|
|
213
|
+
}
|