opc-agent 3.0.0 → 4.0.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.
Files changed (151) hide show
  1. package/README.md +30 -24
  2. package/dist/channels/dingtalk.d.ts +17 -0
  3. package/dist/channels/dingtalk.js +38 -0
  4. package/dist/channels/googlechat.d.ts +14 -0
  5. package/dist/channels/googlechat.js +37 -0
  6. package/dist/channels/imessage.d.ts +13 -0
  7. package/dist/channels/imessage.js +28 -0
  8. package/dist/channels/irc.d.ts +20 -0
  9. package/dist/channels/irc.js +71 -0
  10. package/dist/channels/line.d.ts +14 -0
  11. package/dist/channels/line.js +28 -0
  12. package/dist/channels/matrix.d.ts +15 -0
  13. package/dist/channels/matrix.js +28 -0
  14. package/dist/channels/mattermost.d.ts +18 -0
  15. package/dist/channels/mattermost.js +49 -0
  16. package/dist/channels/msteams.d.ts +14 -0
  17. package/dist/channels/msteams.js +28 -0
  18. package/dist/channels/nostr.d.ts +14 -0
  19. package/dist/channels/nostr.js +28 -0
  20. package/dist/channels/qq.d.ts +15 -0
  21. package/dist/channels/qq.js +28 -0
  22. package/dist/channels/signal.d.ts +14 -0
  23. package/dist/channels/signal.js +28 -0
  24. package/dist/channels/sms.d.ts +15 -0
  25. package/dist/channels/sms.js +28 -0
  26. package/dist/channels/twitch.d.ts +17 -0
  27. package/dist/channels/twitch.js +59 -0
  28. package/dist/channels/voice-call.d.ts +27 -0
  29. package/dist/channels/voice-call.js +82 -0
  30. package/dist/channels/whatsapp.d.ts +14 -0
  31. package/dist/channels/whatsapp.js +28 -0
  32. package/dist/cli.js +36 -0
  33. package/dist/core/api-server.d.ts +25 -0
  34. package/dist/core/api-server.js +286 -0
  35. package/dist/core/audio.d.ts +50 -0
  36. package/dist/core/audio.js +68 -0
  37. package/dist/core/context-discovery.d.ts +16 -0
  38. package/dist/core/context-discovery.js +107 -0
  39. package/dist/core/context-refs.d.ts +29 -0
  40. package/dist/core/context-refs.js +162 -0
  41. package/dist/core/gateway.d.ts +53 -0
  42. package/dist/core/gateway.js +80 -0
  43. package/dist/core/heartbeat.d.ts +19 -0
  44. package/dist/core/heartbeat.js +50 -0
  45. package/dist/core/hooks.d.ts +28 -0
  46. package/dist/core/hooks.js +82 -0
  47. package/dist/core/ide-bridge.d.ts +53 -0
  48. package/dist/core/ide-bridge.js +97 -0
  49. package/dist/core/node-network.d.ts +23 -0
  50. package/dist/core/node-network.js +77 -0
  51. package/dist/core/profiles.d.ts +27 -0
  52. package/dist/core/profiles.js +131 -0
  53. package/dist/core/sandbox.d.ts +25 -0
  54. package/dist/core/sandbox.js +84 -1
  55. package/dist/core/session-manager.d.ts +33 -0
  56. package/dist/core/session-manager.js +157 -0
  57. package/dist/core/vision.d.ts +45 -0
  58. package/dist/core/vision.js +177 -0
  59. package/dist/index.d.ts +64 -1
  60. package/dist/index.js +86 -3
  61. package/dist/memory/context-compressor.d.ts +43 -0
  62. package/dist/memory/context-compressor.js +167 -0
  63. package/dist/memory/index.d.ts +4 -0
  64. package/dist/memory/index.js +5 -1
  65. package/dist/memory/user-profiler.d.ts +50 -0
  66. package/dist/memory/user-profiler.js +201 -0
  67. package/dist/schema/oad.d.ts +12 -12
  68. package/dist/security/approvals.d.ts +53 -0
  69. package/dist/security/approvals.js +115 -0
  70. package/dist/security/elevated.d.ts +41 -0
  71. package/dist/security/elevated.js +89 -0
  72. package/dist/security/index.d.ts +6 -0
  73. package/dist/security/index.js +7 -1
  74. package/dist/security/secrets.d.ts +34 -0
  75. package/dist/security/secrets.js +115 -0
  76. package/dist/tools/builtin/browser.d.ts +47 -0
  77. package/dist/tools/builtin/browser.js +284 -0
  78. package/dist/tools/builtin/home-assistant.d.ts +12 -0
  79. package/dist/tools/builtin/home-assistant.js +126 -0
  80. package/dist/tools/builtin/index.d.ts +6 -1
  81. package/dist/tools/builtin/index.js +18 -2
  82. package/dist/tools/builtin/rl-tools.d.ts +13 -0
  83. package/dist/tools/builtin/rl-tools.js +228 -0
  84. package/dist/tools/builtin/vision.d.ts +6 -0
  85. package/dist/tools/builtin/vision.js +61 -0
  86. package/package.json +3 -3
  87. package/src/channels/dingtalk.ts +46 -0
  88. package/src/channels/googlechat.ts +42 -0
  89. package/src/channels/imessage.ts +32 -0
  90. package/src/channels/irc.ts +82 -0
  91. package/src/channels/line.ts +33 -0
  92. package/src/channels/matrix.ts +34 -0
  93. package/src/channels/mattermost.ts +57 -0
  94. package/src/channels/msteams.ts +33 -0
  95. package/src/channels/nostr.ts +33 -0
  96. package/src/channels/qq.ts +34 -0
  97. package/src/channels/signal.ts +33 -0
  98. package/src/channels/sms.ts +34 -0
  99. package/src/channels/twitch.ts +65 -0
  100. package/src/channels/voice-call.ts +100 -0
  101. package/src/channels/whatsapp.ts +33 -0
  102. package/src/cli.ts +40 -0
  103. package/src/core/api-server.ts +277 -0
  104. package/src/core/audio.ts +98 -0
  105. package/src/core/context-discovery.ts +85 -0
  106. package/src/core/context-refs.ts +140 -0
  107. package/src/core/gateway.ts +106 -0
  108. package/src/core/heartbeat.ts +51 -0
  109. package/src/core/hooks.ts +105 -0
  110. package/src/core/ide-bridge.ts +133 -0
  111. package/src/core/node-network.ts +86 -0
  112. package/src/core/profiles.ts +122 -0
  113. package/src/core/sandbox.ts +100 -0
  114. package/src/core/session-manager.ts +137 -0
  115. package/src/core/vision.ts +180 -0
  116. package/src/index.ts +84 -1
  117. package/src/memory/context-compressor.ts +189 -0
  118. package/src/memory/index.ts +4 -0
  119. package/src/memory/user-profiler.ts +215 -0
  120. package/src/security/approvals.ts +143 -0
  121. package/src/security/elevated.ts +105 -0
  122. package/src/security/index.ts +6 -0
  123. package/src/security/secrets.ts +129 -0
  124. package/src/tools/builtin/browser.ts +299 -0
  125. package/src/tools/builtin/home-assistant.ts +116 -0
  126. package/src/tools/builtin/index.ts +9 -2
  127. package/src/tools/builtin/rl-tools.ts +243 -0
  128. package/src/tools/builtin/vision.ts +64 -0
  129. package/tests/api-server.test.ts +148 -0
  130. package/tests/approvals.test.ts +89 -0
  131. package/tests/audio.test.ts +40 -0
  132. package/tests/browser.test.ts +179 -0
  133. package/tests/builtin-tools.test.ts +83 -83
  134. package/tests/channels-extra.test.ts +45 -0
  135. package/tests/context-compressor.test.ts +172 -0
  136. package/tests/context-refs.test.ts +121 -0
  137. package/tests/elevated.test.ts +69 -0
  138. package/tests/gateway.test.ts +63 -71
  139. package/tests/home-assistant.test.ts +40 -0
  140. package/tests/hooks.test.ts +79 -0
  141. package/tests/ide-bridge.test.ts +38 -0
  142. package/tests/node-network.test.ts +74 -0
  143. package/tests/profiles.test.ts +61 -0
  144. package/tests/rl-tools.test.ts +93 -0
  145. package/tests/sandbox-manager.test.ts +46 -0
  146. package/tests/secrets.test.ts +107 -0
  147. package/tests/tools/builtin-extended.test.ts +138 -138
  148. package/tests/user-profiler.test.ts +169 -0
  149. package/tests/v090-features.test.ts +254 -0
  150. package/tests/vision.test.ts +61 -0
  151. package/tests/voice-call.test.ts +47 -0
@@ -0,0 +1,215 @@
1
+ import type { Message } from '../core/types';
2
+
3
+ export interface UserProfile {
4
+ preferences: Record<string, string>;
5
+ communication_style: string;
6
+ expertise_areas: string[];
7
+ common_requests: string[];
8
+ last_updated: number;
9
+ }
10
+
11
+ const EMPTY_PROFILE: UserProfile = {
12
+ preferences: {},
13
+ communication_style: 'unknown',
14
+ expertise_areas: [],
15
+ common_requests: [],
16
+ last_updated: 0,
17
+ };
18
+
19
+ /**
20
+ * DeepBrain-powered user profiling from conversation signals.
21
+ */
22
+ export class UserProfiler {
23
+ private observationCount = 0;
24
+ private signals = {
25
+ languages: new Map<string, number>(),
26
+ techKeywords: new Set<string>(),
27
+ styleSignals: { brief: 0, detailed: 0, formal: 0, casual: 0 },
28
+ requestTypes: new Map<string, number>(),
29
+ };
30
+
31
+ private readonly LEARN_INTERVAL = 20;
32
+
33
+ /**
34
+ * Detect language mix of a text.
35
+ */
36
+ private detectLanguage(text: string): string {
37
+ let cn = 0, en = 0;
38
+ for (const char of text) {
39
+ const code = char.codePointAt(0) ?? 0;
40
+ if (code >= 0x4e00 && code <= 0x9fff) cn++;
41
+ else if ((code >= 0x41 && code <= 0x5a) || (code >= 0x61 && code <= 0x7a)) en++;
42
+ }
43
+ if (cn > 0 && en > 0) return 'mixed';
44
+ if (cn > en) return 'chinese';
45
+ return 'english';
46
+ }
47
+
48
+ /**
49
+ * Detect technical level from content.
50
+ */
51
+ private detectTechLevel(text: string): string {
52
+ const expertTerms = /\b(kubernetes|k8s|microservice|architecture|distributed|consensus|raft|paxos|sharding|vector db|embedding|fine-?tun|transformer|CUDA|inference|quantiz|LoRA|RAG)\b/i;
53
+ const intermediateTerms = /\b(API|REST|GraphQL|Docker|CI\/CD|database|deploy|cloud|React|TypeScript|Python|async|cache|redis|nginx)\b/i;
54
+
55
+ if (expertTerms.test(text)) return 'expert';
56
+ if (intermediateTerms.test(text)) return 'intermediate';
57
+ return 'beginner';
58
+ }
59
+
60
+ /**
61
+ * Detect communication style.
62
+ */
63
+ private detectStyle(text: string): void {
64
+ if (text.length < 50) this.signals.styleSignals.brief++;
65
+ else if (text.length > 300) this.signals.styleSignals.detailed++;
66
+
67
+ if (/\b(please|kindly|would you|could you|请问|烦请|麻烦)\b/i.test(text)) {
68
+ this.signals.styleSignals.formal++;
69
+ }
70
+ if (/[!]{2,}|lol|haha|😂|🤣|哈哈|牛|666|👍/i.test(text)) {
71
+ this.signals.styleSignals.casual++;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Extract domain keywords.
77
+ */
78
+ private extractDomainKeywords(text: string): void {
79
+ const techWords = text.match(/\b[A-Z][a-zA-Z]{2,}(?:\.js|\.ts|\.py)?\b/g) ?? [];
80
+ techWords.forEach(w => this.signals.techKeywords.add(w));
81
+ // Chinese tech terms
82
+ const cnTerms = text.match(/(?:人工智能|机器学习|深度学习|大模型|微服务|架构|部署|运维|前端|后端|数据库|缓存|分布式)/g) ?? [];
83
+ cnTerms.forEach(w => this.signals.techKeywords.add(w));
84
+ }
85
+
86
+ /**
87
+ * Classify request type.
88
+ */
89
+ private classifyRequest(text: string): string {
90
+ if (/\b(how to|怎么|如何|how do)\b/i.test(text)) return 'how-to';
91
+ if (/\b(why|为什么|原因)\b/i.test(text)) return 'explanation';
92
+ if (/\b(fix|error|bug|报错|出错|failed)\b/i.test(text)) return 'debugging';
93
+ if (/\b(review|评审|看看|check)\b/i.test(text)) return 'review';
94
+ if (/\b(create|build|write|写|创建|生成)\b/i.test(text)) return 'creation';
95
+ return 'general';
96
+ }
97
+
98
+ /**
99
+ * Observe a user message and accumulate profile signals.
100
+ */
101
+ async observe(message: Message, brain?: any): Promise<void> {
102
+ if (message.role !== 'user') return;
103
+
104
+ const text = message.content;
105
+
106
+ // Language
107
+ const lang = this.detectLanguage(text);
108
+ this.signals.languages.set(lang, (this.signals.languages.get(lang) ?? 0) + 1);
109
+
110
+ // Style
111
+ this.detectStyle(text);
112
+
113
+ // Domain keywords
114
+ this.extractDomainKeywords(text);
115
+
116
+ // Request type
117
+ const reqType = this.classifyRequest(text);
118
+ this.signals.requestTypes.set(reqType, (this.signals.requestTypes.get(reqType) ?? 0) + 1);
119
+
120
+ this.observationCount++;
121
+
122
+ // Periodically persist to brain
123
+ if (brain?.learn && this.observationCount % this.LEARN_INTERVAL === 0) {
124
+ const profile = this.buildProfileFromSignals();
125
+ try {
126
+ await brain.learn(JSON.stringify(profile), { insight_type: 'user_profile' });
127
+ } catch { /* non-critical */ }
128
+ }
129
+ }
130
+
131
+ private buildProfileFromSignals(): UserProfile {
132
+ // Language preference
133
+ let topLang = 'english';
134
+ let maxCount = 0;
135
+ for (const [lang, count] of this.signals.languages) {
136
+ if (count > maxCount) { topLang = lang; maxCount = count; }
137
+ }
138
+
139
+ // Communication style
140
+ const ss = this.signals.styleSignals;
141
+ const styles = [
142
+ ['brief', ss.brief], ['detailed', ss.detailed],
143
+ ['formal', ss.formal], ['casual', ss.casual],
144
+ ] as const;
145
+ const topStyle = styles.reduce((a, b) => (b[1] > a[1] ? b : a))[0];
146
+
147
+ // Top request types
148
+ const topRequests = [...this.signals.requestTypes.entries()]
149
+ .sort((a, b) => b[1] - a[1])
150
+ .slice(0, 5)
151
+ .map(([t]) => t);
152
+
153
+ return {
154
+ preferences: { language: topLang },
155
+ communication_style: topStyle,
156
+ expertise_areas: [...this.signals.techKeywords].slice(0, 20),
157
+ common_requests: topRequests,
158
+ last_updated: Date.now(),
159
+ };
160
+ }
161
+
162
+ /**
163
+ * Get user profile, optionally from brain recall.
164
+ */
165
+ async getProfile(brain?: any): Promise<UserProfile> {
166
+ // First try local signals
167
+ if (this.observationCount > 0) {
168
+ return this.buildProfileFromSignals();
169
+ }
170
+
171
+ // Fallback to brain recall
172
+ if (brain?.recall) {
173
+ try {
174
+ const results = await brain.recall('user profile preferences style');
175
+ if (Array.isArray(results) && results.length > 0) {
176
+ const raw = typeof results[0] === 'string' ? results[0] : results[0].content;
177
+ return { ...EMPTY_PROFILE, ...JSON.parse(raw) };
178
+ }
179
+ } catch { /* ignore parse errors */ }
180
+ }
181
+
182
+ return { ...EMPTY_PROFILE };
183
+ }
184
+
185
+ /**
186
+ * Enhance a system prompt with user profile context.
187
+ */
188
+ enhance(systemPrompt: string, profile: UserProfile): string {
189
+ const hints: string[] = [];
190
+
191
+ if (profile.preferences.language) {
192
+ const langMap: Record<string, string> = {
193
+ chinese: 'User prefers Chinese responses.',
194
+ english: 'User prefers English responses.',
195
+ mixed: 'User uses mixed Chinese/English. Match their style.',
196
+ };
197
+ if (langMap[profile.preferences.language]) hints.push(langMap[profile.preferences.language]);
198
+ }
199
+
200
+ if (profile.communication_style && profile.communication_style !== 'unknown') {
201
+ hints.push(`User communication style: ${profile.communication_style}.`);
202
+ }
203
+
204
+ if (profile.expertise_areas.length > 0) {
205
+ hints.push(`User expertise: ${profile.expertise_areas.slice(0, 10).join(', ')}.`);
206
+ }
207
+
208
+ if (profile.common_requests.length > 0) {
209
+ hints.push(`Common request types: ${profile.common_requests.join(', ')}.`);
210
+ }
211
+
212
+ if (hints.length === 0) return systemPrompt;
213
+ return `${systemPrompt}\n\n[User Profile] ${hints.join(' ')}`;
214
+ }
215
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Approvals Module - v1.0.0
3
+ * Policy-based exec approval system with queue, expiry, history, and callbacks.
4
+ */
5
+
6
+ import { randomUUID } from 'crypto';
7
+
8
+ export type ExecApprovalPolicy = 'always' | 'elevated-only' | 'never' | 'allowlist';
9
+
10
+ export interface ExecApprovalRequest {
11
+ id: string;
12
+ command: string;
13
+ elevated: boolean;
14
+ requestedAt: number;
15
+ expiresAt: number;
16
+ status: 'pending' | 'approved' | 'denied' | 'expired';
17
+ approvedBy?: string;
18
+ reason?: string;
19
+ }
20
+
21
+ export interface ExecApprovalHistory {
22
+ request: ExecApprovalRequest;
23
+ resolvedAt: number;
24
+ }
25
+
26
+ export type ApprovalRequestCallback = (request: ExecApprovalRequest) => void;
27
+
28
+ export class ExecApprovalManager {
29
+ private policy: ExecApprovalPolicy;
30
+ private pending: Map<string, ExecApprovalRequest> = new Map();
31
+ private history: ExecApprovalHistory[] = [];
32
+ private allowedCommands: Set<string> = new Set();
33
+ private expiryMs: number;
34
+ private onRequestCallback?: ApprovalRequestCallback;
35
+ private expiryTimer?: ReturnType<typeof setInterval>;
36
+
37
+ constructor(options: {
38
+ policy?: ExecApprovalPolicy;
39
+ expiryMs?: number;
40
+ allowedCommands?: string[];
41
+ onRequest?: ApprovalRequestCallback;
42
+ } = {}) {
43
+ this.policy = options.policy ?? 'elevated-only';
44
+ this.expiryMs = options.expiryMs ?? 300_000; // 5 min default
45
+ this.onRequestCallback = options.onRequest;
46
+ if (options.allowedCommands) {
47
+ for (const cmd of options.allowedCommands) this.allowedCommands.add(cmd);
48
+ }
49
+ this.expiryTimer = setInterval(() => this.expirePending(), 10_000);
50
+ if (this.expiryTimer.unref) this.expiryTimer.unref();
51
+ }
52
+
53
+ getPolicy(): ExecApprovalPolicy { return this.policy; }
54
+ setPolicy(p: ExecApprovalPolicy): void { this.policy = p; }
55
+
56
+ addAllowedCommand(cmd: string): void { this.allowedCommands.add(cmd); }
57
+ removeAllowedCommand(cmd: string): void { this.allowedCommands.delete(cmd); }
58
+ getAllowedCommands(): string[] { return [...this.allowedCommands]; }
59
+
60
+ needsApproval(command: string, elevated: boolean): boolean {
61
+ switch (this.policy) {
62
+ case 'never': return false;
63
+ case 'always': return true;
64
+ case 'elevated-only': return elevated;
65
+ case 'allowlist': return !this.isAllowed(command);
66
+ }
67
+ }
68
+
69
+ private isAllowed(command: string): boolean {
70
+ for (const allowed of this.allowedCommands) {
71
+ if (command.startsWith(allowed) || command === allowed) return true;
72
+ }
73
+ return false;
74
+ }
75
+
76
+ request(command: string, elevated: boolean = false): ExecApprovalRequest {
77
+ const now = Date.now();
78
+ const req: ExecApprovalRequest = {
79
+ id: randomUUID(),
80
+ command,
81
+ elevated,
82
+ requestedAt: now,
83
+ expiresAt: now + this.expiryMs,
84
+ status: 'pending',
85
+ };
86
+ this.pending.set(req.id, req);
87
+ this.onRequestCallback?.(req);
88
+ return req;
89
+ }
90
+
91
+ approve(id: string, approver: string): ExecApprovalRequest {
92
+ const req = this.pending.get(id);
93
+ if (!req) throw new Error(`Request ${id} not found`);
94
+ if (req.status !== 'pending') throw new Error(`Request ${id} already ${req.status}`);
95
+ req.status = 'approved';
96
+ req.approvedBy = approver;
97
+ this.pending.delete(id);
98
+ this.history.push({ request: req, resolvedAt: Date.now() });
99
+ return req;
100
+ }
101
+
102
+ deny(id: string, approver: string, reason?: string): ExecApprovalRequest {
103
+ const req = this.pending.get(id);
104
+ if (!req) throw new Error(`Request ${id} not found`);
105
+ if (req.status !== 'pending') throw new Error(`Request ${id} already ${req.status}`);
106
+ req.status = 'denied';
107
+ req.approvedBy = approver;
108
+ req.reason = reason;
109
+ this.pending.delete(id);
110
+ this.history.push({ request: req, resolvedAt: Date.now() });
111
+ return req;
112
+ }
113
+
114
+ getPending(): ExecApprovalRequest[] {
115
+ return [...this.pending.values()];
116
+ }
117
+
118
+ getHistory(): ExecApprovalHistory[] {
119
+ return [...this.history];
120
+ }
121
+
122
+ getRequest(id: string): ExecApprovalRequest | undefined {
123
+ return this.pending.get(id) ?? this.history.find(h => h.request.id === id)?.request;
124
+ }
125
+
126
+ private expirePending(): void {
127
+ const now = Date.now();
128
+ for (const [id, req] of this.pending) {
129
+ if (now >= req.expiresAt) {
130
+ req.status = 'expired';
131
+ this.pending.delete(id);
132
+ this.history.push({ request: req, resolvedAt: now });
133
+ }
134
+ }
135
+ }
136
+
137
+ /** Force expire check (for testing) */
138
+ checkExpiry(): void { this.expirePending(); }
139
+
140
+ destroy(): void {
141
+ if (this.expiryTimer) clearInterval(this.expiryTimer);
142
+ }
143
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Elevated Permissions Module - v1.0.0
3
+ * Elevation mode management with allowed commands, auto-revoke, and audit log.
4
+ */
5
+
6
+ export type ElevationMode = 'off' | 'ask' | 'on';
7
+
8
+ export interface ElevationAuditEntry {
9
+ timestamp: number;
10
+ action: 'elevate' | 'revoke' | 'execute' | 'deny';
11
+ command?: string;
12
+ reason?: string;
13
+ }
14
+
15
+ export class ElevatedManager {
16
+ private mode: ElevationMode;
17
+ private elevated: boolean = false;
18
+ private allowedCommands: RegExp[] = [];
19
+ private auditLog: ElevationAuditEntry[] = [];
20
+ private revokeTimer?: ReturnType<typeof setTimeout>;
21
+ private autoRevokeMs: number;
22
+
23
+ constructor(options: {
24
+ mode?: ElevationMode;
25
+ allowedCommands?: (string | RegExp)[];
26
+ autoRevokeMs?: number;
27
+ } = {}) {
28
+ this.mode = options.mode ?? 'ask';
29
+ this.autoRevokeMs = options.autoRevokeMs ?? 600_000; // 10 min
30
+ if (options.allowedCommands) {
31
+ for (const cmd of options.allowedCommands) {
32
+ this.allowedCommands.push(cmd instanceof RegExp ? cmd : new RegExp(`^${cmd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`));
33
+ }
34
+ }
35
+ }
36
+
37
+ getMode(): ElevationMode { return this.mode; }
38
+ setMode(mode: ElevationMode): void { this.mode = mode; }
39
+ isElevated(): boolean { return this.elevated; }
40
+
41
+ addAllowedCommand(pattern: string | RegExp): void {
42
+ this.allowedCommands.push(pattern instanceof RegExp ? pattern : new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`));
43
+ }
44
+
45
+ isCommandAllowed(command: string): boolean {
46
+ return this.allowedCommands.some(r => r.test(command));
47
+ }
48
+
49
+ elevate(reason?: string): boolean {
50
+ if (this.mode === 'off') return false;
51
+ this.elevated = true;
52
+ this.auditLog.push({ timestamp: Date.now(), action: 'elevate', reason });
53
+ this.startAutoRevoke();
54
+ return true;
55
+ }
56
+
57
+ revoke(reason?: string): void {
58
+ this.elevated = false;
59
+ this.clearAutoRevoke();
60
+ this.auditLog.push({ timestamp: Date.now(), action: 'revoke', reason });
61
+ }
62
+
63
+ canExecute(command: string): { allowed: boolean; needsElevation: boolean } {
64
+ if (this.isCommandAllowed(command)) return { allowed: true, needsElevation: false };
65
+ if (this.mode === 'off') return { allowed: true, needsElevation: false };
66
+ if (this.mode === 'on') {
67
+ if (!this.elevated) this.elevate('auto-on mode');
68
+ this.auditLog.push({ timestamp: Date.now(), action: 'execute', command });
69
+ return { allowed: true, needsElevation: false };
70
+ }
71
+ // ask mode
72
+ if (this.elevated) {
73
+ this.auditLog.push({ timestamp: Date.now(), action: 'execute', command });
74
+ return { allowed: true, needsElevation: false };
75
+ }
76
+ return { allowed: false, needsElevation: true };
77
+ }
78
+
79
+ getAuditLog(): ElevationAuditEntry[] {
80
+ return [...this.auditLog];
81
+ }
82
+
83
+ clearAuditLog(): void {
84
+ this.auditLog = [];
85
+ }
86
+
87
+ private startAutoRevoke(): void {
88
+ this.clearAutoRevoke();
89
+ this.revokeTimer = setTimeout(() => {
90
+ this.revoke('auto-revoke timer');
91
+ }, this.autoRevokeMs);
92
+ if (this.revokeTimer.unref) this.revokeTimer.unref();
93
+ }
94
+
95
+ private clearAutoRevoke(): void {
96
+ if (this.revokeTimer) {
97
+ clearTimeout(this.revokeTimer);
98
+ this.revokeTimer = undefined;
99
+ }
100
+ }
101
+
102
+ destroy(): void {
103
+ this.clearAutoRevoke();
104
+ }
105
+ }
@@ -1,3 +1,9 @@
1
1
  export { ApprovalManager } from './approval';
2
2
  export type { ApprovalPolicy, ApprovalRequest } from './approval';
3
3
  export { KeyManager } from './keys';
4
+ export { ExecApprovalManager } from './approvals';
5
+ export type { ExecApprovalPolicy, ExecApprovalRequest, ExecApprovalHistory, ApprovalRequestCallback } from './approvals';
6
+ export { ElevatedManager } from './elevated';
7
+ export type { ElevationMode, ElevationAuditEntry } from './elevated';
8
+ export { SecretsManager } from './secrets';
9
+ export type { SecretsStore } from './secrets';
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Secrets Manager - v1.0.0
3
+ * AES-256-GCM encrypted secrets storage with rotation, export/import.
4
+ */
5
+
6
+ import { randomBytes, createCipheriv, createDecipheriv, scryptSync } from 'crypto';
7
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
8
+ import { dirname, join } from 'path';
9
+ import { homedir } from 'os';
10
+
11
+ const ALGORITHM = 'aes-256-gcm';
12
+ const KEY_LEN = 32;
13
+ const IV_LEN = 12;
14
+ const SALT_LEN = 16;
15
+ const TAG_LEN = 16;
16
+
17
+ export interface SecretsStore {
18
+ version: number;
19
+ secrets: Record<string, string>;
20
+ }
21
+
22
+ export class SecretsManager {
23
+ private masterKey: Buffer;
24
+ private filePath: string;
25
+ private store: SecretsStore;
26
+
27
+ constructor(options: { password: string; filePath?: string }) {
28
+ this.filePath = options.filePath ?? join(homedir(), '.opc', 'secrets.enc');
29
+ // Derive a stable key from password (we store salt in the file)
30
+ this.masterKey = Buffer.alloc(KEY_LEN); // placeholder, set on load/init
31
+ this.store = { version: 1, secrets: {} };
32
+ this.init(options.password);
33
+ }
34
+
35
+ private init(password: string): void {
36
+ if (existsSync(this.filePath)) {
37
+ this.load(password);
38
+ } else {
39
+ const salt = randomBytes(SALT_LEN);
40
+ this.masterKey = scryptSync(password, salt, KEY_LEN) as Buffer;
41
+ this.store = { version: 1, secrets: {} };
42
+ this.save(salt);
43
+ }
44
+ }
45
+
46
+ private load(password: string): void {
47
+ const data = readFileSync(this.filePath);
48
+ const salt = data.subarray(0, SALT_LEN);
49
+ const iv = data.subarray(SALT_LEN, SALT_LEN + IV_LEN);
50
+ const tag = data.subarray(SALT_LEN + IV_LEN, SALT_LEN + IV_LEN + TAG_LEN);
51
+ const encrypted = data.subarray(SALT_LEN + IV_LEN + TAG_LEN);
52
+
53
+ this.masterKey = scryptSync(password, salt, KEY_LEN) as Buffer;
54
+ const decipher = createDecipheriv(ALGORITHM, this.masterKey, iv);
55
+ decipher.setAuthTag(tag);
56
+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
57
+ this.store = JSON.parse(decrypted.toString('utf8'));
58
+ }
59
+
60
+ private save(salt?: Buffer): void {
61
+ const dir = dirname(this.filePath);
62
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
63
+
64
+ if (!salt && existsSync(this.filePath)) {
65
+ salt = readFileSync(this.filePath).subarray(0, SALT_LEN);
66
+ }
67
+ if (!salt) salt = randomBytes(SALT_LEN);
68
+
69
+ const iv = randomBytes(IV_LEN);
70
+ const cipher = createCipheriv(ALGORITHM, this.masterKey, iv);
71
+ const encrypted = Buffer.concat([cipher.update(JSON.stringify(this.store), 'utf8'), cipher.final()]);
72
+ const tag = cipher.getAuthTag();
73
+
74
+ writeFileSync(this.filePath, Buffer.concat([salt, iv, tag, encrypted]));
75
+ }
76
+
77
+ set(key: string, value: string): void {
78
+ this.store.secrets[key] = value;
79
+ this.save();
80
+ }
81
+
82
+ get(key: string): string | undefined {
83
+ return this.store.secrets[key];
84
+ }
85
+
86
+ delete(key: string): boolean {
87
+ if (!(key in this.store.secrets)) return false;
88
+ delete this.store.secrets[key];
89
+ this.save();
90
+ return true;
91
+ }
92
+
93
+ list(): string[] {
94
+ return Object.keys(this.store.secrets);
95
+ }
96
+
97
+ has(key: string): boolean {
98
+ return key in this.store.secrets;
99
+ }
100
+
101
+ /** Inject secrets into env-like object */
102
+ inject(env: Record<string, string | undefined>, keys?: string[]): Record<string, string | undefined> {
103
+ const toInject = keys ?? this.list();
104
+ for (const k of toInject) {
105
+ if (this.has(k)) env[k] = this.store.secrets[k];
106
+ }
107
+ return env;
108
+ }
109
+
110
+ /** Rotate: re-encrypt with new password */
111
+ rotate(newPassword: string): void {
112
+ const salt = randomBytes(SALT_LEN);
113
+ this.masterKey = scryptSync(newPassword, salt, KEY_LEN) as Buffer;
114
+ this.save(salt);
115
+ }
116
+
117
+ /** Export as encrypted buffer */
118
+ exportEncrypted(): Buffer {
119
+ return readFileSync(this.filePath);
120
+ }
121
+
122
+ /** Import from encrypted buffer (must know password) */
123
+ static importEncrypted(data: Buffer, password: string, filePath: string): SecretsManager {
124
+ const dir = dirname(filePath);
125
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
126
+ writeFileSync(filePath, data);
127
+ return new SecretsManager({ password, filePath });
128
+ }
129
+ }