@quantiya/codevibe-codex-plugin 1.0.7 → 1.0.9
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/dist/server.js +22 -1051
- package/package.json +5 -7
- package/dist/approval-detector.js +0 -174
- package/dist/appsync-client.js +0 -937
- package/dist/auth-cli.js +0 -241
- package/dist/config.js +0 -116
- package/dist/crypto-service.js +0 -278
- package/dist/event-mapper.js +0 -302
- package/dist/key-manager.js +0 -287
- package/dist/logger.js +0 -18
- package/dist/prompt-parser.js +0 -8
- package/dist/prompt-responder.js +0 -78
- package/dist/session-id-cache.js +0 -90
- package/dist/session-log-watcher.js +0 -372
- package/dist/tmux-pane-observer.js +0 -255
- package/dist/token-storage.js +0 -169
- package/dist/types.js +0 -17
package/dist/auth-cli.js
DELETED
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
"use strict";
|
|
3
|
-
/**
|
|
4
|
-
* CLI OAuth Authentication for CodeVibe Codex Plugin
|
|
5
|
-
*
|
|
6
|
-
* Usage:
|
|
7
|
-
* node auth-cli.js login - Authenticate via browser OAuth
|
|
8
|
-
* node auth-cli.js logout - Clear stored tokens
|
|
9
|
-
* node auth-cli.js status - Show current authentication status
|
|
10
|
-
*/
|
|
11
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
12
|
-
if (k2 === undefined) k2 = k;
|
|
13
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
14
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
15
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
16
|
-
}
|
|
17
|
-
Object.defineProperty(o, k2, desc);
|
|
18
|
-
}) : (function(o, m, k, k2) {
|
|
19
|
-
if (k2 === undefined) k2 = k;
|
|
20
|
-
o[k2] = m[k];
|
|
21
|
-
}));
|
|
22
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
23
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
24
|
-
}) : function(o, v) {
|
|
25
|
-
o["default"] = v;
|
|
26
|
-
});
|
|
27
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
28
|
-
var ownKeys = function(o) {
|
|
29
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
30
|
-
var ar = [];
|
|
31
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
32
|
-
return ar;
|
|
33
|
-
};
|
|
34
|
-
return ownKeys(o);
|
|
35
|
-
};
|
|
36
|
-
return function (mod) {
|
|
37
|
-
if (mod && mod.__esModule) return mod;
|
|
38
|
-
var result = {};
|
|
39
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
40
|
-
__setModuleDefault(result, mod);
|
|
41
|
-
return result;
|
|
42
|
-
};
|
|
43
|
-
})();
|
|
44
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
45
|
-
const crypto = __importStar(require("crypto"));
|
|
46
|
-
const http = __importStar(require("http"));
|
|
47
|
-
const path = __importStar(require("path"));
|
|
48
|
-
const child_process_1 = require("child_process");
|
|
49
|
-
const dotenv = __importStar(require("dotenv"));
|
|
50
|
-
// Load environment-specific .env file from the plugin directory
|
|
51
|
-
const pluginDir = path.resolve(__dirname, '..');
|
|
52
|
-
const environment = process.env.ENVIRONMENT || 'production';
|
|
53
|
-
if (process.env.ENVIRONMENT) {
|
|
54
|
-
const envFile = `.env.${environment}`;
|
|
55
|
-
dotenv.config({ path: path.join(pluginDir, envFile), debug: false });
|
|
56
|
-
if (!process.env.APPSYNC_URL) {
|
|
57
|
-
dotenv.config({ path: path.join(pluginDir, '.env'), debug: false });
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
const config_1 = require("./config");
|
|
61
|
-
const logger_1 = require("./logger");
|
|
62
|
-
const token_storage_1 = require("./token-storage");
|
|
63
|
-
const CALLBACK_PORT = 8080;
|
|
64
|
-
const CALLBACK_PATH = '/callback';
|
|
65
|
-
const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
|
|
66
|
-
const colors = {
|
|
67
|
-
reset: '\x1b[0m',
|
|
68
|
-
green: '\x1b[32m',
|
|
69
|
-
red: '\x1b[31m',
|
|
70
|
-
yellow: '\x1b[33m',
|
|
71
|
-
cyan: '\x1b[36m',
|
|
72
|
-
dim: '\x1b[2m',
|
|
73
|
-
};
|
|
74
|
-
function openBrowser(url) {
|
|
75
|
-
(0, child_process_1.spawn)('open', [url], { detached: true, stdio: 'ignore' }).unref();
|
|
76
|
-
}
|
|
77
|
-
function generateState() {
|
|
78
|
-
return crypto.randomBytes(32).toString('hex');
|
|
79
|
-
}
|
|
80
|
-
function buildAuthUrl(state) {
|
|
81
|
-
const params = new URLSearchParams({
|
|
82
|
-
client_id: config_1.config.aws.cognitoClientId,
|
|
83
|
-
response_type: 'code',
|
|
84
|
-
scope: 'email openid profile',
|
|
85
|
-
redirect_uri: REDIRECT_URI,
|
|
86
|
-
state: state,
|
|
87
|
-
});
|
|
88
|
-
return `https://${config_1.config.aws.cognitoDomain}/oauth2/authorize?${params.toString()}`;
|
|
89
|
-
}
|
|
90
|
-
async function exchangeCodeForTokens(code) {
|
|
91
|
-
const tokenUrl = `https://${config_1.config.aws.cognitoDomain}/oauth2/token`;
|
|
92
|
-
const params = new URLSearchParams({
|
|
93
|
-
grant_type: 'authorization_code',
|
|
94
|
-
client_id: config_1.config.aws.cognitoClientId,
|
|
95
|
-
code: code,
|
|
96
|
-
redirect_uri: REDIRECT_URI,
|
|
97
|
-
});
|
|
98
|
-
const response = await fetch(tokenUrl, {
|
|
99
|
-
method: 'POST',
|
|
100
|
-
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
101
|
-
body: params.toString(),
|
|
102
|
-
});
|
|
103
|
-
if (!response.ok) {
|
|
104
|
-
const errorText = await response.text();
|
|
105
|
-
throw new Error(`Token exchange failed: ${response.status} ${errorText}`);
|
|
106
|
-
}
|
|
107
|
-
const data = await response.json();
|
|
108
|
-
return {
|
|
109
|
-
accessToken: data.access_token,
|
|
110
|
-
idToken: data.id_token,
|
|
111
|
-
refreshToken: data.refresh_token,
|
|
112
|
-
expiresIn: data.expires_in,
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
function decodeJwt(token) {
|
|
116
|
-
const parts = token.split('.');
|
|
117
|
-
if (parts.length !== 3)
|
|
118
|
-
throw new Error('Invalid JWT format');
|
|
119
|
-
const payload = Buffer.from(parts[1], 'base64').toString('utf-8');
|
|
120
|
-
return JSON.parse(payload);
|
|
121
|
-
}
|
|
122
|
-
async function login() {
|
|
123
|
-
console.log(`${colors.cyan}CodeVibe Codex Login${colors.reset}\n`);
|
|
124
|
-
const existingTokens = (0, token_storage_1.loadTokens)();
|
|
125
|
-
if (existingTokens && !(0, token_storage_1.isTokenExpired)(existingTokens)) {
|
|
126
|
-
console.log(`${colors.yellow}Already logged in as: ${existingTokens.email}${colors.reset}`);
|
|
127
|
-
console.log(`Token expires: ${new Date(existingTokens.expiresAt).toLocaleString()}`);
|
|
128
|
-
console.log(`\nRun '${colors.dim}codevibe-codex logout${colors.reset}' to sign out first.`);
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
const state = generateState();
|
|
132
|
-
const authUrl = buildAuthUrl(state);
|
|
133
|
-
console.log('Opening browser for authentication...');
|
|
134
|
-
console.log(`${colors.dim}Waiting for callback on ${REDIRECT_URI}...${colors.reset}\n`);
|
|
135
|
-
return new Promise((resolve, reject) => {
|
|
136
|
-
const server = http.createServer(async (req, res) => {
|
|
137
|
-
if (!req.url?.startsWith(CALLBACK_PATH)) {
|
|
138
|
-
res.writeHead(404);
|
|
139
|
-
res.end('Not found');
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
try {
|
|
143
|
-
const url = new URL(req.url, `http://localhost:${CALLBACK_PORT}`);
|
|
144
|
-
const code = url.searchParams.get('code');
|
|
145
|
-
const returnedState = url.searchParams.get('state');
|
|
146
|
-
const error = url.searchParams.get('error');
|
|
147
|
-
if (error)
|
|
148
|
-
throw new Error(`OAuth error: ${error}`);
|
|
149
|
-
if (returnedState !== state)
|
|
150
|
-
throw new Error('State mismatch');
|
|
151
|
-
if (!code)
|
|
152
|
-
throw new Error('No authorization code received');
|
|
153
|
-
console.log('Exchanging authorization code for tokens...');
|
|
154
|
-
const tokens = await exchangeCodeForTokens(code);
|
|
155
|
-
const idTokenPayload = decodeJwt(tokens.idToken);
|
|
156
|
-
const userId = idTokenPayload.sub;
|
|
157
|
-
const email = idTokenPayload.email || 'unknown';
|
|
158
|
-
const expiresAt = Date.now() + (tokens.expiresIn * 1000);
|
|
159
|
-
const storedTokens = {
|
|
160
|
-
accessToken: tokens.accessToken,
|
|
161
|
-
idToken: tokens.idToken,
|
|
162
|
-
refreshToken: tokens.refreshToken,
|
|
163
|
-
expiresAt,
|
|
164
|
-
userId,
|
|
165
|
-
email,
|
|
166
|
-
};
|
|
167
|
-
(0, token_storage_1.saveTokens)(storedTokens);
|
|
168
|
-
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
169
|
-
res.end(`<!DOCTYPE html><html><head><title>Success</title></head><body style="font-family:system-ui;text-align:center;margin-top:50px"><h1 style="color:#22c55e">Authentication Successful!</h1><p>Signed in as <strong>${email}</strong></p><p>You can close this window.</p></body></html>`);
|
|
170
|
-
console.log(`\n${colors.green}✓ Authentication successful!${colors.reset}`);
|
|
171
|
-
console.log(` User: ${email}`);
|
|
172
|
-
console.log(` Tokens stored in: ${(0, token_storage_1.getTokenFilePath)()}`);
|
|
173
|
-
setTimeout(() => { server.close(() => { resolve(); process.exit(0); }); }, 1000);
|
|
174
|
-
}
|
|
175
|
-
catch (err) {
|
|
176
|
-
logger_1.logger.error('OAuth callback error:', err);
|
|
177
|
-
res.writeHead(400, { 'Content-Type': 'text/html' });
|
|
178
|
-
res.end(`<h1>Authentication Failed</h1><p>${err.message}</p>`);
|
|
179
|
-
console.log(`\n${colors.red}✗ Authentication failed: ${err.message}${colors.reset}`);
|
|
180
|
-
setTimeout(() => { server.close(() => { reject(err); process.exit(1); }); }, 1000);
|
|
181
|
-
}
|
|
182
|
-
});
|
|
183
|
-
server.on('error', (err) => {
|
|
184
|
-
console.log(`${colors.red}Error: ${err.code === 'EADDRINUSE' ? `Port ${CALLBACK_PORT} in use` : err.message}${colors.reset}`);
|
|
185
|
-
reject(err);
|
|
186
|
-
});
|
|
187
|
-
server.listen(CALLBACK_PORT, 'localhost', () => {
|
|
188
|
-
logger_1.logger.info('OAuth callback server started', { port: CALLBACK_PORT });
|
|
189
|
-
openBrowser(authUrl);
|
|
190
|
-
});
|
|
191
|
-
setTimeout(() => {
|
|
192
|
-
console.log(`\n${colors.yellow}Login timed out.${colors.reset}`);
|
|
193
|
-
server.close(() => { reject(new Error('Timeout')); process.exit(1); });
|
|
194
|
-
}, 2 * 60 * 1000);
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
async function logout() {
|
|
198
|
-
console.log(`${colors.cyan}CodeVibe Codex Logout${colors.reset}\n`);
|
|
199
|
-
const tokens = (0, token_storage_1.loadTokens)();
|
|
200
|
-
if (!tokens) {
|
|
201
|
-
console.log(`${colors.yellow}Not logged in.${colors.reset}`);
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
const email = tokens.email;
|
|
205
|
-
(0, token_storage_1.deleteTokens)();
|
|
206
|
-
console.log(`${colors.green}✓ Logged out successfully.${colors.reset}`);
|
|
207
|
-
console.log(` Previous user: ${email}`);
|
|
208
|
-
}
|
|
209
|
-
async function status() {
|
|
210
|
-
console.log(`${colors.cyan}CodeVibe Codex Auth Status${colors.reset}\n`);
|
|
211
|
-
const tokens = (0, token_storage_1.loadTokens)();
|
|
212
|
-
if (!tokens) {
|
|
213
|
-
console.log(`${colors.yellow}Not authenticated.${colors.reset}`);
|
|
214
|
-
console.log(`\nRun '${colors.dim}codevibe-codex login${colors.reset}' to sign in.`);
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
const expired = (0, token_storage_1.isTokenExpired)(tokens);
|
|
218
|
-
console.log(`${expired ? colors.yellow + '⚠ Token expired' : colors.green + '✓ Authenticated'}${colors.reset}`);
|
|
219
|
-
console.log(` User: ${tokens.email}`);
|
|
220
|
-
console.log(` Token expires: ${new Date(tokens.expiresAt).toLocaleString()}`);
|
|
221
|
-
console.log(` Token file: ${(0, token_storage_1.getTokenFilePath)()}`);
|
|
222
|
-
}
|
|
223
|
-
async function main() {
|
|
224
|
-
const command = process.argv[2];
|
|
225
|
-
switch (command) {
|
|
226
|
-
case 'login':
|
|
227
|
-
await login();
|
|
228
|
-
break;
|
|
229
|
-
case 'logout':
|
|
230
|
-
await logout();
|
|
231
|
-
break;
|
|
232
|
-
case 'status':
|
|
233
|
-
await status();
|
|
234
|
-
break;
|
|
235
|
-
default:
|
|
236
|
-
console.log('Usage:\n codevibe-codex login\n codevibe-codex logout\n codevibe-codex status');
|
|
237
|
-
process.exit(1);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
main().catch((err) => { logger_1.logger.error('Auth CLI error:', err); process.exit(1); });
|
|
241
|
-
//# sourceMappingURL=auth-cli.js.map
|
package/dist/config.js
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.config = void 0;
|
|
37
|
-
exports.validateConfig = validateConfig;
|
|
38
|
-
const dotenv = __importStar(require("dotenv"));
|
|
39
|
-
const path = __importStar(require("path"));
|
|
40
|
-
// Determine environment
|
|
41
|
-
// - If ENVIRONMENT is explicitly set, use that
|
|
42
|
-
// - Otherwise default to 'production' for marketplace users (no .env files)
|
|
43
|
-
const environment = process.env.ENVIRONMENT || 'production';
|
|
44
|
-
// Only load .env files if ENVIRONMENT is explicitly set (for development)
|
|
45
|
-
// This ensures marketplace users get production defaults without needing .env files
|
|
46
|
-
if (process.env.ENVIRONMENT) {
|
|
47
|
-
const envFile = `.env.${environment}`;
|
|
48
|
-
const envPath = path.resolve(__dirname, '..', envFile);
|
|
49
|
-
dotenv.config({ path: envPath, debug: false });
|
|
50
|
-
// Fallback to default .env if environment-specific file didn't load required vars
|
|
51
|
-
if (!process.env.APPSYNC_URL) {
|
|
52
|
-
dotenv.config({ debug: false });
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
function getOptionalEnv(key, defaultValue) {
|
|
56
|
-
return process.env[key] || defaultValue;
|
|
57
|
-
}
|
|
58
|
-
// Production defaults - these are public values (not secrets)
|
|
59
|
-
// Users can override via .env files for development
|
|
60
|
-
const PRODUCTION_DEFAULTS = {
|
|
61
|
-
APPSYNC_URL: 'https://jwhyxq4sgrgcdosewp5k4ns5ca.appsync-api.us-east-1.amazonaws.com/graphql',
|
|
62
|
-
COGNITO_USER_POOL_ID: 'us-east-1_mNRO0j5og',
|
|
63
|
-
COGNITO_CLIENT_ID: '5p04dbc9ojptc5r8n7605fg78f',
|
|
64
|
-
COGNITO_DOMAIN: 'codevibe-production.auth.us-east-1.amazoncognito.com',
|
|
65
|
-
};
|
|
66
|
-
// Get home directory for Codex sessions path
|
|
67
|
-
const os = __importStar(require("os"));
|
|
68
|
-
const CODEX_SESSIONS_DIR = path.join(os.homedir(), '.codex', 'sessions');
|
|
69
|
-
// Configuration object
|
|
70
|
-
exports.config = {
|
|
71
|
-
server: {
|
|
72
|
-
port: parseInt(getOptionalEnv('PORT', '3458'), 10),
|
|
73
|
-
host: getOptionalEnv('HOST', 'localhost'),
|
|
74
|
-
dynamicPort: getOptionalEnv('DYNAMIC_PORT', 'true').toLowerCase() === 'true', // Default to dynamic port
|
|
75
|
-
},
|
|
76
|
-
aws: {
|
|
77
|
-
region: getOptionalEnv('AWS_REGION', 'us-east-1'),
|
|
78
|
-
appsyncUrl: getOptionalEnv('APPSYNC_URL', PRODUCTION_DEFAULTS.APPSYNC_URL),
|
|
79
|
-
cognitoUserPoolId: getOptionalEnv('COGNITO_USER_POOL_ID', PRODUCTION_DEFAULTS.COGNITO_USER_POOL_ID),
|
|
80
|
-
cognitoClientId: getOptionalEnv('COGNITO_CLIENT_ID', PRODUCTION_DEFAULTS.COGNITO_CLIENT_ID),
|
|
81
|
-
cognitoDomain: getOptionalEnv('COGNITO_DOMAIN', PRODUCTION_DEFAULTS.COGNITO_DOMAIN),
|
|
82
|
-
},
|
|
83
|
-
codex: {
|
|
84
|
-
command: getOptionalEnv('CODEX_COMMAND', 'codex'),
|
|
85
|
-
defaultTimeout: parseInt(getOptionalEnv('CODEX_TIMEOUT', '60000'), 10),
|
|
86
|
-
sessionsDir: getOptionalEnv('CODEX_SESSIONS_DIR', CODEX_SESSIONS_DIR),
|
|
87
|
-
},
|
|
88
|
-
approval: {
|
|
89
|
-
timeoutMs: parseInt(getOptionalEnv('APPROVAL_TIMEOUT_MS', '5000'), 10),
|
|
90
|
-
},
|
|
91
|
-
logging: {
|
|
92
|
-
logFile: getOptionalEnv('LOG_FILE', '/tmp/codevibe-codex-mcp.log'),
|
|
93
|
-
level: getOptionalEnv('LOG_LEVEL', 'info'),
|
|
94
|
-
},
|
|
95
|
-
};
|
|
96
|
-
// Validate configuration
|
|
97
|
-
function validateConfig() {
|
|
98
|
-
const errors = [];
|
|
99
|
-
// Only validate port if not using dynamic allocation
|
|
100
|
-
if (!exports.config.server.dynamicPort && (exports.config.server.port < 1024 || exports.config.server.port > 65535)) {
|
|
101
|
-
errors.push('PORT must be between 1024 and 65535');
|
|
102
|
-
}
|
|
103
|
-
if (!exports.config.aws.appsyncUrl.startsWith('https://')) {
|
|
104
|
-
errors.push('APPSYNC_URL must start with https://');
|
|
105
|
-
}
|
|
106
|
-
if (exports.config.codex.defaultTimeout < 1000) {
|
|
107
|
-
errors.push('CODEX_TIMEOUT must be at least 1000ms');
|
|
108
|
-
}
|
|
109
|
-
if (exports.config.approval.timeoutMs < 1000) {
|
|
110
|
-
errors.push('APPROVAL_TIMEOUT_MS must be at least 1000ms');
|
|
111
|
-
}
|
|
112
|
-
if (errors.length > 0) {
|
|
113
|
-
throw new Error(`Configuration validation failed:\n${errors.join('\n')}`);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
//# sourceMappingURL=config.js.map
|
package/dist/crypto-service.js
DELETED
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
//
|
|
3
|
-
// crypto-service.ts
|
|
4
|
-
// CodeVibe Codex Plugin
|
|
5
|
-
//
|
|
6
|
-
// End-to-end encryption service using ECDH P-256 and AES-256-GCM
|
|
7
|
-
//
|
|
8
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
9
|
-
if (k2 === undefined) k2 = k;
|
|
10
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
11
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
12
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
13
|
-
}
|
|
14
|
-
Object.defineProperty(o, k2, desc);
|
|
15
|
-
}) : (function(o, m, k, k2) {
|
|
16
|
-
if (k2 === undefined) k2 = k;
|
|
17
|
-
o[k2] = m[k];
|
|
18
|
-
}));
|
|
19
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
20
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
21
|
-
}) : function(o, v) {
|
|
22
|
-
o["default"] = v;
|
|
23
|
-
});
|
|
24
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
25
|
-
var ownKeys = function(o) {
|
|
26
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
27
|
-
var ar = [];
|
|
28
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
29
|
-
return ar;
|
|
30
|
-
};
|
|
31
|
-
return ownKeys(o);
|
|
32
|
-
};
|
|
33
|
-
return function (mod) {
|
|
34
|
-
if (mod && mod.__esModule) return mod;
|
|
35
|
-
var result = {};
|
|
36
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
37
|
-
__setModuleDefault(result, mod);
|
|
38
|
-
return result;
|
|
39
|
-
};
|
|
40
|
-
})();
|
|
41
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
-
exports.cryptoService = exports.CryptoService = exports.ENCRYPTION_VERSION = exports.CryptoError = void 0;
|
|
43
|
-
const crypto = __importStar(require("crypto"));
|
|
44
|
-
// Errors that can occur during cryptographic operations
|
|
45
|
-
class CryptoError extends Error {
|
|
46
|
-
constructor(message) {
|
|
47
|
-
super(message);
|
|
48
|
-
this.name = 'CryptoError';
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
exports.CryptoError = CryptoError;
|
|
52
|
-
// Current encryption version for future algorithm upgrades
|
|
53
|
-
exports.ENCRYPTION_VERSION = 1;
|
|
54
|
-
// HKDF info string for key derivation
|
|
55
|
-
const HKDF_INFO = 'CodeVibe E2E v1';
|
|
56
|
-
/**
|
|
57
|
-
* Service for end-to-end encryption operations
|
|
58
|
-
*/
|
|
59
|
-
class CryptoService {
|
|
60
|
-
constructor() { }
|
|
61
|
-
static getInstance() {
|
|
62
|
-
if (!CryptoService.instance) {
|
|
63
|
-
CryptoService.instance = new CryptoService();
|
|
64
|
-
}
|
|
65
|
-
return CryptoService.instance;
|
|
66
|
-
}
|
|
67
|
-
// MARK: - Key Generation
|
|
68
|
-
/**
|
|
69
|
-
* Generate a new ECDH P-256 key pair
|
|
70
|
-
* @returns Object with privateKey (PEM), publicKey (base64 raw)
|
|
71
|
-
*/
|
|
72
|
-
generateKeyPair() {
|
|
73
|
-
const ecdh = crypto.createECDH('prime256v1');
|
|
74
|
-
ecdh.generateKeys();
|
|
75
|
-
// Get raw public key (uncompressed format without 0x04 prefix for compatibility)
|
|
76
|
-
const publicKeyRaw = ecdh.getPublicKey();
|
|
77
|
-
const publicKeyBase64 = publicKeyRaw.subarray(1).toString('base64'); // Skip 0x04 prefix
|
|
78
|
-
// Get private key as raw bytes
|
|
79
|
-
const privateKeyRaw = ecdh.getPrivateKey();
|
|
80
|
-
const privateKeyBase64 = privateKeyRaw.toString('base64');
|
|
81
|
-
return {
|
|
82
|
-
privateKey: privateKeyBase64,
|
|
83
|
-
publicKey: publicKeyBase64,
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Generate a random 256-bit session key
|
|
88
|
-
* @returns Base64-encoded session key
|
|
89
|
-
*/
|
|
90
|
-
generateSessionKey() {
|
|
91
|
-
const keyData = crypto.randomBytes(32); // 256 bits
|
|
92
|
-
return keyData.toString('base64');
|
|
93
|
-
}
|
|
94
|
-
// MARK: - Key Derivation
|
|
95
|
-
/**
|
|
96
|
-
* Derive a shared secret using ECDH and HKDF
|
|
97
|
-
* @param privateKeyBase64 Our private key (base64)
|
|
98
|
-
* @param publicKeyBase64 Other party's public key (base64)
|
|
99
|
-
* @returns 256-bit derived key as Buffer
|
|
100
|
-
*/
|
|
101
|
-
deriveSharedKey(privateKeyBase64, publicKeyBase64) {
|
|
102
|
-
try {
|
|
103
|
-
const ecdh = crypto.createECDH('prime256v1');
|
|
104
|
-
const privateKeyRaw = Buffer.from(privateKeyBase64, 'base64');
|
|
105
|
-
ecdh.setPrivateKey(privateKeyRaw);
|
|
106
|
-
// Add 0x04 prefix for uncompressed public key format
|
|
107
|
-
const publicKeyRaw = Buffer.concat([
|
|
108
|
-
Buffer.from([0x04]),
|
|
109
|
-
Buffer.from(publicKeyBase64, 'base64'),
|
|
110
|
-
]);
|
|
111
|
-
const sharedSecret = ecdh.computeSecret(publicKeyRaw);
|
|
112
|
-
// Derive key using HKDF-SHA256
|
|
113
|
-
const derivedKey = crypto.hkdfSync('sha256', sharedSecret, Buffer.alloc(0), // Empty salt
|
|
114
|
-
Buffer.from(HKDF_INFO, 'utf8'), 32 // 256 bits
|
|
115
|
-
);
|
|
116
|
-
return Buffer.from(derivedKey);
|
|
117
|
-
}
|
|
118
|
-
catch (error) {
|
|
119
|
-
throw new CryptoError(`Failed to derive shared key: ${error}`);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
// MARK: - Session Key Encryption
|
|
123
|
-
/**
|
|
124
|
-
* Encrypt a session key for a target device using ECDH
|
|
125
|
-
* @param sessionKeyBase64 The session key to encrypt (base64)
|
|
126
|
-
* @param targetPublicKeyBase64 Target device's public key (base64)
|
|
127
|
-
* @returns EncryptedSessionKey containing encrypted key and ephemeral public key
|
|
128
|
-
*/
|
|
129
|
-
encryptSessionKey(sessionKeyBase64, targetPublicKeyBase64) {
|
|
130
|
-
// Generate ephemeral key pair for this encryption
|
|
131
|
-
const ephemeralKeyPair = this.generateKeyPair();
|
|
132
|
-
// Derive shared key using ephemeral private + target public
|
|
133
|
-
const sharedKey = this.deriveSharedKey(ephemeralKeyPair.privateKey, targetPublicKeyBase64);
|
|
134
|
-
// Encrypt session key with derived key
|
|
135
|
-
const sessionKeyData = Buffer.from(sessionKeyBase64, 'base64');
|
|
136
|
-
const encryptedData = this.encrypt(sessionKeyData, sharedKey);
|
|
137
|
-
return {
|
|
138
|
-
encryptedKey: encryptedData.toString('base64'),
|
|
139
|
-
ephemeralPublicKey: ephemeralKeyPair.publicKey,
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Decrypt a session key using our private key
|
|
144
|
-
* @param encryptedSessionKey The encrypted session key data
|
|
145
|
-
* @param privateKeyBase64 Our device's private key (base64)
|
|
146
|
-
* @returns Decrypted session key (base64)
|
|
147
|
-
*/
|
|
148
|
-
decryptSessionKey(encryptedSessionKey, privateKeyBase64) {
|
|
149
|
-
// Derive shared key using our private + ephemeral public
|
|
150
|
-
const sharedKey = this.deriveSharedKey(privateKeyBase64, encryptedSessionKey.ephemeralPublicKey);
|
|
151
|
-
// Decrypt session key
|
|
152
|
-
const encryptedData = Buffer.from(encryptedSessionKey.encryptedKey, 'base64');
|
|
153
|
-
const decryptedData = this.decrypt(encryptedData, sharedKey);
|
|
154
|
-
return decryptedData.toString('base64');
|
|
155
|
-
}
|
|
156
|
-
// MARK: - Content Encryption/Decryption
|
|
157
|
-
/**
|
|
158
|
-
* Encrypt content using AES-256-GCM
|
|
159
|
-
* @param content String content to encrypt
|
|
160
|
-
* @param sessionKeyBase64 Session key (base64)
|
|
161
|
-
* @returns Base64-encoded ciphertext (nonce + ciphertext + tag)
|
|
162
|
-
*/
|
|
163
|
-
encryptContent(content, sessionKeyBase64) {
|
|
164
|
-
const sessionKey = Buffer.from(sessionKeyBase64, 'base64');
|
|
165
|
-
const contentData = Buffer.from(content, 'utf8');
|
|
166
|
-
const encryptedData = this.encrypt(contentData, sessionKey);
|
|
167
|
-
return encryptedData.toString('base64');
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Decrypt content using AES-256-GCM
|
|
171
|
-
* @param encryptedContent Base64-encoded ciphertext
|
|
172
|
-
* @param sessionKeyBase64 Session key (base64)
|
|
173
|
-
* @returns Decrypted string content
|
|
174
|
-
*/
|
|
175
|
-
decryptContent(encryptedContent, sessionKeyBase64) {
|
|
176
|
-
const sessionKey = Buffer.from(sessionKeyBase64, 'base64');
|
|
177
|
-
const encryptedData = Buffer.from(encryptedContent, 'base64');
|
|
178
|
-
const decryptedData = this.decrypt(encryptedData, sessionKey);
|
|
179
|
-
return decryptedData.toString('utf8');
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Encrypt JSON-serializable metadata
|
|
183
|
-
* @param metadata Object to encrypt
|
|
184
|
-
* @param sessionKeyBase64 Session key (base64)
|
|
185
|
-
* @returns Base64-encoded encrypted JSON
|
|
186
|
-
*/
|
|
187
|
-
encryptMetadata(metadata, sessionKeyBase64) {
|
|
188
|
-
const jsonString = JSON.stringify(metadata);
|
|
189
|
-
return this.encryptContent(jsonString, sessionKeyBase64);
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Decrypt encrypted metadata
|
|
193
|
-
* @param encryptedMetadata Base64-encoded encrypted JSON
|
|
194
|
-
* @param sessionKeyBase64 Session key (base64)
|
|
195
|
-
* @returns Decrypted object
|
|
196
|
-
*/
|
|
197
|
-
decryptMetadata(encryptedMetadata, sessionKeyBase64) {
|
|
198
|
-
const jsonString = this.decryptContent(encryptedMetadata, sessionKeyBase64);
|
|
199
|
-
return JSON.parse(jsonString);
|
|
200
|
-
}
|
|
201
|
-
// MARK: - Binary Data Encryption (for attachments)
|
|
202
|
-
/**
|
|
203
|
-
* Encrypt binary data using AES-256-GCM
|
|
204
|
-
* @param data Binary data to encrypt (Buffer)
|
|
205
|
-
* @param sessionKeyBase64 Session key (base64)
|
|
206
|
-
* @returns Encrypted data (Buffer containing nonce + ciphertext + tag)
|
|
207
|
-
*/
|
|
208
|
-
encryptData(data, sessionKeyBase64) {
|
|
209
|
-
const sessionKey = Buffer.from(sessionKeyBase64, 'base64');
|
|
210
|
-
return this.encrypt(data, sessionKey);
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Decrypt binary data using AES-256-GCM
|
|
214
|
-
* @param encryptedData Encrypted data (Buffer containing nonce + ciphertext + tag)
|
|
215
|
-
* @param sessionKeyBase64 Session key (base64)
|
|
216
|
-
* @returns Decrypted binary data (Buffer)
|
|
217
|
-
*/
|
|
218
|
-
decryptData(encryptedData, sessionKeyBase64) {
|
|
219
|
-
const sessionKey = Buffer.from(sessionKeyBase64, 'base64');
|
|
220
|
-
return this.decrypt(encryptedData, sessionKey);
|
|
221
|
-
}
|
|
222
|
-
// MARK: - Low-level Encryption
|
|
223
|
-
/**
|
|
224
|
-
* Encrypt data using AES-256-GCM
|
|
225
|
-
* @param data Data to encrypt
|
|
226
|
-
* @param key Symmetric key (32 bytes)
|
|
227
|
-
* @returns Combined nonce + ciphertext + tag
|
|
228
|
-
*/
|
|
229
|
-
encrypt(data, key) {
|
|
230
|
-
// Generate random 12-byte nonce (IV)
|
|
231
|
-
const nonce = crypto.randomBytes(12);
|
|
232
|
-
const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce);
|
|
233
|
-
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
234
|
-
const tag = cipher.getAuthTag();
|
|
235
|
-
// Combine: nonce (12 bytes) + ciphertext + tag (16 bytes)
|
|
236
|
-
return Buffer.concat([nonce, ciphertext, tag]);
|
|
237
|
-
}
|
|
238
|
-
/**
|
|
239
|
-
* Decrypt data using AES-256-GCM
|
|
240
|
-
* @param data Combined nonce + ciphertext + tag
|
|
241
|
-
* @param key Symmetric key (32 bytes)
|
|
242
|
-
* @returns Decrypted data
|
|
243
|
-
*/
|
|
244
|
-
decrypt(data, key) {
|
|
245
|
-
// Extract: nonce (12 bytes) + ciphertext + tag (16 bytes)
|
|
246
|
-
const nonce = data.subarray(0, 12);
|
|
247
|
-
const tag = data.subarray(data.length - 16);
|
|
248
|
-
const ciphertext = data.subarray(12, data.length - 16);
|
|
249
|
-
const decipher = crypto.createDecipheriv('aes-256-gcm', key, nonce);
|
|
250
|
-
decipher.setAuthTag(tag);
|
|
251
|
-
try {
|
|
252
|
-
const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
253
|
-
return decrypted;
|
|
254
|
-
}
|
|
255
|
-
catch (error) {
|
|
256
|
-
throw new CryptoError('Decryption failed: Invalid ciphertext or authentication tag');
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
// MARK: - Key Serialization
|
|
260
|
-
/**
|
|
261
|
-
* Serialize a private key for storage
|
|
262
|
-
* Note: Private key is already base64 from generateKeyPair
|
|
263
|
-
*/
|
|
264
|
-
serializePrivateKey(privateKeyBase64) {
|
|
265
|
-
return privateKeyBase64;
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Deserialize a private key from storage
|
|
269
|
-
* Note: Private key is already base64
|
|
270
|
-
*/
|
|
271
|
-
deserializePrivateKey(base64) {
|
|
272
|
-
return base64;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
exports.CryptoService = CryptoService;
|
|
276
|
-
// Export singleton instance
|
|
277
|
-
exports.cryptoService = CryptoService.getInstance();
|
|
278
|
-
//# sourceMappingURL=crypto-service.js.map
|