Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1820 lines (1762 loc) · 114 KB
/
Copy pathmain.js
File metadata and controls
1820 lines (1762 loc) · 114 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Darknode desktop - Electron main process. Runs shell commands (streamed),
// checks installed tools, and proxies local Ollama. Renderer has no Node access
// (contextIsolation) and talks only through the preload bridge.
const { app, BrowserWindow, ipcMain, shell, dialog, safeStorage, screen, session } = require("electron");
const { spawn, execFile } = require("child_process");
const os = require("os");
const path = require("path");
const http = require("http");
const https = require("https");
const net = require("net");
const tls = require("tls");
const dns = require("dns").promises;
const fs = require("fs");
const { fileURLToPath } = require("url");
// AI + enterprise governance (vendored from the Darknode CLI)
const { toAnthropicBody, anthropicDelta, usageOf } = require("./lib/anthropic");
const { resolveOperator } = require("./lib/identity");
const { appendUsage, loadUsage, summarize, renderReport } = require("./lib/usage");
const { buildBundle, verifyBundle, renderBundleMd } = require("./lib/compliance");
const hardeningAudit = require("./lib/hardening-audit");
const toolkit = require("./lib/toolkit");
const { scanPorts } = require("./lib/recon/portscan");
const { fuzzDirs } = require("./lib/recon/fuzz");
const cveLib = require("./lib/cve");
const { safeFetch } = require("./lib/net/guard");
const { ScopeEnforcer } = require("./lib/scope/enforce");
const redactor = require("./lib/secret/redact");
const { createVault, electronBackend } = require("./lib/secret/vault");
const webshell = require("./lib/webshell/origin");
const { createHandler: createWebHandler } = require("./lib/webshell/serve");
const { runGoogleSignIn } = require("./lib/webshell/google-signin");
// DA-008: redact secrets from the main-process log channel. Any value the vault
// holds is registered with the redactor, so even an unusual token is scrubbed
// here. Shape rules catch the rest. Installed before anything logs.
(function installRedactingConsole() {
for (const level of ["log", "info", "warn", "error", "debug"]) {
const orig = console[level] ? console[level].bind(console) : null;
if (!orig) continue;
console[level] = (...args) => orig(...args.map((a) => {
try { return typeof a === "string" ? redactor.redactString(a) : redactor.redact(a); } catch (_) { return a; }
}));
}
})();
// Keep a stray throw/rejection from a PTY, QEMU or streaming socket from taking
// down the whole main process and silently losing all in-flight work. The
// console above redacts, so logging here can't leak a secret.
process.on("uncaughtException", (e) => console.error("[darknode] uncaught exception:", e));
process.on("unhandledRejection", (e) => console.error("[darknode] unhandled rejection:", e));
const RESULTS_DIR = path.join(os.homedir(), "darknode-results");
let nodePty = null;
try { nodePty = require("node-pty"); } catch (e) { console.error("[darknode] node-pty unavailable:", e.message); }
console.log("[darknode] node-pty:", nodePty ? "loaded" : "unavailable");
const isWin = process.platform === "win32";
let win;
const procs = new Map();
const ptys = new Map();
let ptySeq = 0;
let _zoom = 0; // persisted UI zoom level (webContents.setZoomLevel units)
let _quitting = false;
let _forceClose = false; // set once the user has confirmed closing with work in flight
let _agentExec = 0; // in-flight agent:exec tool commands (no shared map, so counted)
// Any in-flight work the user would lose by quitting: a running command, an AI
// stream, or an agent tool command. An open terminal shell (in `ptys`) is expected
// and deliberately does not count. Used to confirm-before-close.
function workInFlight() {
return procs.size > 0 || streamReqs.size > 0 || claudeReqs.size > 0 || apiReqs.size > 0 || daiReqs.size > 0 || _agentExec > 0;
}
// --- window state (QoL): remember size/position/maximized/zoom across launches ---
// A tiny JSON file in userData, written debounced on resize/move and on close.
const winStatePath = () => path.join(govCwd(), "window-state.json");
function loadWinState() {
try { const s = JSON.parse(fs.readFileSync(winStatePath(), "utf8")); return (s && typeof s === "object") ? s : {}; } catch (_) { return {}; }
}
let _saveT = null;
function saveWinState() {
if (!win || win.isDestroyed()) return;
try {
const b = win.getNormalBounds ? win.getNormalBounds() : win.getBounds(); // un-maximized bounds, so restore returns to the real size
fs.mkdirSync(path.dirname(winStatePath()), { recursive: true });
fs.writeFileSync(winStatePath(), JSON.stringify({ width: b.width, height: b.height, x: b.x, y: b.y, maximized: win.isMaximized(), zoom: _zoom }));
} catch (_) {}
}
function saveWinStateSoon() { clearTimeout(_saveT); _saveT = setTimeout(saveWinState, 400); }
// A saved position is only reused if it still lands on a connected display, so a
// window never restores off-screen after a monitor is unplugged.
function onScreen(x, y, w, h) {
try {
const a = screen.getDisplayMatching({ x, y, width: w, height: h }).workArea;
return x + w > a.x + 40 && y + h > a.y + 40 && x < a.x + a.width - 40 && y < a.y + a.height - 40;
} catch (_) { return false; }
}
// ---- Shell selection (D0) ----
// Default: the packaged website (web/, produced by scripts/sync-web.mjs) served on
// the fixed app origin. DARKNODE_CLASSIC=1 keeps the legacy renderer reachable
// until it is retired in D2; a missing web/ bundle also falls back to it.
const WEB_ROOT = path.join(__dirname, "web");
const CLASSIC_FILE = path.join(__dirname, "renderer", "index.html");
const SHELL = (process.env.DARKNODE_CLASSIC === "1" || !fs.existsSync(path.join(WEB_ROOT, "index.html"))) ? "classic" : "web";
if (SHELL === "classic" && process.env.DARKNODE_CLASSIC !== "1") console.warn("[darknode] web/ bundle missing - run `npm run sync-web`; using the classic renderer");
const IPC_CTX = SHELL === "web"
? { mode: "web", appOrigin: webshell.APP_ORIGIN }
: { mode: "classic", classicFileUrl: require("url").pathToFileURL(CLASSIC_FILE).href };
// Capabilities the web shell really exposes (window.darknode.desktop.caps).
const WEB_CAPS = ["auth.google", "openExternal", "titlebar", "offline", "native", "device", "update"];
const WEB_PARTITION = "persist:darknode";
// The native tools window (web shell only) runs the app's own bundled classic
// renderer, never website content, so it keeps the full classic surface.
const CLASSIC_CTX = { mode: "classic", classicFileUrl: require("url").pathToFileURL(CLASSIC_FILE).href };
const ctxFor = (frame) => (SHELL === "web" && frame && webshell.isClassicUrl(frame.url, CLASSIC_CTX.classicFileUrl) ? CLASSIC_CTX : IPC_CTX);
// The web origin must be a privileged, secure, service-worker-capable origin.
// http://localhost already is (potentially trustworthy), so nothing is registered
// for it; the session below intercepts it instead of opening a socket.
// Every IPC handler is wrapped: the caller must be the top-level frame of the
// trusted shell (app origin, or the classic file) and the channel must be one
// that shell may use. A navigated, compromised or embedded frame is refused.
{
const rawHandle = ipcMain.handle.bind(ipcMain);
ipcMain.handle = (channel, fn) => rawHandle(channel, (event, ...args) => {
let frame = null;
try { const f = event.senderFrame; if (f) frame = { url: f.url, isTop: !f.parent }; } catch (_) {}
const ctx = ctxFor(frame);
if (!webshell.isTrustedSender(frame, ctx) || !webshell.channelAllowed(channel, ctx)) {
let from = "(no frame)"; try { from = frame ? new URL(frame.url).origin : from; } catch (_) {}
console.warn("[darknode] refused IPC " + channel + " from " + from);
throw new Error("IPC refused");
}
return fn(event, ...args);
});
}
// Wire the app session: serve web/ for the app origin, pass every other http
// request through untouched, serve the vendored Firebase SDK locally, and deny
// permission prompts the website does not need.
function setupWebSession() {
const ses = session.fromPartition(WEB_PARTITION);
let hosting = {};
try { hosting = JSON.parse(fs.readFileSync(path.join(WEB_ROOT, ".hosting.json"), "utf8")); } catch (e) { console.warn("[darknode] web/.hosting.json unreadable; serving without hosting headers:", e.message); }
// The site imports the Firebase SDK from www.gstatic.com. When sync-web vendored
// that exact version, every reference in served JS/HTML is pointed at the local
// copy, so the console boots offline. All references are rewritten together
// (pages and the SDK's own cross-imports), so there is one SDK instance.
const vendorDir = path.join(WEB_ROOT, "__vendor");
const GSTATIC = "https://www.gstatic.com/firebasejs/";
const vendored = new Set();
try { for (const v of fs.readdirSync(path.join(vendorDir, "www.gstatic.com", "firebasejs"))) vendored.add(v); } catch (_) {}
const GSTATIC_RE = /https:\/\/www\.gstatic\.com\/firebasejs\/(\d+\.\d+\.\d+)\//g;
const serveWeb = createWebHandler({
root: WEB_ROOT, hosting,
transform: (p, buf) => {
if (!vendored.size || !/\.(m?js|html)$/.test(p)) return null;
const text = buf.toString("utf8");
if (!text.includes(GSTATIC)) return null;
return Buffer.from(text.replace(GSTATIC_RE, (m, ver) => (vendored.has(ver) ? "/__vendor/www.gstatic.com/firebasejs/" + ver + "/" : m)), "utf8");
},
});
ses.protocol.handle("http", (req) => {
let host = ""; try { host = new URL(req.url).host; } catch (_) {}
if (host === webshell.APP_HOST) return serveWeb(req);
return ses.fetch(req, { bypassCustomProtocolHandlers: true });
});
const ALLOWED_PERMS = new Set(["clipboard-read", "clipboard-sanitized-write", "fullscreen"]);
ses.setPermissionRequestHandler((wc, permission, cb, details) => {
cb(ALLOWED_PERMS.has(permission) && webshell.isAppUrl((details && details.requestingUrl) || wc.getURL()));
});
return ses;
}
// The window that hosts the native (classic) UI: the main window in classic mode,
// the native tools window in web mode. Streamed output (terminals, scans, AI tokens)
// goes there.
let nativeWin = null;
const uiWin = () => (SHELL === "web" ? nativeWin : win);
function toUi(channel, payload) {
const w = uiWin();
if (w && !w.isDestroyed()) { try { w.webContents.send(channel, payload); } catch (_) {} }
}
const NATIVE_SECTIONS = new Set(["runner", "scanner", "fuzzer", "recon", "vms", "lab", "forensics", "loot", "tools", "payloads", "exploits", "http", "engagement", "playbooks", "wordlists", "cloud", "github", "agent", "home"]);
function reapNativeWork() {
for (const p of procs.values()) { try { p.kill(); } catch (_) {} } procs.clear();
for (const p of ptys.values()) { try { p.kill(); } catch (_) {} } ptys.clear();
}
// Web shell: open (or focus) the native tools window, optionally on one section.
function openNativeWindow(sec, type) {
if (nativeWin && !nativeWin.isDestroyed()) {
// Still loading from an earlier open: the page has no listener yet, so send it after load.
if (sec) { const go = () => toUi("native:go", { sec, type }); if (nativeWin.webContents.isLoading()) nativeWin.webContents.once("did-finish-load", () => setTimeout(go, 400)); else go(); }
if (nativeWin.isMinimized()) nativeWin.restore();
nativeWin.focus();
return;
}
let force = false;
nativeWin = new BrowserWindow({
width: 1240, height: 820, minWidth: 900, minHeight: 600,
backgroundColor: "#06080f", show: false, frame: false, title: "Darknode native tools",
icon: path.join(__dirname, "renderer", "icon.png"),
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true, nodeIntegration: false, sandbox: true, webviewTag: true,
additionalArguments: ["--no-boot-anim"],
},
});
const nw = nativeWin;
nw.setMenuBarVisibility(false);
nw.once("ready-to-show", () => nw.show());
const rendererDir = path.join(__dirname, "renderer");
nw.webContents.on("will-navigate", (e, url) => {
let ok = false;
try { const p = fileURLToPath(url); ok = p === path.join(rendererDir, "index.html") || p.startsWith(rendererDir + path.sep); } catch (_) {}
if (!ok) e.preventDefault();
});
nw.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
// Same confirm-before-close as the classic app while its work is in flight.
nw.on("close", (e) => {
if (force || _forceClose || !workInFlight()) return;
e.preventDefault();
toUi("app:confirm-close");
});
nw.on("maximize", () => toUi("win:state", true));
nw.on("unmaximize", () => toUi("win:state", false));
nw.webContents.on("render-process-gone", reapNativeWork);
nw.on("closed", () => { if (nativeWin === nw) nativeWin = null; reapNativeWork(); });
nw._dnForceClose = () => { force = true; nw.close(); };
// A command to type (not run) goes over once the page is up; the hash alone opens the section.
if (type) nw.webContents.once("did-finish-load", () => setTimeout(() => toUi("native:go", { sec, type }), 400));
nw.loadFile(CLASSIC_FILE, sec && !type ? { hash: "sec=" + sec } : undefined);
}
function windowFrameOptions() {
if (SHELL === "classic") return { frame: false };
// Native window controls; the website draws its own top bar beneath them and
// marks it as the drag region (html[data-desktop] in the web CSS).
if (process.platform === "darwin") return { titleBarStyle: "hiddenInset" };
return { titleBarStyle: "hidden", titleBarOverlay: { color: "#ffffff", symbolColor: "#1f2937", height: 48 } };
}
function createWindow() {
const st = loadWinState();
_zoom = Number.isFinite(st.zoom) ? st.zoom : 0;
const webPreferences = {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
sandbox: true, // OS-level sandbox for the renderer/preload (defense in depth)
webSecurity: true,
webviewTag: SHELL === "classic", // the classic Browser section (<webview>) only
};
if (SHELL === "web") {
webPreferences.session = setupWebSession();
webPreferences.additionalArguments = ["--dn-shell=web", "--dn-app-origin=" + webshell.APP_ORIGIN, "--dn-app-version=" + app.getVersion(), "--dn-caps=" + WEB_CAPS.join(",")];
}
const opts = Object.assign({
width: 1300, height: 840, minWidth: 900, minHeight: 600,
backgroundColor: SHELL === "web" ? "#ffffff" : "#06080f",
show: false, // show on ready-to-show once painted, so there is no blank/flash on launch
icon: path.join(__dirname, "renderer", "icon.png"),
title: "Darknode",
webPreferences,
}, windowFrameOptions());
if (Number.isFinite(st.width) && st.width >= opts.minWidth) opts.width = Math.round(st.width);
if (Number.isFinite(st.height) && st.height >= opts.minHeight) opts.height = Math.round(st.height);
if (Number.isFinite(st.x) && Number.isFinite(st.y) && onScreen(st.x, st.y, opts.width, opts.height)) { opts.x = Math.round(st.x); opts.y = Math.round(st.y); }
win = new BrowserWindow(opts);
win.setMenuBarVisibility(false);
win.once("ready-to-show", () => { if (st.maximized) win.maximize(); win.show(); });
win.on("resize", saveWinStateSoon);
win.on("move", saveWinStateSoon);
win.on("close", saveWinState);
// Confirm before closing while a command / AI stream / agent run is in flight, so
// a stray click on X does not silently kill in-progress work. The renderer shows
// the confirm (no native dialog); on "close anyway" it calls win:close-now.
win.on("close", (e) => {
if (SHELL === "web") {
if (!_forceClose && nativeWin && !nativeWin.isDestroyed()) {
e.preventDefault();
// Finish what the user asked for once the tools window is gone (it used to take a
// second click, and Cmd+Q was dropped). With work in flight the tools window asks first.
if (!workInFlight()) { const quitting = _quitting; nativeWin.once("closed", () => { if (quitting) app.quit(); else if (win && !win.isDestroyed()) win.close(); }); }
nativeWin.focus(); nativeWin.close();
}
return;
}
if (_forceClose || !workInFlight()) return;
e.preventDefault();
try { win.webContents.send("app:confirm-close"); } catch (_) {}
});
// Standard zoom chords (Ctrl/Cmd +/-/0), handled here because the menu bar is
// hidden so the default zoom roles never register. Persisted with window state.
win.webContents.on("before-input-event", (e, input) => {
if (input.type !== "keyDown" || !(input.control || input.meta)) return;
const k = input.key, code = input.code;
if (k === "=" || k === "+" || code === "NumpadAdd") { _zoom = Math.min(_zoom + 0.5, 5); win.webContents.setZoomLevel(_zoom); e.preventDefault(); saveWinStateSoon(); }
else if (k === "-" || k === "_" || code === "NumpadSubtract") { _zoom = Math.max(_zoom - 0.5, -3); win.webContents.setZoomLevel(_zoom); e.preventDefault(); saveWinStateSoon(); }
else if (k === "0" || code === "Numpad0") { _zoom = 0; win.webContents.setZoomLevel(0); e.preventDefault(); saveWinStateSoon(); }
});
win.webContents.on("did-finish-load", () => { try { win.webContents.setZoomLevel(_zoom); } catch (_) {} });
// If the renderer process dies (crash/OOM), the shells, streamed runs and MCP stdio
// servers it owned are orphaned — and MCP would keep trying to reconnect to a dead
// renderer every few seconds. Reap them so nothing leaks; VMs are left running (main
// still holds their handles and a reloaded renderer can re-list them).
win.webContents.on("render-process-gone", () => {
if (SHELL === "web") return; // native work belongs to the native tools window
for (const p of procs.values()) { try { p.kill(); } catch (_) {} } procs.clear();
for (const p of ptys.values()) { try { p.kill(); } catch (_) {} } ptys.clear();
for (const s of mcpServers.values()) { s.closedByUser = true; if (s.reconnectTimer) { try { clearTimeout(s.reconnectTimer); } catch (_) {} s.reconnectTimer = null; } try { if (s.proc) s.proc.kill("SIGKILL"); } catch (_) {} }
mcpServers.clear(); mcpRetry.clear();
});
win.on("maximize", () => { win.webContents.send("win:state", true); saveWinStateSoon(); });
win.on("unmaximize", () => { win.webContents.send("win:state", false); saveWinStateSoon(); });
if (process.env.DARKNODE_DEBUG) win.webContents.on("console-message", (e, lvl, msg) => console.log("[renderer]", msg !== undefined ? msg : (e && e.message) || ""));
if (process.env.DARKNODE_SHOT) win.webContents.on("did-finish-load", () => setTimeout(async () => { try { const img = await win.webContents.capturePage(); fs.writeFileSync(process.env.DARKNODE_SHOT, img.toPNG()); console.log("SHOT_SAVED"); } catch (e) { console.log("SHOT_ERR " + e.message); } }, Number(process.env.DARKNODE_SHOT_DELAY) || 3500));
if (SHELL === "web") {
// Security: the main frame stays on the app origin; real web links open in the
// OS browser; every other scheme is dropped.
const guardNav = (e, url) => {
const kind = webshell.classifyNavigation(url);
if (kind === "allow") return;
e.preventDefault();
if (kind === "external") shell.openExternal(url);
};
win.webContents.on("will-navigate", guardNav);
win.webContents.on("will-redirect", (e, url, _inPlace, isMainFrame) => { if (isMainFrame) guardNav(e, url); });
// window.open: only the Firebase auth handler may open in-app, as a sandboxed
// popup that can only move between the auth/provider hosts.
win.webContents.setWindowOpenHandler(({ url }) => {
const kind = webshell.classifyWindowOpen(url);
if (kind === "auth-popup") {
return { action: "allow", overrideBrowserWindowOptions: { width: 520, height: 680, parent: win, autoHideMenuBar: true, titleBarStyle: "default", titleBarOverlay: false, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } } };
}
if (kind === "blank") {
return { action: "allow", overrideBrowserWindowOptions: { width: 900, height: 1000, autoHideMenuBar: true, backgroundColor: "#ffffff", titleBarStyle: "default", titleBarOverlay: false, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } } };
}
if (kind === "external") shell.openExternal(url);
return { action: "deny" };
});
win.webContents.on("did-create-window", (child, details) => {
// Auth popups may move between the provider hosts; a blank report window never
// navigates (its links go to the OS browser). Neither gets the bridge (preload).
const blank = webshell.classifyWindowOpen(details && details.url) === "blank";
const guardPopup = (e, url) => {
if (blank) { e.preventDefault(); if (webshell.classifyNavigation(url) === "external") shell.openExternal(url); return; }
if (!webshell.authPopupNavAllowed(url)) { e.preventDefault(); }
};
child.webContents.on("will-navigate", guardPopup);
child.webContents.on("will-redirect", guardPopup);
child.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
});
// The site asks before unloading when a tool has typed input (beforeunload).
// Electron would silently cancel the navigation (e.g. sign-out); show the same
// leave-or-stay choice a browser shows instead.
win.webContents.on("will-prevent-unload", (e) => {
const choice = dialog.showMessageBoxSync(win, { type: "question", buttons: ["Leave", "Stay"], defaultId: 1, cancelId: 1, title: "Darknode", message: "Leave this page?", detail: "Changes you made may not be saved." });
if (choice === 0) e.preventDefault();
});
win.loadURL(webshell.APP_ORIGIN + "/");
return;
}
// Security: keep the main renderer pinned to the app's own bundled files.
// Any non-file URL, or a file:// path outside renderer/, is blocked — so a
// stray link can't escape the shell into file:///etc/passwd etc.
const rendererDir = path.join(__dirname, "renderer");
win.webContents.on("will-navigate", (e, url) => {
let ok = false;
try { const p = fileURLToPath(url); ok = p === path.join(rendererDir, "index.html") || p.startsWith(rendererDir + path.sep); } catch (_) {}
if (!ok) e.preventDefault();
});
// Security: block new-window requests from the renderer (links should use openExternal).
win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
win.loadFile(CLASSIC_FILE);
}
// Constrain any web content (esp. the <webview> Browser tab): open real links in the
// OS browser, deny every other window.open, and never let a guest webview gain Node.
app.on("web-contents-created", (_e, contents) => {
contents.setWindowOpenHandler(({ url }) => {
try { const p = new URL(url).protocol; if (p === "http:" || p === "https:") shell.openExternal(url); } catch (_) {}
return { action: "deny" };
});
contents.on("will-attach-webview", (_evt, wp) => { delete wp.preload; wp.nodeIntegration = false; wp.contextIsolation = true; wp.sandbox = true; });
});
// One instance: a second launch focuses the first (two processes must not share
// the persistent web partition).
if (!app.requestSingleInstanceLock()) app.quit();
else app.on("second-instance", () => { if (win) { if (win.isMinimized()) win.restore(); win.focus(); } });
app.whenReady().then(createWindow);
app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); });
app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
ipcMain.handle("sysinfo", () => ({
platform: process.platform, arch: process.arch, hostname: os.hostname(),
release: os.release(), cpus: os.cpus().length,
mem: Math.round(os.totalmem() / 1e9) + " GB", home: os.homedir(),
electron: process.versions.electron, node: process.versions.node, version: app.getVersion(),
}));
// Check GitHub Releases for a newer version (renderer CSP blocks external fetch, so do it here).
// One GitHub lookup an hour at most (unauthenticated API: 60 requests/hour per IP).
let _updCache = null, _updAt = 0, _updP = null;
ipcMain.handle("app:checkUpdate", async () => {
if (_updCache && Date.now() - _updAt < 3600000) return _updCache;
if (!_updP) _updP = checkUpdateNow().then((r) => { if (r.ok) { _updCache = r; _updAt = Date.now(); } return r; }).finally(() => { _updP = null; });
return _updP;
});
async function checkUpdateNow() {
const cmp = (a, b) => { const x = a.split(".").map(Number), y = b.split(".").map(Number); for (let i = 0; i < 3; i++) { if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0); } return 0; };
try {
const cur = app.getVersion();
const ctrl = new AbortController(); const to = setTimeout(() => ctrl.abort(), 15000);
let r; try { r = await fetch("https://api.github.com/repos/Darknode-Official/darknode-app/releases/latest", { headers: { "User-Agent": "Darknode" }, signal: ctrl.signal }); } finally { clearTimeout(to); }
if (!r.ok) return { ok: false };
const d = await r.json();
const vers = (d.assets || []).map((a) => (a.name.match(/(\d+\.\d+\.\d+)/) || [])[1]).filter(Boolean);
// Also take the release tag itself (e.g. v1.2.3) so a release whose assets
// aren't version-named — or aren't uploaded yet — still reports correctly.
const tag = (String(d.tag_name || "").match(/(\d+\.\d+\.\d+)/) || [])[1];
if (tag) vers.push(tag);
vers.sort(cmp);
const latest = vers.length ? vers[vers.length - 1] : cur;
return { ok: true, current: cur, latest, update: cmp(latest, cur) > 0, url: "https://github.com/Darknode-Official/darknode-app/releases/latest" };
} catch (e) { return { ok: false, error: e.message }; }
}
// ---- Native Gmail OAuth (Desktop client: loopback + PKCE) ----
// A Desktop OAuth client can't keep its secret confidential (it ships in the app),
// which is expected for installed apps; loopback + PKCE is the flow Google prescribes.
// The id/secret are NOT hardcoded here -- they load from env or oauth.config.json
// (gitignored), so no credentials live in source. See oauth.config.example.json.
function loadOAuthConfig() {
try { const p = path.join(__dirname, "oauth.config.json"); if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, "utf8")); } catch (_) {}
return {};
}
const _oauthCfg = loadOAuthConfig();
const GMAIL_OAUTH = {
clientId: process.env.DARKNODE_GMAIL_CLIENT_ID || _oauthCfg.gmailClientId || "",
clientSecret: process.env.DARKNODE_GMAIL_CLIENT_SECRET || _oauthCfg.gmailClientSecret || "",
scopes: ["https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.compose"],
};
const b64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
// Block loopback / link-local (incl. cloud metadata 169.254.169.254) / private
// ranges so net:get can't be turned into an SSRF/exfil channel by tool input.
// SSRF guard lives in lib/net/guard.js (isPrivateHost, resolvesToPrivate,
// validateUrl, safeFetch). safeFetch re-validates EVERY redirect hop so a
// permitted public host cannot 3xx-redirect the fetch to an internal address.
async function gmailExchange(params) {
const r = await fetch("https://oauth2.googleapis.com/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(params).toString() });
return r.json();
}
ipcMain.handle("gmail:oauth", async (_e, creds) => {
const crypto = require("crypto");
const clientId = (creds && creds.clientId) || GMAIL_OAUTH.clientId;
const clientSecret = (creds && creds.clientSecret) || GMAIL_OAUTH.clientSecret;
return await new Promise((resolve) => {
const verifier = b64url(crypto.randomBytes(32));
const challenge = b64url(crypto.createHash("sha256").update(verifier).digest());
const state = b64url(crypto.randomBytes(16));
let redirect = "", done = false;
const finish = (v) => { if (done) return; done = true; try { server.close(); } catch (_) {} resolve(v); };
const server = http.createServer(async (req, res) => {
try {
const u = new URL(req.url, redirect || "http://127.0.0.1");
const code = u.searchParams.get("code"), err = u.searchParams.get("error");
if (!code && !err) { res.writeHead(404); res.end(); return; }
// CSRF defense-in-depth: reject callbacks whose state doesn't match ours.
if (code && u.searchParams.get("state") !== state) { res.writeHead(400); res.end("bad state"); return; }
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<!doctype html><meta charset=utf-8><body style='font-family:system-ui;background:#0b0e14;color:#e6edf3;text-align:center;padding-top:90px'><h2>" + (code ? "Gmail connected ✓" : "Gmail connection failed") + "</h2><p>You can close this tab and return to Darknode.</p>");
if (err || !code) return finish({ ok: false, error: err || "no authorization code" });
const d = await gmailExchange({ client_id: clientId, client_secret: clientSecret, code, code_verifier: verifier, grant_type: "authorization_code", redirect_uri: redirect });
if (d.access_token) finish({ ok: true, access_token: d.access_token, refresh_token: d.refresh_token || "", expires_in: d.expires_in || 3600 });
else finish({ ok: false, error: d.error_description || d.error || "token exchange failed" });
} catch (e) { finish({ ok: false, error: e.message }); }
});
server.on("error", (e) => finish({ ok: false, error: e.message }));
server.listen(0, "127.0.0.1", () => {
redirect = "http://127.0.0.1:" + server.address().port;
const auth = "https://accounts.google.com/o/oauth2/v2/auth?" + new URLSearchParams({ client_id: clientId, redirect_uri: redirect, response_type: "code", scope: GMAIL_OAUTH.scopes.join(" "), access_type: "offline", prompt: "consent", state, code_challenge: challenge, code_challenge_method: "S256" }).toString();
shell.openExternal(auth);
});
setTimeout(() => finish({ ok: false, error: "timed out waiting for Google sign-in" }), 300000);
});
});
ipcMain.handle("gmail:refresh", async (_e, arg) => {
const refreshToken = typeof arg === "string" ? arg : (arg && arg.refreshToken);
if (!refreshToken) return { ok: false, error: "no refresh token" };
const clientId = (arg && arg.clientId) || GMAIL_OAUTH.clientId;
const clientSecret = (arg && arg.clientSecret) || GMAIL_OAUTH.clientSecret;
try {
const d = await gmailExchange({ client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: "refresh_token" });
if (d.access_token) return { ok: true, access_token: d.access_token, expires_in: d.expires_in || 3600 };
return { ok: false, error: d.error_description || d.error || "refresh failed" };
} catch (e) { return { ok: false, error: e.message }; }
});
// Generic HTTP GET/POST proxy for the renderer — runs in the main process, so
// third-party security/OSINT APIs that don't send CORS headers still work.
// Returns { ok, status, data } (data is parsed JSON when the response is JSON).
ipcMain.handle("net:get", async (_e, opts) => {
const { url, headers, method, body } = opts || {};
try {
if (!/^https?:\/\//i.test(String(url || ""))) return { ok: false, status: 0, error: "bad url" };
const ctrl = new AbortController();
const to = setTimeout(() => ctrl.abort(), 20000);
try {
// safeFetch validates the initial host AND every redirect hop (SSRF-safe).
const r = await safeFetch(url, { method: method || "GET", headers: Object.assign({ "User-Agent": "Darknode/1.0" }, headers || {}), body: body || undefined, signal: ctrl.signal });
const ct = r.headers.get("content-type") || "";
// Cap the response body (like http:request does) so a huge/hostile reply
// can't OOM the main process; parse JSON from the capped text ourselves.
const text = await readTextCapped(r, 1_000_000);
const data = ct.includes("json") ? (() => { try { return JSON.parse(text); } catch (_) { return null; } })() : text;
return { ok: r.ok, status: r.status, data };
} finally { clearTimeout(to); }
} catch (e) { return { ok: false, status: 0, error: e.name === "AbortError" ? "timed out" : e.message }; }
});
// Stream a shell command's output to the renderer.
ipcMain.handle("run", (_e, { id, cmd, cwd }) => {
const p = isWin ? spawn("cmd.exe", ["/c", cmd], { cwd: cwd || os.homedir() })
: spawn("/bin/sh", ["-c", cmd], { cwd: cwd || os.homedir() });
procs.set(id, p);
const send = (chunk) => toUi("run:data", { id, chunk });
p.stdout.setEncoding("utf8"); p.stderr.setEncoding("utf8"); // decode across pipe-chunk boundaries so multibyte UTF-8 isn't split into U+FFFD
p.stdout.on("data", send);
p.stderr.on("data", send);
p.on("close", (code) => { procs.delete(id); toUi("run:end", { id, code }); });
p.on("error", (err) => { send("[error] " + err.message + "\n"); procs.delete(id); toUi("run:end", { id, code: -1 }); });
return true;
});
ipcMain.handle("kill", (_e, id) => { const p = procs.get(id); if (p) { try { p.kill(); } catch (_) {} } return true; });
// ---- Agent: blocking command runner. Captures output + exit code (for the AI agent loop). ----
// Runs an agent command in a PTY so INTERACTIVE tools work fully autonomously:
// ssh, sudo, su, mysql -p, etc. all get a real terminal. We auto-answer the two prompts
// that otherwise block an unattended agent — the SSH host-key question ("yes") and
// password prompts (typed from the operator-configured `autopass`). Password input is not
// echoed by the tty, so it never lands in the captured output. Falls back to a plain pipe
// if node-pty is unavailable.
ipcMain.handle("agent:exec", (_e, { command, cwd, timeout, autopass }) => new Promise((res) => {
_agentExec++;
const workdir = cwd || os.homedir();
const cap = 50000;
let out = "", killed = false, settled = false, answers = 0, to;
const finish = (v) => { if (settled) return; settled = true; _agentExec = Math.max(0, _agentExec - 1); clearTimeout(to); res(v); };
// Strip ANSI/OSC escapes + stray control chars so the model sees clean text.
const clean = (s) => s
.replace(/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g, "")
.replace(/\x1B[\[\]][0-9;?=]*[ -\/]*[@-~]/g, "")
.replace(/\x1B[()][0-9A-Za-z]/g, "")
.replace(/\x1B[=>NM]/g, "")
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "")
.replace(/\r\n?/g, "\n");
if (!isWin && nodePty) {
let p;
try { p = nodePty.spawn("/bin/sh", ["-c", command], { name: "xterm-256color", cols: 120, rows: 40, cwd: workdir, env: process.env }); }
catch (err) { return finish({ ok: false, error: err.message }); }
p.onData((d) => {
if (out.length < cap + 8000) out += d;
const tail = out.slice(-240);
if (answers < 10) {
if (/(?:\(yes\/no(?:\/\[fingerprint\])?\)\??|continue connecting\??)\s*$/i.test(tail)) { answers++; try { p.write("yes\r"); } catch (_) {} }
else if (autopass && /(?:[Pp]assword|[Pp]assphrase)(?:\s+for\s+\S+)?:\s*$/.test(tail)) { answers++; try { p.write(autopass + "\r"); } catch (_) {} }
}
});
// Shape the captured output once; used by both normal exit and the timeout fallback.
const done = (code) => { let c = clean(out).trim(); if (autopass) c = c.split(autopass).join("***"); c = redactor.redactString(c); finish({ ok: true, code, killed, output: c.length > cap ? c.slice(0, cap) + "\n...[truncated]" : (c || "(no output)") }); };
p.onExit(({ exitCode }) => done(exitCode));
to = setTimeout(() => {
killed = true;
try { p.kill(); } catch (_) {} // polite first (node-pty default is SIGHUP)
setTimeout(() => { try { p.kill("SIGKILL"); } catch (_) {} }, 2000); // escalate if the child ignores SIGHUP
setTimeout(() => done(null), 3500); // guarantee the promise resolves even if onExit never fires
}, timeout || 60000);
return;
}
let p;
try { p = isWin ? spawn("cmd.exe", ["/c", command], { cwd: workdir }) : spawn("/bin/sh", ["-c", command], { cwd: workdir }); }
catch (err) { return finish({ ok: false, error: err.message }); }
p.stdout.setEncoding("utf8"); p.stderr.setEncoding("utf8"); // decode across chunk boundaries before the model sees it
const add = (d) => { if (out.length < cap + 200) out += d; };
p.stdout.on("data", add); p.stderr.on("data", add);
p.on("close", (code) => { let c = out; if (autopass) c = c.split(autopass).join("***"); c = redactor.redactString(c); finish({ ok: true, code, killed, output: c.length > cap ? c.slice(0, cap) + "\n...[truncated]" : (c || "(no output)") }); });
p.on("error", (err) => finish({ ok: false, error: err.message }));
to = setTimeout(() => { killed = true; try { p.kill("SIGKILL"); } catch (_) {} }, timeout || 60000);
}));
// ---- Auto-configure a tool: install on first use, streaming progress. ----
// Privileged installs go through pkexec (graphical prompt); no password stored.
ipcMain.handle("tool:install", (_e, { id, install }) => new Promise((res) => {
let cmd = String(install || "").trim();
if (cmd.startsWith("sudo ")) cmd = "pkexec " + cmd.slice(5).replace(/^apt install/, "apt-get install");
const p = spawn("/bin/bash", ["-lc", cmd]);
p.stdout.setEncoding("utf8"); p.stderr.setEncoding("utf8"); // decode across chunk boundaries (multibyte-safe)
const send = (c) => toUi("tool:install:data", { id, chunk: c });
p.stdout.on("data", send); p.stderr.on("data", send);
p.on("close", (code) => res({ ok: code === 0, code, cmd }));
p.on("error", (e) => { send("[error] " + e.message + "\n"); res({ ok: false, error: e.message, cmd }); });
}));
// ---- interactive PTYs (real terminals, one per tab) ----
ipcMain.handle("pty:spawn", (_e, { cols, rows }) => {
if (!nodePty) return { ok: false, error: "node-pty is not available in this build" };
const id = "p" + (++ptySeq);
const shell = isWin ? "powershell.exe" : (process.env.SHELL || "/bin/bash");
let p;
try { p = nodePty.spawn(shell, [], { name: "xterm-color", cols: cols || 80, rows: rows || 24, cwd: os.homedir(), env: process.env }); }
catch (e) { return { ok: false, error: e.message }; }
ptys.set(id, p);
p.onData((d) => toUi("pty:data", { id, data: d }));
p.onExit(() => { ptys.delete(id); toUi("pty:exit", { id }); });
return { ok: true, id, shell };
});
ipcMain.handle("pty:write", (_e, { id, data }) => { const p = ptys.get(id); if (p) { try { p.write(data); } catch (_) {} } }); // keystrokes can race pty exit
ipcMain.handle("pty:resize", (_e, { id, cols, rows }) => { const p = ptys.get(id); if (p) { try { p.resize(cols, rows); } catch (_) {} } });
ipcMain.handle("pty:kill", (_e, { id }) => { const p = ptys.get(id); if (p) { try { p.kill(); } catch (_) {} ptys.delete(id); } });
// Is a tool on PATH? Sanitize name to prevent shell injection.
ipcMain.handle("which", (_e, name) => new Promise((res) => {
name = String(name || "").replace(/[^a-zA-Z0-9_.+-]/g, "");
if (!name) return res({ found: false });
const cmd = isWin ? "where " + name : "command -v " + name;
const p = isWin ? spawn("cmd.exe", ["/c", cmd]) : spawn("/bin/sh", ["-c", cmd]);
let out = "";
p.stdout.on("data", (d) => (out += d));
p.on("close", (c) => res({ found: c === 0, path: out.trim() }));
p.on("error", () => res({ found: false }));
}));
// Proxy local Ollama (avoids renderer file:// CORS).
ipcMain.handle("ollama", (_e, { path: pth, body }) => new Promise((res) => {
const data = body ? JSON.stringify(body) : null;
const req = http.request(
{ host: "127.0.0.1", port: 11434, path: pth, method: data ? "POST" : "GET",
headers: data ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } : {} },
(r) => { let b = ""; r.on("data", (d) => (b += d)); r.on("end", () => { try { res({ ok: true, data: JSON.parse(b) }); } catch (_) { res({ ok: true, data: b }); } }); }
);
req.on("error", (err) => res({ ok: false, error: err.message }));
if (data) req.write(data);
req.end();
}));
// Streaming Ollama chat: emits ollama:token events live, resolves with the full
// assembled message (content + tool_calls) when the stream ends.
const streamReqs = new Map();
ipcMain.handle("ollama:stream", (_e, { id, body }) => new Promise((resolve) => {
// keep_alive: keep the model resident for 30m so agentic multi-step turns don't
// pay a cold ~8s reload each step (the main cause of the "glitchy/hung" feel).
// Caller can still override by setting keep_alive on the body.
const data = JSON.stringify(Object.assign({ keep_alive: "30m" }, body, { stream: true }));
let content = "", toolCalls = null, settled = false;
const done = (v) => { if (settled) return; settled = true; streamReqs.delete(id); resolve(v); };
const req = http.request(
{ host: "127.0.0.1", port: 11434, path: "/api/chat", method: "POST",
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } },
(r) => {
r.setEncoding("utf8"); // decode on the stream so a multibyte char split across chunks is never mangled
let buf = "";
const pump = (d) => {
buf += d; let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1); if (!line) continue;
let j; try { j = JSON.parse(line); } catch (_) { continue; }
if (j.error) { done({ ok: false, error: j.error }); return; }
const m = j.message || {};
if (m.content) { content += m.content; toUi("ollama:token", { id, chunk: m.content }); }
if (m.tool_calls && m.tool_calls.length) toolCalls = (toolCalls || []).concat(m.tool_calls);
}
};
r.on("data", pump);
r.on("end", () => { if (buf.trim()) pump("\n"); done({ ok: true, message: { role: "assistant", content, tool_calls: toolCalls || undefined } }); });
r.on("error", (err) => done({ ok: false, error: err.message }));
}
);
req.on("error", (err) => done({ ok: false, error: err.message }));
streamReqs.set(id, req);
req.write(data); req.end();
}));
ipcMain.handle("ollama:cancel", (_e, id) => { const rq = streamReqs.get(id); if (rq) { try { rq.destroy(); } catch (_) {} streamReqs.delete(id); } return true; });
// ---- Claude (Anthropic) streaming — the cloud engine for the Assistant ----
// Mirrors ollama:stream's contract: streams claude:token events and resolves with
// { ok, message:{content}, usage:{inTok,outTok} }. Key comes from the request
// (Assistant settings) or the ANTHROPIC_API_KEY env var. For authorized security work.
const claudeReqs = new Map();
ipcMain.handle("claude:stream", (_e, { id, body, apiKey }) => new Promise((resolve) => {
const key = apiKey || process.env.ANTHROPIC_API_KEY || "";
if (!key) { resolve({ ok: false, error: "no Anthropic API key — add one in the Assistant settings (gear) or set ANTHROPIC_API_KEY" }); return; }
const data = JSON.stringify(Object.assign({}, toAnthropicBody(body), { stream: true }));
let content = "", inTok = 0, outTok = 0, settled = false;
const done = (v) => { if (settled) return; settled = true; claudeReqs.delete(id); resolve(v); };
const req = https.request(
{ host: "api.anthropic.com", path: "/v1/messages", method: "POST",
headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data), "x-api-key": key, "anthropic-version": "2023-06-01" } },
(r) => {
if (r.statusCode >= 400) { let e = ""; r.on("data", (d) => (e += d)); r.on("end", () => { let msg = e; try { const j = JSON.parse(e); msg = (j.error && j.error.message) || e; } catch (_) {} done({ ok: false, error: "Anthropic " + r.statusCode + ": " + msg }); }); return; }
r.setEncoding("utf8"); // decode on the stream so a multibyte char split across chunks is never mangled
let buf = "";
const pump = (d) => {
buf += d; let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const p = line.slice(5).trim(); if (!p || p === "[DONE]") continue;
let o; try { o = JSON.parse(p); } catch (_) { continue; }
if (o.type === "error") { done({ ok: false, error: (o.error && o.error.message) || "stream error" }); return; }
const txt = anthropicDelta(o); if (txt) { content += txt; toUi("claude:token", { id, chunk: txt }); }
const u = usageOf(o); if (u) { if (u.inTok) inTok = u.inTok; if (u.outTok) outTok = u.outTok; }
}
};
r.on("data", pump);
r.on("end", () => { if (buf.trim()) pump("\n"); done({ ok: true, message: { role: "assistant", content }, usage: { inTok, outTok } }); });
r.on("error", (err) => done({ ok: false, error: err.message }));
}
);
req.on("error", (err) => done({ ok: false, error: err.message }));
claudeReqs.set(id, req);
req.write(data); req.end();
}));
ipcMain.handle("claude:cancel", (_e, id) => { const rq = claudeReqs.get(id); if (rq) { try { rq.destroy(); } catch (_) {} claudeReqs.delete(id); } return true; });
// ---- Any model (OpenAI-compatible) streaming — OpenRouter, Groq, DeepSeek, Together,
// Mistral, LM Studio, vLLM, llama.cpp, … Mirrors ollama:stream's contract: emits
// api:token events, resolves with { ok, message:{content,tool_calls}, usage }. base +
// apiKey + model come from the Assistant settings. Tool-call args are parsed to objects
// so the planner sees the SAME shape Ollama returns.
const apiReqs = new Map();
function mergeToolCallDeltas(acc, deltas) {
acc = acc || [];
for (const d of deltas) {
const i = typeof d.index === "number" ? d.index : acc.length;
acc[i] = acc[i] || { id: "", type: "function", function: { name: "", arguments: "" } };
if (d.id) acc[i].id = d.id;
if (d.type) acc[i].type = d.type;
if (d.function) { if (d.function.name) acc[i].function.name = d.function.name; if (d.function.arguments) acc[i].function.arguments += d.function.arguments; }
}
return acc;
}
ipcMain.handle("api:stream", (_e, { id, body, base, apiKey, model }) => new Promise((resolve) => {
let url;
try { url = new URL(String(base || "").replace(/\/+$/, "") + "/chat/completions"); }
catch (e) { resolve({ ok: false, error: "invalid API base URL: " + base }); return; }
const lib = url.protocol === "https:" ? https : http;
const payload = Object.assign({}, body, { stream: true }); if (model) payload.model = model;
// translate Ollama-shaped fields to OpenAI schema: temperature lives at top level,
// and format(JSON schema) → response_format so structured output is actually enforced.
if (payload.options && typeof payload.options.temperature === "number") payload.temperature = payload.options.temperature;
if (payload.format) payload.response_format = { type: "json_object" };
delete payload.options; delete payload.format; delete payload.keep_alive; delete payload.num_ctx;
const data = JSON.stringify(payload);
const headers = { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) };
const key = apiKey || process.env.DARKNODE_API_KEY || process.env.OPENAI_API_KEY || "";
if (key) headers["Authorization"] = "Bearer " + key;
let content = "", toolCalls = null, inTok = 0, outTok = 0, settled = false;
const done = (v) => { if (settled) return; settled = true; apiReqs.delete(id); resolve(v); };
const req = lib.request(
{ hostname: url.hostname, port: url.port || (url.protocol === "https:" ? 443 : 80), path: url.pathname + url.search, method: "POST", headers },
(r) => {
if (r.statusCode >= 400) { let e = ""; r.on("data", (d) => (e += d)); r.on("end", () => { let msg = e; try { const j = JSON.parse(e); msg = (j.error && j.error.message) || e; } catch (_) {} done({ ok: false, error: "API " + r.statusCode + ": " + String(msg).slice(0, 300) }); }); return; }
r.setEncoding("utf8"); // decode on the stream so a multibyte char split across chunks is never mangled
let buf = "";
const pump = (d) => {
buf += d; let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const p = line.slice(5).trim(); if (!p || p === "[DONE]") continue;
let o; try { o = JSON.parse(p); } catch (_) { continue; }
if (o.error) { done({ ok: false, error: (o.error && o.error.message) || "stream error" }); return; }
const ch = (o.choices && o.choices[0]) || {}, delta = ch.delta || {};
if (delta.content) { content += delta.content; toUi("api:token", { id, chunk: delta.content }); }
if (delta.tool_calls && delta.tool_calls.length) toolCalls = mergeToolCallDeltas(toolCalls, delta.tool_calls);
if (o.usage) { inTok = o.usage.prompt_tokens || inTok; outTok = o.usage.completion_tokens || outTok; }
}
};
r.on("data", pump);
r.on("end", () => {
if (buf.trim()) pump("\n");
const tc = toolCalls ? toolCalls.filter(Boolean).map((t) => ({ id: t.id, type: t.type, function: { name: t.function.name, arguments: (() => { try { return JSON.parse(t.function.arguments || "{}"); } catch (_) { return t.function.arguments; } })() } })) : null;
done({ ok: true, message: { role: "assistant", content, tool_calls: tc && tc.length ? tc : undefined }, usage: { inTok, outTok } });
});
r.on("error", (err) => done({ ok: false, error: err.message }));
}
);
req.on("error", (err) => done({ ok: false, error: err.message }));
apiReqs.set(id, req);
req.write(data); req.end();
}));
ipcMain.handle("api:cancel", (_e, id) => { const rq = apiReqs.get(id); if (rq) { try { rq.destroy(); } catch (_) {} apiReqs.delete(id); } return true; });
// Darknode AI (cloud): routes the app's default assistant through the darknode.ai
// proxy (Cloudflare worker) so no API key lives on the device. Sends cite:false
// so answers never carry a Sources list. Streams dai:token and resolves with the
// assembled message — same contract as ollama:stream / api:stream.
const daiReqs = new Map();
ipcMain.handle("dai:stream", (_e, { id, messages }) => new Promise((resolve) => {
const data = JSON.stringify({ provider: "darknode", model: "darknode", cite: false, messages: messages || [] });
let content = "", settled = false;
const done = (v) => { if (settled) return; settled = true; daiReqs.delete(id); resolve(v); };
const req = https.request(
{ hostname: "darknode-proxy.darknode-ai.workers.dev", port: 443, path: "/api/chat", method: "POST",
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } },
(r) => {
if (r.statusCode >= 400) { let e = ""; r.on("data", (d) => (e += d)); r.on("end", () => { let msg = e; try { const j = JSON.parse(e); msg = (j && j.error) || e; } catch (_) {} done({ ok: false, error: "Darknode AI " + r.statusCode + ": " + String(msg).slice(0, 300) }); }); return; }
r.setEncoding("utf8"); // decode on the stream so a multibyte char split across chunks is never mangled
let buf = "";
const pump = (d) => {
buf += d; let nl;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim(); buf = buf.slice(nl + 1);
if (!line.startsWith("data:")) continue;
const p = line.slice(5).trim(); if (!p || p === "[DONE]") continue;
let o; try { o = JSON.parse(p); } catch (_) { continue; }
const ch = (o.choices && o.choices[0]) || {}, delta = ch.delta || {};
if (delta.content) { content += delta.content; toUi("dai:token", { id, chunk: delta.content }); }
}
};
r.on("data", pump);
r.on("end", () => { if (buf.trim()) pump("\n"); done({ ok: true, message: { role: "assistant", content } }); });
r.on("error", (err) => done({ ok: false, error: err.message }));
}
);
req.on("error", (err) => done({ ok: false, error: err.message }));
daiReqs.set(id, req);
req.write(data); req.end();
}));
ipcMain.handle("dai:cancel", (_e, id) => { const rq = daiReqs.get(id); if (rq) { try { rq.destroy(); } catch (_) {} daiReqs.delete(id); } return true; });
// ---- enterprise governance: usage ledger + signed compliance bundle ----
const govCwd = () => { try { return app.getPath("userData"); } catch (_) { return os.homedir(); } };
// Scope-authorization enforcer (DA-009). Lazily built so app paths are ready.
// Active capabilities (scan/fuzz/subdomains/tls/http) are gated by scope().enforce().
let _scope = null;
const scope = () => _scope || (_scope = new ScopeEnforcer(govCwd()));
// DA-008: OS-keychain-backed credential vault. Values are encrypted with the
// current OS user's safeStorage key (macOS Keychain / Windows DPAPI / Linux
// libsecret-kwallet) and written as ciphertext to <userData>/.nexus/secrets.enc
// (mode 0600). Every value read/written is registered with the redactor so it
// is scrubbed from logs, transcripts, and the usage ledger.
let _vault = null;
const vault = () => _vault || (_vault = createVault({ cwd: govCwd(), backend: electronBackend(safeStorage, process.platform) }));
ipcMain.handle("secret:set", (_e, { name, value }) => { try { const r = vault().set(name, value); if (r.ok) redactor.registerSecret(value); return r; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("secret:get", (_e, name) => { try { const v = vault().get(name); if (v != null) redactor.registerSecret(v); return { ok: true, value: v }; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("secret:has", (_e, name) => { try { return { ok: true, has: vault().has(name) }; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("secret:list", () => { try { return { ok: true, secrets: vault().list() }; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("secret:remove", (_e, name) => { try { return vault().remove(name); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("secret:mode", () => { try { return vault().mode(); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("scope:authorize", (_e, rec) => { try { return scope().addAuthorization(rec || {}); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("scope:list", () => { try { return { ok: true, records: scope().list() }; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("scope:revoke", (_e, id) => { try { return scope().revoke(id); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("scope:check", (_e, { kind, target }) => { try { return scope().preview(kind, target); } catch (e) { return { allowed: false, reason: String((e && e.message) || e) }; } });
ipcMain.handle("gov:identity", () => { try { return resolveOperator({ cwd: govCwd() }); } catch (_) { return { operator: "unknown", team: "", source: "os" }; } });
ipcMain.handle("gov:usage:append", (_e, rec) => { try { return appendUsage(govCwd(), redactor.redact(rec || {})); } catch (_) { return false; } });
ipcMain.handle("gov:usage:report", (_e, opts) => { try { const recs = loadUsage(govCwd(), (opts && opts.since) ? { since: opts.since } : {}); const s = summarize(recs); return { ok: true, summary: s, text: renderReport(s, { project: "Darknode Assistant" }), count: recs.length }; } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
ipcMain.handle("gov:compliance:build", (_e, opts) => {
try {
opts = opts || {}; const cwd = govCwd(); const id = resolveOperator({ cwd });
const key = opts.signingKey || process.env.DARKNODE_SIGNING_KEY || "";
const b = buildBundle(cwd, { operator: opts.operator || id.operator, team: opts.team || id.team, signingKey: key || undefined });
let outPath = null;
try { const dir = path.join(cwd, ".nexus"); fs.mkdirSync(dir, { recursive: true }); const stamp = new Date().toISOString().replace(/[:.]/g, "-"); outPath = path.join(dir, "compliance-" + stamp + ".json"); fs.writeFileSync(outPath, JSON.stringify(b, null, 2)); fs.writeFileSync(outPath.replace(/\.json$/, ".md"), renderBundleMd(b)); } catch (_) {}
return { ok: true, bundle: b, md: renderBundleMd(b), path: outPath };
} catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
});
ipcMain.handle("gov:compliance:verify", (_e, { bundle, signingKey }) => { try { return Object.assign({ ok: true }, verifyBundle(bundle, signingKey || process.env.DARKNODE_SIGNING_KEY || undefined)); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; } });
// ---- Workstation Security Audit (CIS Level 1-style, read-only) ----
// Runs fixed status/query commands for the local machine and parses their real
// output. execFile (never a shell), a per-command timeout, and NO privilege
// escalation: a command that is missing, not applicable, or needs root reports
// `na`/`error` honestly rather than guessing. Evidence is scrubbed through the
// redactor before it leaves the main process.
const AUDIT_ALLOWED = new Set([
"fdesetup", "/usr/libexec/ApplicationFirewall/socketfilterfw", "defaults", "sysadminctl",
"spctl", "csrutil", "sshd", "systemsetup", "lsof", "ls", "manage-bde", "netsh", "sc",
"reg", "powershell", "net", "schtasks", "w32tm", "lsblk", "dmsetup", "ufw", "firewall-cmd",
"nft", "iptables", "apt-config", "systemctl", "gsettings", "ps", "cat", "getent", "ss",
"timedatectl", "mokutil",
]);
function auditExec(bin, args) {
return new Promise((resolve) => {
if (!AUDIT_ALLOWED.has(bin)) { resolve({ na: true, reason: "command not permitted by audit allowlist" }); return; }
let done = false;
const finish = (v) => { if (!done) { done = true; resolve(v); } };
try {
const child = execFile(bin, args || [], { timeout: 8000, maxBuffer: 4 * 1024 * 1024, windowsHide: true },
(err, stdout, stderr) => {
if (err && err.code === "ENOENT") { finish({ na: true, reason: "command not found (" + bin + ")" }); return; }
if (err && err.killed) { finish({ error: "timed out after 8s", code: -1, stdout: String(stdout || ""), stderr: String(stderr || "") }); return; }
finish({ ok: true, code: (err && typeof err.code === "number") ? err.code : 0, stdout: String(stdout || ""), stderr: String(stderr || "") });
});
child.on("error", (e) => { if (e && e.code === "ENOENT") finish({ na: true, reason: "command not found (" + bin + ")" }); else finish({ error: String((e && e.message) || e), code: -1, stdout: "", stderr: "" }); });
} catch (e) { finish({ error: String((e && e.message) || e), code: -1, stdout: "", stderr: "" }); }
});
}
function osDescription() {
try {
const p = process.platform;
if (p === "darwin") return "macOS " + os.release();
if (p === "win32") return "Windows " + os.release();
return (os.type() || "Linux") + " " + os.release();
} catch (_) { return process.platform; }
}
ipcMain.handle("audit:run", async () => {
try {
const report = await hardeningAudit.runAudit({
platform: process.platform,
exec: auditExec,
host: os.hostname(),
osDescription: osDescription(),
appVersion: app.getVersion(),
});
// Scrub any secret-shaped content out of every evidence string before it
// reaches the renderer / any export.
for (const r of report.results) { try { r.evidence = redactor.redact(r.evidence); } catch (_) {} }
return { ok: true, report };
} catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
});
ipcMain.handle("audit:export", (_e, { report, format }) => {
try {
if (!report || !Array.isArray(report.results)) return { ok: false, error: "no report" };
let text, ext, mime;
if (format === "csv") { text = hardeningAudit.toCSV(report); ext = "csv"; mime = "text/csv"; }
else if (format === "txt") { text = hardeningAudit.toText(report); ext = "txt"; mime = "text/plain"; }
else if (format === "fleet") { text = JSON.stringify(hardeningAudit.toFleetRecord(report), null, 2); ext = "json"; mime = "application/json"; }
else { text = hardeningAudit.toJSON(report); ext = "json"; mime = "application/json"; }
return { ok: true, text, ext, mime };
} catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
});
ipcMain.handle("audit:save", async (_e, { text, defaultName, ext }) => {
try {
const r = await dialog.showSaveDialog(win, { defaultPath: defaultName || ("workstation-audit." + (ext || "txt")) });
if (r.canceled || !r.filePath) return { ok: false, canceled: true };
await fs.promises.writeFile(r.filePath, String(text == null ? "" : text), "utf8");
return { ok: true, path: r.filePath };
} catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
});
ipcMain.handle("openExternal", (_e, url) => {
// Only open web URLs in the OS browser -- never file://, or app/protocol-handler
// schemes a browsed/redirected page could smuggle in.
try { const p = new URL(String(url)).protocol; if (p === "http:" || p === "https:") return shell.openExternal(url); } catch (_) {}
return false;
});
// ---- Web shell: Google sign-in via the system browser (D0) ----
// Google blocks OAuth inside embedded browsers, so the page asks the app. The
// system browser runs loopback + PKCE and only the Google ID token comes back;
// the page signs in to Firebase with it. One flow at a time; a new request
// cancels the previous one. Nothing here logs or stores the token.
const GOOGLE_SIGNIN = {
clientId: process.env.DARKNODE_GOOGLE_CLIENT_ID || _oauthCfg.googleSignInClientId || _oauthCfg.gmailClientId || "",
clientSecret: process.env.DARKNODE_GOOGLE_CLIENT_SECRET || _oauthCfg.googleSignInClientSecret || (_oauthCfg.googleSignInClientId ? "" : _oauthCfg.gmailClientSecret) || "",
};
let _cancelGoogle = null;
ipcMain.handle("auth:google", async () => {
if (_cancelGoogle) { try { _cancelGoogle(); } catch (_) {} }
const r = await runGoogleSignIn({
http, fetchImpl: fetch, openExternal: (u) => shell.openExternal(u),
clientId: GOOGLE_SIGNIN.clientId, clientSecret: GOOGLE_SIGNIN.clientSecret,
onCancel: (fn) => { _cancelGoogle = fn; },
});
_cancelGoogle = null;
if (r.ok && win) { if (win.isMinimized()) win.restore(); win.focus(); }
return r.ok ? { ok: true, idToken: r.idToken } : { ok: false, error: r.error };
});
// Recolour the native window-controls overlay so it matches the page's top bar.
ipcMain.handle("shell:titlebar", (_e, opts) => {
if (!win || process.platform === "darwin" || typeof win.setTitleBarOverlay !== "function") return false;
const hex = (v) => (typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v) ? v : undefined);
const o = {};
if (hex(opts && opts.color)) o.color = opts.color;
if (hex(opts && opts.symbolColor)) o.symbolColor = opts.symbolColor;
const h = Number(opts && opts.height);
if (Number.isInteger(h) && h >= 28 && h <= 80) o.height = h;
if (!Object.keys(o).length) return false;
try { win.setTitleBarOverlay(o); return true; } catch (_) { return false; }
});
// ---- custom (frameless) window controls ----
// Each acts on the window that asked (the main window, or the native tools window).
const callerWin = (e) => { try { return BrowserWindow.fromWebContents(e.sender); } catch (_) { return null; } };
ipcMain.handle("win:minimize", (e) => { const w = callerWin(e); if (w) w.minimize(); });
ipcMain.handle("win:maximize", (e) => { const w = callerWin(e); if (!w) return false; w.isMaximized() ? w.unmaximize() : w.maximize(); return w.isMaximized(); });
ipcMain.handle("win:close", (e) => { const w = callerWin(e); if (w) w.close(); });
ipcMain.handle("win:close-now", (e) => { // user confirmed closing with work in flight
const w = callerWin(e);
if (w && w === nativeWin && typeof w._dnForceClose === "function") { w._dnForceClose(); return; }
_forceClose = true; if (win) win.close();
});