-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
288 lines (242 loc) · 8.34 KB
/
main.js
File metadata and controls
288 lines (242 loc) · 8.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
const { app, BrowserWindow, protocol, shell, session, net } = require('electron');
const path = require('path');
let mainWindow;
let authWindow;
const PROTOCOL = 'unifyai';
const AUTH_CALLBACK_PATH = 'auth-callback';
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
webviewTag: true,
contextIsolation: true,
nodeIntegration: false,
preload: path.join(__dirname, 'preload.js')
}
});
mainWindow.loadFile('dist/index.html');
mainWindow.webContents.openDevTools();
// Set up IPC handlers
mainWindow.webContents.ipc.handle('open-auth-window', async (event, service) => {
return openAuthWindow(service);
});
mainWindow.webContents.ipc.handle('check-auth-status', async (event, service) => {
return checkAuthStatus(service);
});
mainWindow.webContents.ipc.handle('switch-service', async (event, service) => {
// Handle service switching logic
console.log('Switching to service:', service);
return { success: true, service };
});
mainWindow.webContents.ipc.handle('share-context', async (event, data) => {
// Handle context sharing logic
console.log('Sharing context:', data);
return { success: true };
});
mainWindow.webContents.ipc.handle('create-project', async (event, project) => {
// Handle project creation logic
console.log('Creating project:', project);
return { success: true, project };
});
mainWindow.webContents.ipc.handle('update-project', async (event, projectId, data) => {
// Handle project update logic
console.log('Updating project:', projectId, data);
return { success: true };
});
}
function handleAuthCallback(url) {
console.log('Auth callback received:', url);
const urlParams = new URL(url);
const params = new URLSearchParams(urlParams.search);
if (authWindow && !authWindow.isDestroyed()) {
authWindow.close();
}
if (mainWindow) {
mainWindow.webContents.send('auth-success', {
url: url,
params: Object.fromEntries(params)
});
}
}
app.setAsDefaultProtocolClient(PROTOCOL);
protocol.registerSchemesAsPrivileged([
{ scheme: PROTOCOL, privileges: { secure: true, standard: true } }
]);
app.on('open-url', (event, url) => {
event.preventDefault();
console.log('Received URL:', url);
if (url.startsWith(`${PROTOCOL}://${AUTH_CALLBACK_PATH}`)) {
handleAuthCallback(url);
}
});
app.whenReady().then(() => {
protocol.handle(PROTOCOL, (request) => {
const url = request.url;
console.log('Protocol handler:', url);
if (url.includes(AUTH_CALLBACK_PATH)) {
handleAuthCallback(url);
}
return new Response('Auth callback received. You can close this window.', {
headers: { 'content-type': 'text/html' }
});
});
createWindow();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// Function to open auth window and monitor for successful login
async function openAuthWindow(service = 'chatgpt') {
authWindow = new BrowserWindow({
width: 500,
height: 700,
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
});
const authUrls = {
chatgpt: 'https://chatgpt.com/auth/login',
claude: 'https://claude.ai/login'
};
const domains = {
chatgpt: '.chatgpt.com',
claude: '.claude.ai'
};
const successUrls = {
chatgpt: ['https://chatgpt.com/', 'https://chatgpt.com/?'],
claude: ['https://claude.ai/chats', 'https://claude.ai/', 'https://claude.ai/chat']
};
const authUrl = authUrls[service];
const domain = domains[service];
const successPatterns = successUrls[service];
authWindow.loadURL(authUrl);
authWindow.webContents.openDevTools(); // Open dev tools to see what's happening
// Add a manual way to close and transfer cookies after 30 seconds
const autoCloseTimer = setTimeout(async () => {
if (authWindow && !authWindow.isDestroyed()) {
console.log(`Auto-closing ${service} auth window after 30 seconds`);
await transferCookiesAndClose();
}
}, 30000);
async function transferCookiesAndClose() {
try {
// Get cookies from the auth window
const cookies = await authWindow.webContents.session.cookies.get({ domain });
console.log(`Found ${cookies.length} cookies for ${service}:`, cookies.map(c => c.name));
if (cookies.length > 0) {
// Get the webview's partition session
const webviewSession = session.fromPartition(`persist:${service}`);
// Transfer cookies to the webview's partition
for (const cookie of cookies) {
await webviewSession.cookies.set({
url: authUrls[service].replace('/auth/login', '').replace('/login', ''),
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
httpOnly: cookie.httpOnly,
expirationDate: cookie.expirationDate
});
}
// Notify renderer that auth is complete
if (mainWindow) {
mainWindow.webContents.send('auth-success', {
success: true,
service: service,
cookieCount: cookies.length
});
}
}
clearTimeout(autoCloseTimer);
authWindow.close();
} catch (error) {
console.error(`Error transferring ${service} cookies:`, error);
clearTimeout(autoCloseTimer);
authWindow.close();
}
}
// Monitor for successful login by checking URL changes
authWindow.webContents.on('did-navigate', async (event, url) => {
console.log(`${service} auth window navigated to:`, url);
// For Claude, also check for intermediate redirect URLs
let isSuccess = false;
if (service === 'claude') {
// Claude might redirect through various URLs, so be more flexible
isSuccess = url.includes('claude.ai') &&
!url.includes('/login') &&
!url.includes('/auth') &&
(url.includes('/chats') || url.includes('/chat') || url === 'https://claude.ai/');
} else {
// For other services, use the exact patterns
isSuccess = successPatterns.some(pattern =>
url === pattern || url.startsWith(pattern)
);
}
if (isSuccess) {
console.log(`${service} login successful!`);
// Wait a moment for cookies to be fully set, then transfer
setTimeout(transferCookiesAndClose, 2000);
}
});
// Add manual close button functionality
authWindow.webContents.on('dom-ready', () => {
// Inject a "Transfer & Close" button for manual testing
authWindow.webContents.executeJavaScript(`
if (!document.getElementById('manual-close-btn')) {
const btn = document.createElement('button');
btn.id = 'manual-close-btn';
btn.innerText = 'Transfer Cookies & Close';
btn.style.position = 'fixed';
btn.style.top = '10px';
btn.style.right = '10px';
btn.style.zIndex = '9999';
btn.style.background = '#10b981';
btn.style.color = 'white';
btn.style.border = 'none';
btn.style.padding = '10px';
btn.style.borderRadius = '4px';
btn.style.cursor = 'pointer';
btn.onclick = () => {
window.postMessage('transfer-cookies', '*');
};
document.body.appendChild(btn);
}
`);
});
// Listen for manual transfer message
authWindow.webContents.on('ipc-message', (event, channel) => {
if (channel === 'transfer-cookies') {
transferCookiesAndClose();
}
});
authWindow.on('closed', () => {
authWindow = null;
});
}
// Check if user is authenticated
async function checkAuthStatus(service = 'chatgpt') {
const domains = {
chatgpt: '.chatgpt.com',
claude: '.claude.ai'
};
const webviewSession = session.fromPartition(`persist:${service}`);
const cookies = await webviewSession.cookies.get({ domain: domains[service] });
const hasAuthCookies = cookies.some(cookie =>
cookie.name.includes('sess') ||
cookie.name.includes('auth') ||
cookie.name.includes('__Secure') ||
cookie.name.includes('token') ||
cookie.name.includes('sessionid')
);
return hasAuthCookies;
}