@causyne/agent 1.20.120 → 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.
Files changed (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Causyne Agent — MCP Protocol Security & Untrusted Metadata Bounds
3
+ *
4
+ * Hardens external MCP server integration against:
5
+ * 1. Polynomial / catastrophic ReDoS (CWE-1333) in `tools.include` / `tools.exclude`
6
+ * glob filters by replacing dynamic `new RegExp()` compilation with a strictly
7
+ * linear-space iterative wildcard matcher.
8
+ * 2. Context-window flooding & schema bombs (CWE-400) via per-server tool caps,
9
+ * description/instruction length ceilings, and bounded JSON schema sanitization.
10
+ * 3. Terminal escape injection & Trojan Source hidden Unicode bidi/zero-width
11
+ * control characters inside untrusted MCP tool names, descriptions, schema
12
+ * annotations, and server instructions.
13
+ */
14
+ import { safeDisplay } from '../tui/text.js';
15
+ export const MAX_GLOB_PATTERN_CHARS = 256;
16
+ export const MAX_TOOLS_PER_MCP_SERVER = 256;
17
+ export const MAX_MCP_TOOL_NAME_CHARS = 128;
18
+ export const MAX_MCP_TOOL_DESCRIPTION_CHARS = 2048;
19
+ export const MAX_MCP_SERVER_INSTRUCTIONS_CHARS = 4096;
20
+ export const MAX_MCP_SCHEMA_STRING_CHARS = 1024;
21
+ export const MAX_MCP_SCHEMA_DEPTH = 16;
22
+ export const MAX_MCP_SCHEMA_JSON_BYTES = 65_536;
23
+ function isRecord(value) {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
25
+ }
26
+ /**
27
+ * Strips invisible zero-width and Unicode bidirectional override/isolate format
28
+ * characters (Trojan Source vectors: U+202A–U+202E, U+2066–U+2069, U+200B–U+200F,
29
+ * U+061C, U+2060, U+FEFF) in a single linear O(n) pass.
30
+ */
31
+ export function stripInvisibleAndBidi(text) {
32
+ if (!text)
33
+ return '';
34
+ let out = '';
35
+ for (let i = 0; i < text.length; i++) {
36
+ const code = text.charCodeAt(i);
37
+ if (code === 0x061c ||
38
+ (code >= 0x200b && code <= 0x200f) ||
39
+ (code >= 0x202a && code <= 0x202e) ||
40
+ code === 0x2060 ||
41
+ (code >= 0x2066 && code <= 0x2069) ||
42
+ code === 0xfeff) {
43
+ continue;
44
+ }
45
+ out += text[i];
46
+ }
47
+ return out;
48
+ }
49
+ /**
50
+ * ReDoS-free iterative wildcard matcher supporting `*` (0+ code points) and
51
+ * `?` (exactly 1 code point). Uses Unicode code points (`Array.from`) so
52
+ * surrogate pairs match identically to Unicode-mode regexes without constructing
53
+ * any `RegExp`. Guaranteed O(n * m) worst-case time, O(n + m) memory.
54
+ */
55
+ export function globMatchesSafe(name, pattern) {
56
+ if (typeof name !== 'string' || typeof pattern !== 'string')
57
+ return false;
58
+ if (pattern.length > MAX_GLOB_PATTERN_CHARS)
59
+ return false;
60
+ const textChars = Array.from(name);
61
+ const rawPatChars = Array.from(pattern);
62
+ // Collapse consecutive `*` wildcards to prevent redundant backtracking steps
63
+ const patChars = [];
64
+ for (const ch of rawPatChars) {
65
+ if (ch === '*' && patChars[patChars.length - 1] === '*')
66
+ continue;
67
+ patChars.push(ch);
68
+ }
69
+ let t = 0;
70
+ let p = 0;
71
+ let starIdx = -1;
72
+ let matchIdx = 0;
73
+ while (t < textChars.length) {
74
+ if (p < patChars.length && (patChars[p] === '?' || patChars[p] === textChars[t])) {
75
+ t++;
76
+ p++;
77
+ }
78
+ else if (p < patChars.length && patChars[p] === '*') {
79
+ starIdx = p;
80
+ matchIdx = t;
81
+ p++;
82
+ }
83
+ else if (starIdx !== -1) {
84
+ p = starIdx + 1;
85
+ matchIdx++;
86
+ t = matchIdx;
87
+ }
88
+ else {
89
+ return false;
90
+ }
91
+ }
92
+ while (p < patChars.length && patChars[p] === '*') {
93
+ p++;
94
+ }
95
+ return p === patChars.length;
96
+ }
97
+ /**
98
+ * Sanitizes untrusted text received from an MCP server (descriptions, server
99
+ * instructions, error strings) via canonical `safeDisplay()`, strips invisible
100
+ * Unicode bidi/zero-width characters, and enforces a strict character cap.
101
+ */
102
+ export function sanitizeMcpMetadataText(value, maxChars) {
103
+ if (typeof value !== 'string')
104
+ return '';
105
+ const cleaned = stripInvisibleAndBidi(safeDisplay(value)).trim();
106
+ if (cleaned.length <= maxChars)
107
+ return cleaned;
108
+ const suffix = '… [truncated]';
109
+ const keep = Math.max(0, maxChars - suffix.length);
110
+ return `${cleaned.slice(0, keep).trimEnd()}${suffix}`;
111
+ }
112
+ /**
113
+ * Validates and sanitizes an MCP tool name. Rejects empty names, names with
114
+ * ASCII control characters / NUL bytes, or names exceeding the length ceiling.
115
+ */
116
+ export function sanitizeMcpToolName(value) {
117
+ if (typeof value !== 'string')
118
+ return null;
119
+ const stripped = stripInvisibleAndBidi(value).trim();
120
+ if (stripped.length === 0 || stripped.length > MAX_MCP_TOOL_NAME_CHARS)
121
+ return null;
122
+ for (let i = 0; i < stripped.length; i++) {
123
+ const code = stripped.charCodeAt(i);
124
+ if (code < 0x20 || code === 0x7f)
125
+ return null;
126
+ }
127
+ return stripped;
128
+ }
129
+ function sanitizeSchemaNode(value, depth) {
130
+ if (depth > MAX_MCP_SCHEMA_DEPTH) {
131
+ return { type: 'object', description: 'Nested schema truncated at maximum depth.' };
132
+ }
133
+ if (typeof value === 'string') {
134
+ return sanitizeMcpMetadataText(value, MAX_MCP_SCHEMA_STRING_CHARS);
135
+ }
136
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
137
+ return value;
138
+ }
139
+ if (Array.isArray(value)) {
140
+ const maxItems = 128;
141
+ return value.slice(0, maxItems).map(item => sanitizeSchemaNode(item, depth + 1));
142
+ }
143
+ if (isRecord(value)) {
144
+ const out = {};
145
+ let count = 0;
146
+ for (const [key, item] of Object.entries(value)) {
147
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
148
+ continue;
149
+ if (count >= 256)
150
+ break;
151
+ const safeKey = stripInvisibleAndBidi(safeDisplay(key));
152
+ if (!safeKey)
153
+ continue;
154
+ out[safeKey] = sanitizeSchemaNode(item, depth + 1);
155
+ count++;
156
+ }
157
+ return out;
158
+ }
159
+ return undefined;
160
+ }
161
+ /**
162
+ * Sanitizes and size-bounds an untrusted MCP tool JSON input schema.
163
+ * Strips ANSI escapes and bidi characters from nested property descriptions,
164
+ * prevents prototype pollution keys, caps nesting depth, and falls back to an
165
+ * empty object schema if serialized size exceeds `MAX_MCP_SCHEMA_JSON_BYTES`.
166
+ */
167
+ export function sanitizeMcpInputSchema(schema) {
168
+ if (!isRecord(schema)) {
169
+ return { type: 'object', properties: {} };
170
+ }
171
+ const sanitized = sanitizeSchemaNode(schema, 0);
172
+ if (!isRecord(sanitized)) {
173
+ return { type: 'object', properties: {} };
174
+ }
175
+ try {
176
+ const serialized = JSON.stringify(sanitized);
177
+ if (Buffer.byteLength(serialized, 'utf8') > MAX_MCP_SCHEMA_JSON_BYTES) {
178
+ return {
179
+ type: 'object',
180
+ properties: {},
181
+ description: 'MCP tool input schema omitted because it exceeded the 64 KiB safety limit.'
182
+ };
183
+ }
184
+ }
185
+ catch {
186
+ return { type: 'object', properties: {} };
187
+ }
188
+ return sanitized;
189
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Causyne Agent — MCP Protocol Security & Untrusted Metadata Bounds
3
+ *
4
+ * Hardens external MCP server integration against:
5
+ * 1. Polynomial / catastrophic ReDoS (CWE-1333) in `tools.include` / `tools.exclude`
6
+ * glob filters by replacing dynamic `new RegExp()` compilation with a strictly
7
+ * linear-space iterative wildcard matcher.
8
+ * 2. Context-window flooding & schema bombs (CWE-400) via per-server tool caps,
9
+ * description/instruction length ceilings, and bounded JSON schema sanitization.
10
+ * 3. Terminal escape injection & Trojan Source hidden Unicode bidi/zero-width
11
+ * control characters inside untrusted MCP tool names, descriptions, schema
12
+ * annotations, and server instructions.
13
+ */
14
+
15
+ import { safeDisplay } from '../tui/text.js';
16
+
17
+ export const MAX_GLOB_PATTERN_CHARS = 256;
18
+ export const MAX_TOOLS_PER_MCP_SERVER = 256;
19
+ export const MAX_MCP_TOOL_NAME_CHARS = 128;
20
+ export const MAX_MCP_TOOL_DESCRIPTION_CHARS = 2048;
21
+ export const MAX_MCP_SERVER_INSTRUCTIONS_CHARS = 4096;
22
+ export const MAX_MCP_SCHEMA_STRING_CHARS = 1024;
23
+ export const MAX_MCP_SCHEMA_DEPTH = 16;
24
+ export const MAX_MCP_SCHEMA_JSON_BYTES = 65_536;
25
+
26
+ function isRecord(value: unknown): value is Record<string, unknown> {
27
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
28
+ }
29
+
30
+ /**
31
+ * Strips invisible zero-width and Unicode bidirectional override/isolate format
32
+ * characters (Trojan Source vectors: U+202A–U+202E, U+2066–U+2069, U+200B–U+200F,
33
+ * U+061C, U+2060, U+FEFF) in a single linear O(n) pass.
34
+ */
35
+ export function stripInvisibleAndBidi(text: string): string {
36
+ if (!text) return '';
37
+ let out = '';
38
+ for (let i = 0; i < text.length; i++) {
39
+ const code = text.charCodeAt(i);
40
+ if (
41
+ code === 0x061c ||
42
+ (code >= 0x200b && code <= 0x200f) ||
43
+ (code >= 0x202a && code <= 0x202e) ||
44
+ code === 0x2060 ||
45
+ (code >= 0x2066 && code <= 0x2069) ||
46
+ code === 0xfeff
47
+ ) {
48
+ continue;
49
+ }
50
+ out += text[i];
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * ReDoS-free iterative wildcard matcher supporting `*` (0+ code points) and
57
+ * `?` (exactly 1 code point). Uses Unicode code points (`Array.from`) so
58
+ * surrogate pairs match identically to Unicode-mode regexes without constructing
59
+ * any `RegExp`. Guaranteed O(n * m) worst-case time, O(n + m) memory.
60
+ */
61
+ export function globMatchesSafe(name: string, pattern: string): boolean {
62
+ if (typeof name !== 'string' || typeof pattern !== 'string') return false;
63
+ if (pattern.length > MAX_GLOB_PATTERN_CHARS) return false;
64
+
65
+ const textChars = Array.from(name);
66
+ const rawPatChars = Array.from(pattern);
67
+
68
+ // Collapse consecutive `*` wildcards to prevent redundant backtracking steps
69
+ const patChars: string[] = [];
70
+ for (const ch of rawPatChars) {
71
+ if (ch === '*' && patChars[patChars.length - 1] === '*') continue;
72
+ patChars.push(ch);
73
+ }
74
+
75
+ let t = 0;
76
+ let p = 0;
77
+ let starIdx = -1;
78
+ let matchIdx = 0;
79
+
80
+ while (t < textChars.length) {
81
+ if (p < patChars.length && (patChars[p] === '?' || patChars[p] === textChars[t])) {
82
+ t++;
83
+ p++;
84
+ } else if (p < patChars.length && patChars[p] === '*') {
85
+ starIdx = p;
86
+ matchIdx = t;
87
+ p++;
88
+ } else if (starIdx !== -1) {
89
+ p = starIdx + 1;
90
+ matchIdx++;
91
+ t = matchIdx;
92
+ } else {
93
+ return false;
94
+ }
95
+ }
96
+
97
+ while (p < patChars.length && patChars[p] === '*') {
98
+ p++;
99
+ }
100
+
101
+ return p === patChars.length;
102
+ }
103
+
104
+ /**
105
+ * Sanitizes untrusted text received from an MCP server (descriptions, server
106
+ * instructions, error strings) via canonical `safeDisplay()`, strips invisible
107
+ * Unicode bidi/zero-width characters, and enforces a strict character cap.
108
+ */
109
+ export function sanitizeMcpMetadataText(value: unknown, maxChars: number): string {
110
+ if (typeof value !== 'string') return '';
111
+ const cleaned = stripInvisibleAndBidi(safeDisplay(value)).trim();
112
+ if (cleaned.length <= maxChars) return cleaned;
113
+ const suffix = '… [truncated]';
114
+ const keep = Math.max(0, maxChars - suffix.length);
115
+ return `${cleaned.slice(0, keep).trimEnd()}${suffix}`;
116
+ }
117
+
118
+ /**
119
+ * Validates and sanitizes an MCP tool name. Rejects empty names, names with
120
+ * ASCII control characters / NUL bytes, or names exceeding the length ceiling.
121
+ */
122
+ export function sanitizeMcpToolName(value: unknown): string | null {
123
+ if (typeof value !== 'string') return null;
124
+ const stripped = stripInvisibleAndBidi(value).trim();
125
+ if (stripped.length === 0 || stripped.length > MAX_MCP_TOOL_NAME_CHARS) return null;
126
+ for (let i = 0; i < stripped.length; i++) {
127
+ const code = stripped.charCodeAt(i);
128
+ if (code < 0x20 || code === 0x7f) return null;
129
+ }
130
+ return stripped;
131
+ }
132
+
133
+ function sanitizeSchemaNode(value: unknown, depth: number): unknown {
134
+ if (depth > MAX_MCP_SCHEMA_DEPTH) {
135
+ return { type: 'object', description: 'Nested schema truncated at maximum depth.' };
136
+ }
137
+ if (typeof value === 'string') {
138
+ return sanitizeMcpMetadataText(value, MAX_MCP_SCHEMA_STRING_CHARS);
139
+ }
140
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
141
+ return value;
142
+ }
143
+ if (Array.isArray(value)) {
144
+ const maxItems = 128;
145
+ return value.slice(0, maxItems).map(item => sanitizeSchemaNode(item, depth + 1));
146
+ }
147
+ if (isRecord(value)) {
148
+ const out: Record<string, unknown> = {};
149
+ let count = 0;
150
+ for (const [key, item] of Object.entries(value)) {
151
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
152
+ if (count >= 256) break;
153
+ const safeKey = stripInvisibleAndBidi(safeDisplay(key));
154
+ if (!safeKey) continue;
155
+ out[safeKey] = sanitizeSchemaNode(item, depth + 1);
156
+ count++;
157
+ }
158
+ return out;
159
+ }
160
+ return undefined;
161
+ }
162
+
163
+ /**
164
+ * Sanitizes and size-bounds an untrusted MCP tool JSON input schema.
165
+ * Strips ANSI escapes and bidi characters from nested property descriptions,
166
+ * prevents prototype pollution keys, caps nesting depth, and falls back to an
167
+ * empty object schema if serialized size exceeds `MAX_MCP_SCHEMA_JSON_BYTES`.
168
+ */
169
+ export function sanitizeMcpInputSchema(schema: unknown): Record<string, unknown> {
170
+ if (!isRecord(schema)) {
171
+ return { type: 'object', properties: {} };
172
+ }
173
+ const sanitized = sanitizeSchemaNode(schema, 0);
174
+ if (!isRecord(sanitized)) {
175
+ return { type: 'object', properties: {} };
176
+ }
177
+ try {
178
+ const serialized = JSON.stringify(sanitized);
179
+ if (Buffer.byteLength(serialized, 'utf8') > MAX_MCP_SCHEMA_JSON_BYTES) {
180
+ return {
181
+ type: 'object',
182
+ properties: {},
183
+ description: 'MCP tool input schema omitted because it exceeded the 64 KiB safety limit.'
184
+ };
185
+ }
186
+ } catch {
187
+ return { type: 'object', properties: {} };
188
+ }
189
+ return sanitized;
190
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Causyne Agent — Optional OS Keychain Master-Key Backend (Sector 6C)
3
+ *
4
+ * Stores and retrieves the 32-byte AES-256-GCM vault master key in the host
5
+ * operating system's credential store when enabled via `CAUSYNE_KEYCHAIN=on|auto|strict`:
6
+ * - macOS (`darwin`): Keychain Services (`/usr/bin/security -i` via stdin, never argv)
7
+ * - Linux (`linux`): libsecret (`secret-tool` via stdin, never argv)
8
+ * - Windows (`win32`): DPAPI `CurrentUser` encrypted blob (`.vault_key.dpapi` via stdin)
9
+ *
10
+ * Defaults to `'off'` so headless CI runners, containers, and existing `.vault_key`
11
+ * users experience zero unexpected OS prompts.
12
+ */
13
+ import { spawnSync } from 'node:child_process';
14
+ import crypto from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ const KEYCHAIN_SERVICE = 'causyne-agent';
18
+ const EXPECTED_KEY_BYTES = 32;
19
+ const EXPECTED_KEY_HEX_LEN = EXPECTED_KEY_BYTES * 2;
20
+ const MACOS_SECURITY_BIN = '/usr/bin/security';
21
+ export function resolveKeychainMode(env = process.env) {
22
+ const raw = typeof env.CAUSYNE_KEYCHAIN === 'string' ? env.CAUSYNE_KEYCHAIN.trim().toLowerCase() : '';
23
+ if (raw === 'strict')
24
+ return 'strict';
25
+ if (raw === 'on' || raw === '1' || raw === 'true')
26
+ return 'on';
27
+ if (raw === 'auto')
28
+ return 'auto';
29
+ return 'off';
30
+ }
31
+ export function keychainAccountForVaultDir(vaultDir) {
32
+ const digest = crypto.createHash('sha256').update(path.resolve(vaultDir)).digest('hex').slice(0, 12);
33
+ return `vault-key-${digest}`;
34
+ }
35
+ function isValidHexKey(raw) {
36
+ return raw.length === EXPECTED_KEY_HEX_LEN && /^[0-9a-fA-F]+$/.test(raw);
37
+ }
38
+ function findInPath(binary, env = process.env) {
39
+ const pathVal = env.PATH || env.Path || '';
40
+ for (const dir of pathVal.split(path.delimiter)) {
41
+ if (!dir)
42
+ continue;
43
+ const full = path.join(dir, binary);
44
+ try {
45
+ fs.accessSync(full, fs.constants.X_OK);
46
+ if (fs.statSync(full).isFile())
47
+ return full;
48
+ }
49
+ catch {
50
+ continue;
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+ export function probeOsKeychain(options = {}) {
56
+ const platform = options.platform ?? process.platform;
57
+ const env = options.env ?? process.env;
58
+ if (platform === 'darwin') {
59
+ const exists = fs.existsSync(MACOS_SECURITY_BIN);
60
+ return {
61
+ backend: exists ? 'macos-keychain' : 'none',
62
+ platform,
63
+ available: exists,
64
+ reason: exists ? 'macOS Keychain Services (/usr/bin/security) available.' : 'macOS security CLI not found.'
65
+ };
66
+ }
67
+ if (platform === 'linux') {
68
+ const secretTool = findInPath('secret-tool', env);
69
+ return {
70
+ backend: secretTool ? 'linux-secret-service' : 'none',
71
+ platform,
72
+ available: Boolean(secretTool),
73
+ reason: secretTool ? 'Linux Secret Service (secret-tool) available.' : 'secret-tool not installed.'
74
+ };
75
+ }
76
+ if (platform === 'win32') {
77
+ return {
78
+ backend: 'windows-dpapi',
79
+ platform,
80
+ available: true,
81
+ reason: 'Windows DPAPI (CurrentUser scope) available.'
82
+ };
83
+ }
84
+ return {
85
+ backend: 'none',
86
+ platform,
87
+ available: false,
88
+ reason: `No OS keychain backend implemented for platform "${platform}".`
89
+ };
90
+ }
91
+ function dpapiBlobPath(vaultDir) {
92
+ return path.join(path.resolve(vaultDir), '.vault_key.dpapi');
93
+ }
94
+ /**
95
+ * Loads the 32-byte vault key from the OS credential store, or returns `null` if absent/unavailable.
96
+ */
97
+ export function loadVaultKeyFromKeychain(vaultDir, options = {}) {
98
+ const platform = options.platform ?? process.platform;
99
+ const runner = options.spawnSyncImpl ?? spawnSync;
100
+ const account = keychainAccountForVaultDir(vaultDir);
101
+ if (platform === 'darwin') {
102
+ const res = runner(MACOS_SECURITY_BIN, ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'], {
103
+ encoding: 'utf8',
104
+ stdio: ['ignore', 'pipe', 'pipe'],
105
+ timeout: 5000,
106
+ shell: false
107
+ });
108
+ if (res.status !== 0 || typeof res.stdout !== 'string')
109
+ return null;
110
+ const hex = res.stdout.trim();
111
+ return isValidHexKey(hex) ? Buffer.from(hex, 'hex') : null;
112
+ }
113
+ if (platform === 'linux') {
114
+ const res = runner('secret-tool', ['lookup', 'service', KEYCHAIN_SERVICE, 'account', account], {
115
+ encoding: 'utf8',
116
+ stdio: ['ignore', 'pipe', 'pipe'],
117
+ timeout: 5000,
118
+ shell: false
119
+ });
120
+ if (res.status !== 0 || typeof res.stdout !== 'string')
121
+ return null;
122
+ const hex = res.stdout.trim();
123
+ return isValidHexKey(hex) ? Buffer.from(hex, 'hex') : null;
124
+ }
125
+ if (platform === 'win32') {
126
+ const blobFile = dpapiBlobPath(vaultDir);
127
+ if (!fs.existsSync(blobFile))
128
+ return null;
129
+ const protectedBase64 = fs.readFileSync(blobFile, 'utf8').trim();
130
+ if (!protectedBase64)
131
+ return null;
132
+ const script = [
133
+ 'Add-Type -AssemblyName System.Security',
134
+ '$b64 = [Console]::In.ReadToEnd().Trim()',
135
+ '$enc = [Convert]::FromBase64String($b64)',
136
+ '$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($enc, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)',
137
+ '[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain))'
138
+ ].join('; ');
139
+ const res = runner('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
140
+ input: protectedBase64,
141
+ encoding: 'utf8',
142
+ stdio: ['pipe', 'pipe', 'pipe'],
143
+ timeout: 8000,
144
+ shell: false
145
+ });
146
+ if (res.status !== 0 || typeof res.stdout !== 'string')
147
+ return null;
148
+ const hex = res.stdout.trim();
149
+ return isValidHexKey(hex) ? Buffer.from(hex, 'hex') : null;
150
+ }
151
+ return null;
152
+ }
153
+ /**
154
+ * Persists a 32-byte vault key into the OS credential store without passing
155
+ * secret material on command-line argv (always delivered via stdin).
156
+ */
157
+ export function saveVaultKeyToKeychain(vaultDir, key, options = {}) {
158
+ if (!Buffer.isBuffer(key) || key.length !== EXPECTED_KEY_BYTES)
159
+ return false;
160
+ const platform = options.platform ?? process.platform;
161
+ const runner = options.spawnSyncImpl ?? spawnSync;
162
+ const account = keychainAccountForVaultDir(vaultDir);
163
+ const hexKey = key.toString('hex');
164
+ if (platform === 'darwin') {
165
+ // Use interactive `-i` stdin mode so the hex key never appears in process argv (`ps`)
166
+ const stdinCmd = `add-generic-password -U -s "${KEYCHAIN_SERVICE}" -a "${account}" -w "${hexKey}"\n`;
167
+ const res = runner(MACOS_SECURITY_BIN, ['-i'], {
168
+ input: stdinCmd,
169
+ encoding: 'utf8',
170
+ stdio: ['pipe', 'pipe', 'pipe'],
171
+ timeout: 5000,
172
+ shell: false
173
+ });
174
+ return res.status === 0;
175
+ }
176
+ if (platform === 'linux') {
177
+ const res = runner('secret-tool', ['store', '--label', 'Causyne Agent Vault Key', 'service', KEYCHAIN_SERVICE, 'account', account], {
178
+ input: hexKey,
179
+ encoding: 'utf8',
180
+ stdio: ['pipe', 'pipe', 'pipe'],
181
+ timeout: 5000,
182
+ shell: false
183
+ });
184
+ return res.status === 0;
185
+ }
186
+ if (platform === 'win32') {
187
+ const script = [
188
+ 'Add-Type -AssemblyName System.Security',
189
+ '$hex = [Console]::In.ReadToEnd().Trim()',
190
+ '$bytes = [System.Text.Encoding]::UTF8.GetBytes($hex)',
191
+ '$enc = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)',
192
+ '[Console]::Out.Write([Convert]::ToBase64String($enc))'
193
+ ].join('; ');
194
+ const res = runner('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
195
+ input: hexKey,
196
+ encoding: 'utf8',
197
+ stdio: ['pipe', 'pipe', 'pipe'],
198
+ timeout: 8000,
199
+ shell: false
200
+ });
201
+ if (res.status !== 0 || typeof res.stdout !== 'string' || !res.stdout.trim())
202
+ return false;
203
+ const blobFile = dpapiBlobPath(vaultDir);
204
+ fs.mkdirSync(path.dirname(blobFile), { recursive: true });
205
+ fs.writeFileSync(blobFile, `${res.stdout.trim()}\n`, { encoding: 'utf8', mode: 0o600 });
206
+ return true;
207
+ }
208
+ return false;
209
+ }