-
Notifications
You must be signed in to change notification settings - Fork 697
Expand file tree
/
Copy pathfull.js
More file actions
3978 lines (3727 loc) · 130 KB
/
full.js
File metadata and controls
3978 lines (3727 loc) · 130 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
const {app, screen, shell, BrowserWindow, BrowserView, ipcMain, dialog, clipboard, session, desktopCapturer, systemPreferences, Menu } = require('electron')
const windowStateKeeper = require('electron-window-state');
const fs = require('fs')
const path = require("path")
const Pinokiod = require("pinokiod")
const os = require('os')
const Updater = require('./updater')
const createPopupShellManager = require('./popup-shell')
const is_mac = process.platform.startsWith("darwin")
const platform = os.platform()
var mainWindow;
var root_url;
var wins = {}
var pinned = {}
var launched
var theme
var colors
var splashWindow
var splashIcon
var updateBannerPayload
var updateBannerDismissed = false
var updateInfo = null
var updateDownloadInFlight = false
const updateTestMode = (() => {
const value = process.env.PINOKIO_TEST_UPDATE_BANNER
if (!value) {
return false
}
return ['1', 'true', 'yes', 'on'].includes(String(value).toLowerCase())
})()
let updateTestInterval = null
let updateTestTimeout = null
const UPDATE_RELEASES_URL = 'https://github.com/peanutcocktail/pinokio/releases'
const setWindowTitleBarOverlay = (win, overlay) => {
if (!win || !win.setTitleBarOverlay) {
return
}
try {
win.setTitleBarOverlay(overlay)
} catch (e) {
// console.log("ERROR", e)
}
}
const applyTitleBarOverlayToAllWindows = () => {
if (!colors) {
return
}
const overlay = titleBarOverlay(colors)
const browserWindows = BrowserWindow.getAllWindows()
for (const win of browserWindows) {
setWindowTitleBarOverlay(win, overlay)
}
}
const updateThemeColors = (payload = {}) => {
console.log("updateThemeColors", payload)
const nextTheme = payload.theme
const nextColors = payload.colors
if (nextTheme) {
theme = nextTheme
}
if (nextColors) {
colors = nextColors
}
applyTitleBarOverlayToAllWindows()
}
const stripHtmlTags = (value) => {
if (!value) {
return ''
}
return String(value).replace(/<[^>]*>/g, '')
}
const buildReleaseNotesPreview = (notes) => {
if (!notes) {
return ''
}
let text = ''
if (Array.isArray(notes)) {
text = notes.map((note) => note && (note.note || note.releaseNotes || note.title || '')).join('\n')
} else if (typeof notes === 'string') {
text = notes
} else {
text = String(notes)
}
const cleaned = stripHtmlTags(text).replace(/\r/g, '')
const lines = cleaned.split('\n').map((line) => line.trim()).filter(Boolean)
if (!lines.length) {
return ''
}
const firstLine = lines[0]
if (firstLine.length > 140) {
return `${firstLine.slice(0, 137)}...`
}
return firstLine
}
const buildProgressLabel = (progress) => {
if (!progress || typeof progress.percent !== 'number') {
return ''
}
const percent = Math.round(progress.percent)
if (typeof progress.transferred === 'number' && typeof progress.total === 'number' && progress.total > 0) {
const transferred = (progress.transferred / 1024 / 1024).toFixed(1)
const total = (progress.total / 1024 / 1024).toFixed(1)
return `${percent}% (${transferred} MB of ${total} MB)`
}
return `${percent}%`
}
const buildUpdateBannerPayload = (state, info, extra = {}) => {
const resolved = info || {}
return {
state,
version: resolved.version || '',
notesPreview: buildReleaseNotesPreview(resolved.releaseNotes),
releaseUrl: UPDATE_RELEASES_URL,
...extra
}
}
const clearUpdateTestTimers = () => {
if (updateTestInterval) {
clearInterval(updateTestInterval)
updateTestInterval = null
}
if (updateTestTimeout) {
clearTimeout(updateTestTimeout)
updateTestTimeout = null
}
}
const showUpdateBannerTestAvailable = () => {
updateInfo = {
version: '99.9.9-test',
releaseNotes: 'Simulated update for banner testing.'
}
updateDownloadInFlight = false
updateBannerDismissed = false
showUpdateBanner(buildUpdateBannerPayload('available', updateInfo))
}
const startUpdateBannerTestDownload = () => {
if (!updateInfo) {
showUpdateBannerTestAvailable()
}
clearUpdateTestTimers()
updateDownloadInFlight = true
let progress = 0
const tick = () => {
progress = Math.min(100, progress + 6 + Math.random() * 12)
showUpdateBanner(buildUpdateBannerPayload('downloading', updateInfo, {
progressPercent: progress,
notesPreview: `${Math.round(progress)}%`
}))
if (progress >= 100) {
clearUpdateTestTimers()
updateDownloadInFlight = false
showUpdateBanner(buildUpdateBannerPayload('ready', updateInfo))
}
}
tick()
updateTestInterval = setInterval(tick, 320)
}
const simulateUpdateBannerRestart = () => {
clearUpdateTestTimers()
hideUpdateBanner()
updateTestTimeout = setTimeout(() => {
showUpdateBannerTestAvailable()
}, 800)
}
const dispatchUpdateBanner = (payload) => {
updateBannerPayload = payload
if (!mainWindow || mainWindow.isDestroyed()) {
return
}
if (payload && payload.state === 'available' && updateBannerDismissed) {
return
}
if (mainWindow.webContents && !mainWindow.webContents.isDestroyed()) {
if (!mainWindow.webContents.isLoading()) {
mainWindow.webContents.send('pinokio:update-banner', payload)
}
}
}
const showUpdateBanner = (payload) => {
if (payload && payload.state === 'available' && updateBannerDismissed) {
updateBannerPayload = payload
return
}
dispatchUpdateBanner(payload || updateBannerPayload)
}
const hideUpdateBanner = () => {
dispatchUpdateBanner({ state: 'hidden' })
}
let PORT
//let PORT = 42000
//let PORT = (platform === 'linux' ? 42000 : 80)
let config = require('./config')
const filter = function (item) {
return item.browserName === 'Chrome';
};
const updater = new Updater()
const pinokiod = new Pinokiod(config)
const ENABLE_BROWSER_CONSOLE_LOG = process.env.PINOKIO_BROWSER_LOG === '1'
const browserConsoleState = new WeakMap()
const attachedConsoleListeners = new WeakSet()
const consoleLevelLabels = ['log', 'info', 'warn', 'error', 'debug']
let browserLogFilePath
let browserLogFileReady = false
let browserLogBuffer = []
let browserLogWritePromise = Promise.resolve()
let permissionHandlersInstalled = false
let injectorHandlersInstalled = false
const frameInjectorSyncState = new Map()
const frameInjectTargetRegistry = new Map()
const PINOKIO_INJECT_ISOLATED_WORLD_ID = 42000
const permissionPrompted = new Set()
const permissionPromptInFlight = new Set()
const safeParseUrl = (value, base) => {
if (!value) {
return null
}
try {
if (base) {
return new URL(value, base)
}
return new URL(value)
} catch (err) {
return null
}
}
const popupNavigationGuards = new Map()
const isRootShellUrl = (value) => {
const root = safeParseUrl(root_url)
const target = safeParseUrl(value, root ? root.href : undefined)
return Boolean(root && target && target.origin === root.origin && (target.pathname || '/') === '/')
}
const getHttpNavigationTarget = (value, base) => {
const target = safeParseUrl(value, base)
if (!target || (target.protocol !== 'http:' && target.protocol !== 'https:')) {
return null
}
return target
}
const resolveNavigationTarget = ({ url, openerWebContents, baseUrl } = {}) => {
const openerUrl = (() => {
if (typeof baseUrl === 'string' && baseUrl) {
return baseUrl
}
try {
return openerWebContents && !openerWebContents.isDestroyed()
? openerWebContents.getURL()
: (root_url || '')
} catch (_) {
return root_url || ''
}
})()
return getHttpNavigationTarget(url, openerUrl || (root_url || undefined))
}
const openHttpsInBrowser = ({ event, url, openerWebContents, baseUrl } = {}) => {
const target = resolveNavigationTarget({ url, openerWebContents, baseUrl })
if (target?.protocol !== 'https:') {
return false
}
event?.preventDefault?.()
shell.openExternal(target.href).catch(() => {})
return true
}
const openPopupShellHttpsNavigationInBrowser = ({ event, owner, url, openerWebContents, baseUrl } = {}) => {
if (!owner?.__pinokioPopupShell) {
return false
}
return openHttpsInBrowser({ event, url, openerWebContents, baseUrl })
}
const openNonPinokioNavigationInPopup = ({ event, owner, url, frame } = {}) => {
const target = getHttpNavigationTarget(url, root_url || undefined)
if (!target || !owner || owner.isDestroyed?.() || owner.__pinokioPopupShell) {
return false
}
if (popupShellManager.isPinokioWindowUrl(target.href, root_url)) {
return false
}
if (event && typeof event.preventDefault === 'function') {
event.preventDefault()
}
const frameId = frame && (frame.frameToken || frame.frameTreeNodeId || frame.routingId)
if (frameId) {
const guardKey = `${owner.id}:${frameId}:${target.href}`
const now = Date.now()
const last = popupNavigationGuards.get(guardKey) || 0
popupNavigationGuards.set(guardKey, now)
setTimeout(() => {
if (popupNavigationGuards.get(guardKey) === now) {
popupNavigationGuards.delete(guardKey)
}
}, 1500)
if (now - last < 1500) {
return true
}
}
popupShellManager.openExternalWindow({ url: target.href })
return true
}
const installForceDestroyOnClose = (win) => {
if (!win || win.__pinokioCloseHandlerInstalled) {
return
}
win.__pinokioCloseHandlerInstalled = true
win.once('close', (event) => {
if (win.isDestroyed()) {
return
}
event.preventDefault()
win.destroy()
})
}
const popupShellManager = createPopupShellManager({
installForceDestroyOnClose
})
const normalizeOpenSurface = (value) => {
return String(value || '').trim().toLowerCase() === 'browser' ? 'browser' : 'popup'
}
const normalizePopupPreset = (value) => {
const normalized = String(value || '').trim().toLowerCase()
if (normalized === 'center-small' || normalized === 'center-medium' || normalized === 'center-large' || normalized === 'fullscreen') {
return normalized
}
return 'center-medium'
}
const clampDimension = (value, min, max) => {
const boundedMax = Math.max(min, max)
return Math.max(min, Math.min(value, boundedMax))
}
const buildPopupWindowState = ({ preset } = {}) => {
const resolvedPreset = normalizePopupPreset(preset)
const point = (() => {
try {
return screen.getCursorScreenPoint()
} catch (_) {
return { x: 0, y: 0 }
}
})()
const display = screen.getDisplayNearestPoint(point) || screen.getPrimaryDisplay()
const workArea = display && display.workArea
? display.workArea
: { x: 0, y: 0, width: 1280, height: 800 }
let width = 960
let height = 720
if (resolvedPreset === 'center-small') {
width = clampDimension(Math.round(workArea.width * 0.42), 640, workArea.width)
height = clampDimension(Math.round(workArea.height * 0.52), 480, workArea.height)
} else if (resolvedPreset === 'center-large') {
width = clampDimension(Math.round(workArea.width * 0.82), 1100, workArea.width)
height = clampDimension(Math.round(workArea.height * 0.86), 820, workArea.height)
} else if (resolvedPreset === 'fullscreen') {
width = workArea.width
height = workArea.height
} else {
width = clampDimension(Math.round(workArea.width * 0.64), 900, workArea.width)
height = clampDimension(Math.round(workArea.height * 0.72), 700, workArea.height)
}
const x = resolvedPreset === 'fullscreen'
? workArea.x
: workArea.x + Math.max(Math.round((workArea.width - width) / 2), 0)
const y = resolvedPreset === 'fullscreen'
? workArea.y
: workArea.y + Math.max(Math.round((workArea.height - height) / 2), 0)
return {
preset: resolvedPreset,
windowState: {
x,
y,
width,
height,
manage: () => {}
}
}
}
const installClosePopupOnDownload = (targetSession) => {
if (!targetSession || targetSession.__pinokioClosePopupOnDownloadInstalled) {
return
}
targetSession.__pinokioClosePopupOnDownloadInstalled = true
targetSession.on('will-download', (_event, _item, webContents) => {
if (!webContents || typeof webContents.getOwnerBrowserWindow !== 'function') {
return
}
let owner = null
try {
owner = webContents.getOwnerBrowserWindow()
} catch (_) {
owner = null
}
if (!owner || owner.isDestroyed?.() || !owner.__pinokioCloseOnFirstDownload) {
return
}
owner.__pinokioCloseOnFirstDownload = false
setTimeout(() => {
if (!owner.isDestroyed()) {
owner.close()
}
}, 0)
})
}
const resolveConsoleSourceUrl = (sourceId, pageUrl) => {
const page = safeParseUrl(pageUrl)
const source = safeParseUrl(sourceId, page ? page.href : undefined)
if (source && (source.protocol === 'http:' || source.protocol === 'https:' || source.protocol === 'file:')) {
return source.href
}
if (page) {
return page.href
}
return null
}
const shouldLogUrl = (url) => {
if (!ENABLE_BROWSER_CONSOLE_LOG) {
return false
}
if (!url) {
return false
}
const rootParsed = safeParseUrl(root_url)
const target = safeParseUrl(url, rootParsed ? rootParsed.origin : undefined)
if (!target) {
return false
}
if (rootParsed) {
if (target.origin !== rootParsed.origin) {
return false
}
const normalizedTargetPath = (target.pathname || '').replace(/\/+$/, '')
const normalizedRootPath = (rootParsed.pathname || '').replace(/\/+$/, '')
if (normalizedTargetPath === normalizedRootPath) {
return false
}
} else {
const normalizedTargetPath = (target.pathname || '').replace(/\/+$/, '')
if (!normalizedTargetPath) {
return false
}
}
return true
}
const getBrowserLogFile = () => {
if (!ENABLE_BROWSER_CONSOLE_LOG) {
return null
}
if (!browserLogFilePath) {
if (!pinokiod || !pinokiod.kernel || !pinokiod.kernel.homedir) {
return null
}
try {
browserLogFilePath = pinokiod.kernel.path('logs/browser.log')
} catch (err) {
console.error('[BROWSER LOG] Failed to resolve browser log file path', err)
return null
}
}
return browserLogFilePath
}
const ensureBrowserLogFile = () => {
if (!ENABLE_BROWSER_CONSOLE_LOG) {
return null
}
const filePath = getBrowserLogFile()
if (!filePath) {
return null
}
if (browserLogFileReady) {
return filePath
}
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true })
if (fs.existsSync(filePath)) {
try {
const existingContent = fs.readFileSync(filePath, 'utf8')
const existingLines = existingContent.split(/\r?\n/).filter((line) => line.length > 0)
const filteredLines = []
for (const line of existingLines) {
const parts = line.split('\t')
if (parts.length >= 2) {
const urlPart = parts[1]
if (!shouldLogUrl(urlPart)) {
continue
}
}
filteredLines.push(`${line}\n`)
if (filteredLines.length > 100) {
filteredLines.shift()
}
}
browserLogBuffer = filteredLines
fs.writeFileSync(filePath, browserLogBuffer.join(''))
} catch (err) {
console.error('[BROWSER LOG] Failed to prime existing browser log', err)
browserLogBuffer = []
}
}
browserLogFileReady = true
return filePath
} catch (err) {
console.error('[BROWSER LOG] Failed to prepare browser log file', err)
return null
}
}
const titleBarOverlay = (colors) => {
if (is_mac) {
return false
} else {
return colors
}
}
const getLogFileHint = () => {
try {
if (pinokiod && pinokiod.kernel && pinokiod.kernel.homedir) {
return path.resolve(pinokiod.kernel.homedir, "logs", "stdout.txt")
}
} catch (err) {
}
return path.resolve(os.homedir(), ".pinokio", "logs", "stdout.txt")
}
const getSplashIcon = () => {
if (splashIcon) {
return splashIcon
}
const candidates = [
path.join('assets', 'icon.png'),
path.join('assets', 'icon_small@2x.png'),
path.join('assets', 'icon_small.png'),
'icon2.png'
]
for (const relative of candidates) {
const absolute = path.join(__dirname, relative)
if (fs.existsSync(absolute)) {
splashIcon = relative.split(path.sep).join('/')
return splashIcon
}
}
splashIcon = path.join('assets', 'icon_small.png').split(path.sep).join('/')
return splashIcon
}
const ensureSplashWindow = () => {
if (splashWindow && !splashWindow.isDestroyed()) {
return splashWindow
}
splashWindow = new BrowserWindow({
width: 420,
height: 320,
frame: false,
resizable: false,
transparent: true,
show: false,
alwaysOnTop: true,
skipTaskbar: true,
fullscreenable: false,
webPreferences: {
spellcheck: false,
backgroundThrottling: false
}
})
splashWindow.on('closed', () => {
splashWindow = null
})
return splashWindow
}
const updateSplashWindow = ({ state = 'loading', message, detail, logPath, icon } = {}) => {
const win = ensureSplashWindow()
const query = { state }
if (message) {
query.message = message
}
if (detail) {
const trimmed = detail.length > 800 ? `${detail.slice(0, 800)}…` : detail
query.detail = trimmed
}
if (logPath) {
query.log = logPath
}
if (icon) {
query.icon = icon
}
win.loadFile(path.join(__dirname, 'splash.html'), { query }).finally(() => {
if (!win.isDestroyed()) {
win.show()
}
})
}
const closeSplashWindow = () => {
if (splashWindow && !splashWindow.isDestroyed()) {
splashWindow.close()
}
}
const showStartupError = ({ message, detail, error } = {}) => {
const formatted = detail || formatStartupError(error)
updateSplashWindow({
state: 'error',
message: message || 'Pinokio could not start',
detail: formatted,
logPath: getLogFileHint(),
icon: getSplashIcon()
})
}
const formatStartupError = (error) => {
if (!error) {
return ''
}
if (error.stack) {
return `${error.message || 'Unknown error'}\n\n${error.stack}`
}
if (error.message) {
return error.message
}
if (typeof error === 'string') {
return error
}
try {
return JSON.stringify(error, null, 2)
} catch (err) {
return String(error)
}
}
const SESSION_COOKIE_TTL_DAYS = 90
const SESSION_COOKIE_TTL_SEC = SESSION_COOKIE_TTL_DAYS * 24 * 60 * 60
const SESSION_COOKIE_JAR_FILENAME = 'session-cookies.json'
let sessionCookieSavePromise = null
let isQuitting = false
const getSessionCookieJarPath = () => path.join(app.getPath('userData'), SESSION_COOKIE_JAR_FILENAME)
const buildCookieUrl = (cookie) => {
if (!cookie || !cookie.domain) {
return null
}
const host = cookie.domain.startsWith('.') ? cookie.domain.slice(1) : cookie.domain
if (!host) {
return null
}
const scheme = cookie.secure ? 'https://' : 'http://'
const cookiePath = cookie.path && cookie.path.startsWith('/') ? cookie.path : '/'
return `${scheme}${host}${cookiePath}`
}
const serializeSessionCookie = (cookie) => {
const url = buildCookieUrl(cookie)
if (!url || typeof cookie.name !== 'string') {
return null
}
const entry = {
url,
name: cookie.name,
value: typeof cookie.value === 'string' ? cookie.value : '',
path: cookie.path && cookie.path.startsWith('/') ? cookie.path : '/',
secure: !!cookie.secure,
httpOnly: !!cookie.httpOnly
}
if (cookie.hostOnly !== true && cookie.domain) {
entry.domain = cookie.domain
}
if (cookie.sameSite) {
entry.sameSite = cookie.sameSite
}
if (cookie.priority) {
entry.priority = cookie.priority
}
if (cookie.sameParty != null) {
entry.sameParty = cookie.sameParty
}
if (cookie.sourceScheme) {
entry.sourceScheme = cookie.sourceScheme
}
if (Number.isInteger(cookie.sourcePort)) {
entry.sourcePort = cookie.sourcePort
}
return entry
}
const persistSessionCookies = () => {
if (sessionCookieSavePromise) {
return sessionCookieSavePromise
}
sessionCookieSavePromise = (async () => {
try {
const cookies = await session.defaultSession.cookies.get({})
const sessionCookies = cookies.filter((cookie) => cookie && cookie.session)
const entries = sessionCookies.map(serializeSessionCookie).filter(Boolean)
const jarPath = getSessionCookieJarPath()
if (!entries.length) {
await fs.promises.unlink(jarPath).catch((err) => {
if (err && err.code !== 'ENOENT') {
console.warn('[Session Cookies] Failed to remove jar', err)
}
})
return
}
const payload = {
version: 1,
savedAt: Date.now(),
cookies: entries
}
await fs.promises.mkdir(path.dirname(jarPath), { recursive: true }).catch(() => {})
await fs.promises.writeFile(jarPath, JSON.stringify(payload), 'utf8')
} catch (err) {
console.warn('[Session Cookies] Failed to persist', err)
} finally {
sessionCookieSavePromise = null
}
})()
return sessionCookieSavePromise
}
const restoreSessionCookies = async () => {
const jarPath = getSessionCookieJarPath()
let raw
try {
raw = await fs.promises.readFile(jarPath, 'utf8')
} catch (err) {
if (err && err.code !== 'ENOENT') {
console.warn('[Session Cookies] Failed to read jar', err)
}
return
}
let data
try {
data = JSON.parse(raw)
} catch (err) {
console.warn('[Session Cookies] Failed to parse jar', err)
return
}
const entries = Array.isArray(data.cookies) ? data.cookies : []
if (!entries.length) {
return
}
const expirationDate = Math.floor(Date.now() / 1000) + SESSION_COOKIE_TTL_SEC
for (const entry of entries) {
if (!entry || !entry.url || !entry.name) {
continue
}
const details = {
url: entry.url,
name: entry.name,
value: typeof entry.value === 'string' ? entry.value : '',
path: entry.path || '/',
secure: !!entry.secure,
httpOnly: !!entry.httpOnly,
expirationDate
}
if (entry.domain) {
details.domain = entry.domain
}
if (entry.sameSite) {
details.sameSite = entry.sameSite
}
if (entry.priority) {
details.priority = entry.priority
}
if (entry.sameParty != null) {
details.sameParty = entry.sameParty
}
if (entry.sourceScheme) {
details.sourceScheme = entry.sourceScheme
}
if (Number.isInteger(entry.sourcePort)) {
details.sourcePort = entry.sourcePort
}
try {
await session.defaultSession.cookies.set(details)
} catch (err) {
console.warn('[Session Cookies] Failed to restore cookie', entry.name, err)
}
}
}
const clearPersistedSessionCookies = async () => {
const jarPath = getSessionCookieJarPath()
try {
await fs.promises.unlink(jarPath)
} catch (err) {
if (err && err.code !== 'ENOENT') {
console.warn('[Session Cookies] Failed to remove jar', err)
}
}
}
const clearSessionCaches = async () => {
try {
await session.defaultSession.clearCache()
} catch (err) {
console.warn('[Session Cache] Failed to clear http cache', err)
}
try {
await session.defaultSession.clearStorageData({
storages: ['serviceworkers', 'cachestorage']
})
} catch (err) {
console.warn('[Session Cache] Failed to clear service worker/cache storage', err)
}
}
function UpsertKeyValue(obj, keyToChange, value) {
const keyToChangeLower = keyToChange.toLowerCase();
for (const key of Object.keys(obj)) {
if (key.toLowerCase() === keyToChangeLower) {
// Reassign old key
obj[key] = value;
// Done
return;
}
}
// Insert at end instead
obj[keyToChange] = value;
}
const clearBrowserConsoleState = (webContents) => {
if (browserConsoleState.has(webContents)) {
browserConsoleState.delete(webContents)
}
}
const updateBrowserConsoleTarget = (webContents, url) => {
if (!ENABLE_BROWSER_CONSOLE_LOG) {
return
}
if (!root_url) {
clearBrowserConsoleState(webContents)
return
}
let parsed
try {
parsed = new URL(url)
} catch (e) {
clearBrowserConsoleState(webContents)
return
}
if (parsed.origin !== root_url) {
clearBrowserConsoleState(webContents)
return
}
const existing = browserConsoleState.get(webContents)
if (existing && existing.url === parsed.href) {
return
}
browserConsoleState.set(webContents, { url: parsed.href })
}
const inspectorSessions = new Map()
let inspectorHandlersInstalled = false
const inspectorLogFile = path.join(os.tmpdir(), 'pinokio-inspector.log')
const inspectorMainLog = (label, payload) => {
try {
const serialized = payload === undefined ? '' : ' ' + JSON.stringify(payload)
const line = `[InspectorMain] ${label}${serialized}\n`
try {
fs.appendFileSync(inspectorLogFile, line)
} catch (_) {}
process.stdout.write(line)
} catch (_) {
try {
fs.appendFileSync(inspectorLogFile, `[InspectorMain] ${label}\n`)
} catch (_) {}
process.stdout.write(`[InspectorMain] ${label}\n`)
}
}
const normalizeInspectorUrl = (value) => {
if (!value) {
return null
}
try {
return new URL(value).href
} catch (_) {
return value
}
}
const urlsRoughlyMatch = (expected, candidate) => {
if (!expected) {
return true
}
if (!candidate) {
return false
}
if (candidate === expected) {
return true
}
return candidate.startsWith(expected) || expected.startsWith(candidate)
}
const flattenFrameTree = (frame, acc = [], depth = 0) => {
if (!frame) {
return acc
}
let frameName = null
try {
frameName = typeof frame.name === 'string' && frame.name.length ? frame.name : null
} catch (_) {
frameName = null
}
acc.push({ frame, depth, url: normalizeInspectorUrl(frame.url || ''), name: frameName })
const children = Array.isArray(frame.frames) ? frame.frames : []
for (const child of children) {
flattenFrameTree(child, acc, depth + 1)
}
return acc
}
const findDescendantByUrl = (frame, targetUrl) => {
if (!frame || !targetUrl) {
return null
}
const normalizedTarget = normalizeInspectorUrl(targetUrl)
if (!normalizedTarget) {
return null
}
const stack = [frame]
while (stack.length) {
const current = stack.pop()
try {
const currentUrl = normalizeInspectorUrl(current.url || '')
if (currentUrl && urlsRoughlyMatch(normalizedTarget, currentUrl)) {
return current
}
} catch (_) {}
const children = Array.isArray(current.frames) ? current.frames : []
for (const child of children) {
if (child) {
stack.push(child)
}
}
}
return null
}
const selectTargetFrame = (webContents, payload = {}) => {
if (!webContents || !webContents.mainFrame) {
inspectorMainLog('no-webcontents', {})
return null
}
const frames = flattenFrameTree(webContents.mainFrame, [])
if (!frames.length) {
inspectorMainLog('no-frames', { webContentsId: webContents.id })
return null
}
inspectorMainLog('incoming', {
frameUrl: payload.frameUrl || null,
frameName: payload.frameName || null,
frameNodeId: payload.frameNodeId || null,
frameCount: frames.length,
})
const canonicalUrl = normalizeInspectorUrl(payload.frameUrl)
const relativeOrdinal = typeof payload.candidateRelativeOrdinal === 'number' ? payload.candidateRelativeOrdinal : null
const globalOrdinal = typeof payload.frameIndex === 'number' ? payload.frameIndex : null
const canonicalFrameName = typeof payload.frameName === 'string' && payload.frameName.trim() ? payload.frameName.trim() : null
const canonicalFrameNodeId = typeof payload.frameNodeId === 'string' && payload.frameNodeId.trim() ? payload.frameNodeId.trim() : null
if (canonicalFrameName || canonicalFrameNodeId) {
inspectorMainLog('identifier-search', {
frameName: canonicalFrameName || null,
frameNodeId: canonicalFrameNodeId || null,
names: frames.map((entry) => entry.name || null).slice(0, 12),
})
let identifierMatch = null
if (canonicalFrameNodeId) {
identifierMatch = frames.find((entry) => entry && entry.name === canonicalFrameNodeId) || null
if (identifierMatch) {
const normalizedUrl = normalizeInspectorUrl(identifierMatch.url || '')
if (canonicalUrl && (!normalizedUrl || !urlsRoughlyMatch(canonicalUrl, normalizedUrl))) {
const descendant = findDescendantByUrl(identifierMatch.frame, canonicalUrl)
if (descendant) {
inspectorMainLog('identifier-match-node-descendant', {
index: frames.indexOf(identifierMatch),
name: identifierMatch.name || null,
url: identifierMatch.url || null,
descendantUrl: normalizeInspectorUrl(descendant.url || ''),
})
return descendant
}
}
inspectorMainLog('identifier-match-node', {
index: frames.indexOf(identifierMatch),
name: identifierMatch.name || null,
url: identifierMatch.url || null,
})
return identifierMatch.frame
}
}
if (canonicalFrameName) {
identifierMatch = frames.find((entry) => entry && entry.name === canonicalFrameName) || null
if (identifierMatch) {
const normalizedUrl = normalizeInspectorUrl(identifierMatch.url || '')
if (canonicalUrl && (!normalizedUrl || !urlsRoughlyMatch(canonicalUrl, normalizedUrl))) {
const descendant = findDescendantByUrl(identifierMatch.frame, canonicalUrl)
if (descendant) {
inspectorMainLog('identifier-match-name-descendant', {
index: frames.indexOf(identifierMatch),
name: identifierMatch.name || null,
url: identifierMatch.url || null,
descendantUrl: normalizeInspectorUrl(descendant.url || ''),
})
return descendant
}
}
inspectorMainLog('identifier-match-name', {
index: frames.indexOf(identifierMatch),
name: identifierMatch.name || null,
url: identifierMatch.url || null,