-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathinjector.mjs
More file actions
2128 lines (2050 loc) · 83.4 KB
/
Copy pathinjector.mjs
File metadata and controls
2128 lines (2050 loc) · 83.4 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
import fs from "node:fs/promises";
import { constants as fsConstants, watch as watchFs } from "node:fs";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { Script } from "node:vm";
import { readImageMetadata } from "./image-metadata.mjs";
import {
normalizeThemeColor,
normalizeThemeText,
} from "../assets/theme-package-validator.mjs";
import { decodeAndValidateSafeCss } from "../assets/safe-css-validator.mjs";
const execFileAsync = promisify(execFile);
const scriptPath = fileURLToPath(import.meta.url);
const here = path.dirname(scriptPath);
const root = path.resolve(here, "..");
const SELECTOR_CONTRACT = JSON.parse(await fs.readFile(
path.join(root, "assets", "selectors.json"), "utf8",
));
if (SELECTOR_CONTRACT.schema !== "codex-dream-skin-selectors/1" ||
!Array.isArray(SELECTOR_CONTRACT.selectors)) {
throw new Error("assets/selectors.json has an unsupported schema");
}
const SELECTOR_MAP = new Map();
for (const entry of SELECTOR_CONTRACT.selectors) {
if (!entry?.key || !entry.selector || SELECTOR_MAP.has(entry.key)) {
throw new Error(`assets/selectors.json has an invalid selector key: ${entry?.key || "<missing>"}`);
}
SELECTOR_MAP.set(entry.key, entry.selector);
}
const selectorFor = (key) => {
const selector = SELECTOR_MAP.get(key);
if (!selector) throw new Error(`Selector contract is missing ${key}`);
return selector;
};
const selectorLiteral = (key) => JSON.stringify(selectorFor(key));
const stableTestidLiteral = (testid) => {
if (!SELECTOR_CONTRACT.stableTestids?.includes(testid)) {
throw new Error(`Selector contract is missing stable testid ${testid}`);
}
return JSON.stringify(`[data-testid="${testid}"]`);
};
const SKIN_VERSION = "1.5.11";
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
const CDP_ID_PATTERN = /^[A-Za-z0-9._-]{1,200}$/;
const MAX_ART_BYTES = 10 * 1024 * 1024;
const MAX_SAFE_CSS_BYTES = 256 * 1024;
const OPERATION_UI_HOST_ID = "chatgpt-dream-skin-operation";
const OPERATION_UI_REGISTRY_KEY = "__CHATGPT_DREAM_SKIN_OPERATION_UI__";
const OPERATION_KINDS = new Set(["apply", "pause", "switch"]);
const OPERATION_UI_STATES = new Set(["success", "error", "cancelled"]);
const MIN_RENDERER_WIDTH = 320;
const MIN_RENDERER_HEIGHT = 240;
const MAX_RENDERER_DIMENSION = 65536;
const OPERATION_UI_CSS = `
:host {
all: initial;
position: fixed;
top: var(--dream-skin-operation-top, 0px);
left: var(--dream-skin-operation-left, 0px);
width: var(--dream-skin-operation-width, 100vw);
height: var(--dream-skin-operation-height, 100vh);
z-index: 2147483647;
pointer-events: none;
opacity: 0;
display: grid;
place-items: center;
transition: opacity 180ms cubic-bezier(0.16, 1, 0.3, 1);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
}
:host([data-visible="true"]) {
opacity: 1;
}
.status {
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
width: min(220px, calc(100% - 32px));
min-height: 112px;
padding: 18px 20px;
border: 1px solid rgba(238, 239, 244, 0.16);
border-radius: 8px;
background: rgba(32, 33, 38, 0.94);
color: #f3f3f6;
box-shadow: 0 8px 24px rgba(12, 14, 19, 0.22);
font-size: 13px;
font-weight: 550;
line-height: 1.35;
letter-spacing: 0;
text-align: center;
transform: translateY(-4px) scale(0.98);
transition: transform 180ms cubic-bezier(0.16, 1, 0.3, 1);
}
:host([data-visible="true"]) .status {
transform: translateY(0) scale(1);
}
:host([data-tone="light"]) .status {
border-color: #d9dbe3;
background: rgba(248, 248, 251, 0.96);
color: #25262c;
box-shadow: 0 8px 24px rgba(31, 35, 48, 0.14);
}
.indicator {
box-sizing: border-box;
flex: 0 0 22px;
width: 22px;
height: 22px;
color: #78a8f5;
}
:host([data-state="loading"]) .indicator {
border: 2px solid currentColor;
border-top-color: transparent;
border-radius: 50%;
animation: dream-skin-operation-spin 720ms linear infinite;
}
:host([data-state="success"]) .indicator,
:host([data-state="error"]) .indicator,
:host([data-state="cancelled"]) .indicator {
display: grid;
place-items: center;
border-radius: 50%;
font-size: 16px;
font-weight: 750;
}
:host([data-state="success"]) .indicator {
color: #53b77b;
}
:host([data-state="success"]) .indicator::before {
content: "✓";
}
:host([data-state="error"]) .indicator {
color: #e26d7e;
}
:host([data-state="error"]) .indicator::before {
content: "!";
}
:host([data-state="cancelled"]) .indicator {
color: #a5a7b0;
}
:host([data-state="cancelled"]) .indicator::before {
content: "×";
}
.message {
min-width: 0;
overflow-wrap: anywhere;
}
@keyframes dream-skin-operation-spin {
to { transform: rotate(360deg); }
}
@media (prefers-reduced-motion: reduce) {
:host, .status { transition: none; }
:host([data-state="loading"]) .indicator {
animation: none;
border-top-color: currentColor;
opacity: 0.65;
}
}
`;
let staticPayloadAssets = null;
let operationSequence = 0;
function hasReasonableDimensions(width, height) {
return Number.isFinite(width) && Number.isFinite(height)
&& width >= MIN_RENDERER_WIDTH && height >= MIN_RENDERER_HEIGHT
&& width <= MAX_RENDERER_DIMENSION && height <= MAX_RENDERER_DIMENSION;
}
export function classifyNativeWindowResponse(response) {
const windowId = Number(response?.windowId);
const bounds = response?.bounds && typeof response.bounds === "object"
? {
width: Number(response.bounds.width),
height: Number(response.bounds.height),
windowState: typeof response.bounds.windowState === "string"
? response.bounds.windowState : null,
}
: null;
const stateReady = bounds
&& ["normal", "maximized", "fullscreen"].includes(bounds.windowState);
const ready = Number.isSafeInteger(windowId) && windowId > 0 && stateReady
&& hasReasonableDimensions(bounds.width, bounds.height);
return {
status: ready ? "ready" : "not-ready",
windowId: Number.isSafeInteger(windowId) && windowId > 0 ? windowId : null,
bounds,
reason: ready ? null : "native-window-not-visible",
};
}
export function classifyNativeWindowError(error) {
const message = error instanceof Error ? error.message : String(error ?? "");
const cdpCode = Number(error?.cdpCode);
const withoutCode = message.replace(/\s*\(-?\d+\)\s*$/, "").trim();
const domainUnsupported = cdpCode === -32601
|| /\(-32601\)\s*$/.test(message)
|| /^method(?: ['"]Browser\.getWindowForTarget['"])? not found$/i.test(withoutCode)
|| /^['"]?Browser\.getWindowForTarget['"]? (?:wasn't|was not) found$/i.test(withoutCode);
// Codex 26.721.x (Chrome/150) returns "Browser window not found" (-32000)
// for the app's real, focused, on-screen window -- verified live via CDP:
// the error stays identical before and after actually activating the
// window, while documentVisibility correctly flips hidden -> visible. The
// domain is implemented but this build never resolves a window for our
// target, so -32000 is exactly as uninformative here as -32601 elsewhere;
// treat it the same way and lean on documentVisible (still required by
// windowPass) as the real visibility signal. See #256.
const windowNotFound = cdpCode === -32000
|| /\(-32000\)\s*$/.test(message)
|| /^browser window not found$/i.test(withoutCode);
const unsupported = domainUnsupported || windowNotFound;
return {
status: unsupported ? "unsupported" : "not-ready",
windowId: null,
bounds: null,
reason: domainUnsupported ? "browser-window-domain-unsupported"
: windowNotFound ? "browser-window-not-found"
: "native-window-unavailable",
};
}
export function assessRendererVerification(renderer, nativeWindow, expected) {
const result = renderer && typeof renderer === "object" ? { ...renderer } : {};
const viewportWidth = Number(result.viewport?.width);
const viewportHeight = Number(result.viewport?.height);
const viewportPass = hasReasonableDimensions(viewportWidth, viewportHeight);
const documentVisible = result.documentVisibility === "visible";
const settingsRoute = result.scope?.baseState === "settings";
const homeRoute = result.scope?.baseState === "home" || result.homeRoute || result.homePresent;
const l1ScopePass = result.scope?.level === "L1" &&
Array.isArray(result.scope?.missingL1) && result.scope.missingL1.length === 0;
const genericStructurePass = l1ScopePass && Boolean(result.genericMain?.visible) &&
(Boolean(result.genericInput?.visible) || Boolean(homeRoute && result.homePresent));
const l0StructurePass = result.scope?.level === "L0" &&
settingsRoute && Boolean(result.settings?.visible);
const structurePass = l0StructurePass || (l1ScopePass && (
(Boolean(result.shell?.visible) && Boolean(result.sidebar?.visible)) || genericStructurePass
));
const nativeWindowPass = nativeWindow?.status === "ready";
const fallbackWindowPass = nativeWindow?.status === "unsupported";
const windowPass = documentVisible && viewportPass
&& (nativeWindowPass || fallbackWindowPass);
const basePass = result.installed && result.version === expected.skinVersion
&& result.stylePresent && result.businessClassPollution === 0
&& structurePass && windowPass && !result.documentOverflow?.x;
const payloadPass = (!expected.expectedThemeId || result.themeId === expected.expectedThemeId)
&& (!expected.expectedRevision || result.revision === expected.expectedRevision);
const visibleSuggestionLabels = Array.isArray(result.suggestionLabels)
? result.suggestionLabels.filter((item) => item?.visible) : [];
const homeFallbackVisible = Boolean(homeRoute && result.homePresent && result.genericMain?.visible);
const homePass = !homeRoute || (
result.homePresent && ((result.hero?.visible && result.hero.width >= 280
&& result.hero.height >= 120) || homeFallbackVisible)
&& (result.visibleCardCount === 0 || (
visibleSuggestionLabels.length >= result.visibleCardCount
&& result.suggestionLabelColorsMatch
))
);
result.nativeWindow = nativeWindow;
result.checks = {
documentVisible,
fallbackWindowPass,
nativeWindowPass,
payloadPass,
structurePass,
viewportPass,
windowPass,
};
result.pass = Boolean(basePass && homePass && payloadPass);
result.expectedThemeId = expected.expectedThemeId;
result.expectedRevision = expected.expectedRevision;
result.softNotes = {
projectButtonOptional: !result.projectButton?.visible,
composerOptionalOnNonTaskRoutes: !result.composer?.visible,
suggestionCardsOptional: homeRoute && result.visibleCardCount === 0,
};
return result;
}
function parseArgs(argv) {
const options = {
port: 9341,
mode: "watch",
timeoutMs: 30000,
screenshot: null,
reload: false,
themeDir: null,
operationState: null,
operationAck: null,
operationKind: null,
operationUiState: null,
operationMessage: null,
operationToken: null,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "--port") options.port = Number(argv[++i]);
else if (arg === "--once") options.mode = "once";
else if (arg === "--watch") options.mode = "watch";
else if (arg === "--verify") options.mode = "verify";
else if (arg === "--remove") options.mode = "remove";
else if (arg === "--begin-operation") options.mode = "begin-operation";
else if (arg === "--finish-operation") options.mode = "finish-operation";
else if (arg === "--check-payload") options.mode = "check";
else if (arg === "--timeout-ms") options.timeoutMs = Number(argv[++i]);
else if (arg === "--screenshot") options.screenshot = path.resolve(argv[++i]);
else if (arg === "--theme-dir") options.themeDir = path.resolve(argv[++i]);
else if (arg === "--operation-state") options.operationState = path.resolve(argv[++i]);
else if (arg === "--operation-ack") options.operationAck = path.resolve(argv[++i]);
else if (arg === "--operation-kind") options.operationKind = argv[++i];
else if (arg === "--operation-ui-state") options.operationUiState = argv[++i];
else if (arg === "--operation-message") options.operationMessage = argv[++i];
else if (arg === "--operation-token") options.operationToken = argv[++i];
else if (arg === "--reload") options.reload = true;
else throw new Error(`Unknown argument: ${arg}`);
}
if (!Number.isInteger(options.port) || options.port < 1024 || options.port > 65535) {
throw new Error(`Invalid port: ${options.port}`);
}
if (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 250 || options.timeoutMs > 120000) {
throw new Error(`Invalid timeout: ${options.timeoutMs}`);
}
if (options.operationToken !== null && !/^\d{1,12}:\d{13}:\d{1,8}$/.test(options.operationToken)) {
throw new Error("Invalid operation token");
}
if (options.mode === "begin-operation" && !OPERATION_KINDS.has(options.operationKind)) {
throw new Error("Begin operation requires --operation-kind apply, pause, or switch");
}
if (options.mode === "finish-operation") {
if (!OPERATION_UI_STATES.has(options.operationUiState)) {
throw new Error("Finish operation requires --operation-ui-state success, error, or cancelled");
}
if (!options.operationToken) throw new Error("Finish operation requires --operation-token");
if (typeof options.operationMessage !== "string" || options.operationMessage.length > 240
|| /[\r\n]/.test(options.operationMessage)) {
throw new Error("Finish operation requires a single-line --operation-message up to 240 characters");
}
}
return options;
}
function validatedDebuggerUrl(target, port) {
const url = new URL(target.webSocketDebuggerUrl);
const pathIsValid = /^\/devtools\/page\/[A-Za-z0-9._-]{1,200}$/.test(url.pathname);
if (
url.protocol !== "ws:" || !LOOPBACK_HOSTS.has(url.hostname) || Number(url.port) !== port
|| url.username || url.password || url.search || url.hash || !pathIsValid
) {
throw new Error("Rejected a CDP WebSocket URL outside the allowed loopback page endpoint shape");
}
return url.href;
}
function isValidCdpPageTarget(item, port) {
if (
item?.type !== "page" || !item.url?.startsWith("app://")
|| typeof item.id !== "string" || !CDP_ID_PATTERN.test(item.id)
|| !item.webSocketDebuggerUrl
) return false;
try {
const debuggerUrl = new URL(validatedDebuggerUrl(item, port));
return debuggerUrl.pathname === `/devtools/page/${item.id}`;
} catch {
return false;
}
}
class CdpSession {
constructor(target, port) {
this.target = target;
this.ws = new WebSocket(validatedDebuggerUrl(target, port));
this.nextId = 1;
this.pending = new Map();
this.listeners = new Map();
this.closed = false;
}
async open() {
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
try { this.ws.close(); } catch {}
reject(new Error("CDP WebSocket open timed out"));
}, 5000);
this.ws.addEventListener("open", () => { clearTimeout(timeout); resolve(); }, { once: true });
this.ws.addEventListener("error", () => { clearTimeout(timeout); reject(new Error("CDP WebSocket open failed")); }, { once: true });
});
this.ws.addEventListener("message", (event) => this.onMessage(event));
this.ws.addEventListener("error", () => this.close());
this.ws.addEventListener("close", () => {
this.closed = true;
for (const waiter of this.pending.values()) {
clearTimeout(waiter.timeout);
waiter.reject(new Error("CDP socket closed"));
}
this.pending.clear();
});
await this.send("Runtime.enable");
await this.send("Page.enable");
return this;
}
onMessage(event) {
let message;
try {
message = JSON.parse(String(event.data));
} catch {
this.close();
return;
}
if (!message || typeof message !== "object") {
this.close();
return;
}
if (message.id) {
const waiter = this.pending.get(message.id);
if (!waiter) return;
clearTimeout(waiter.timeout);
this.pending.delete(message.id);
if (message.error) {
const error = new Error(`${message.error.message} (${message.error.code})`);
error.cdpCode = message.error.code;
waiter.reject(error);
} else waiter.resolve(message.result);
return;
}
for (const listener of this.listeners.get(message.method) ?? []) {
try { listener(message.params ?? {}); } catch (error) {
console.error(`[dream-skin] CDP listener failed: ${error.message}`);
}
}
}
on(method, listener) {
const listeners = this.listeners.get(method) ?? [];
listeners.push(listener);
this.listeners.set(method, listeners);
}
send(method, params = {}, timeoutMs = 10000) {
if (this.closed) return Promise.reject(new Error("CDP session is closed"));
return new Promise((resolve, reject) => {
const id = this.nextId++;
const timeout = setTimeout(() => {
this.pending.delete(id);
reject(new Error(`CDP command timed out: ${method}`));
}, timeoutMs);
this.pending.set(id, { resolve, reject, timeout });
try {
this.ws.send(JSON.stringify({ id, method, params }));
} catch (error) {
clearTimeout(timeout);
this.pending.delete(id);
reject(error);
}
});
}
async evaluate(expression, timeoutMs = 10000) {
const result = await this.send("Runtime.evaluate", {
expression,
awaitPromise: true,
returnByValue: true,
userGesture: false,
}, timeoutMs);
if (result.exceptionDetails) {
const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.text;
throw new Error(`Renderer evaluation failed: ${detail}`);
}
return result.result?.value;
}
close() {
for (const waiter of this.pending.values()) {
clearTimeout(waiter.timeout);
waiter.reject(new Error("CDP session closed"));
}
this.pending.clear();
if (!this.closed) {
try { this.ws.close(); } catch {}
}
this.closed = true;
}
}
async function listAppTargets(port) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 2000);
try {
const response = await fetch(`http://127.0.0.1:${port}/json/list`, {
redirect: "error",
signal: controller.signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const targets = await response.json();
if (!Array.isArray(targets)) throw new Error("CDP target list was not an array");
return targets.filter((item) => isValidCdpPageTarget(item, port));
} finally {
clearTimeout(timeout);
}
}
async function probeSession(session) {
return session.evaluate(`(() => {
const genericCodexSurface = () => {
if (location.protocol !== 'app:') return false;
const main = document.querySelector('main, [role="main"]');
const input = document.querySelector('textarea, [contenteditable="true"], [role="textbox"]');
const branded = Boolean(document.querySelector(
${stableTestidLiteral("app-shell-header-context-menu-surface")},
));
return Boolean(main && input && branded);
};
const markers = {
shell: Boolean(document.querySelector(${selectorLiteral("shell-main")})),
sidebar: Boolean(document.querySelector(${selectorLiteral("left-panel")})),
composer: Boolean(document.querySelector(${selectorLiteral("composer-chrome")})),
main: Boolean(document.querySelector(${selectorLiteral("home-route")})),
generic: genericCodexSurface(),
};
const settings = Boolean(document.querySelector(${selectorLiteral("settings-panel")})) ||
Boolean(document.querySelector(${selectorLiteral("appearance-radio")})) ||
Boolean(document.querySelector(${stableTestidLiteral("theme-preview")}));
return {
markers,
codex: location.protocol === 'app:' &&
((markers.shell && markers.sidebar) || settings || markers.main || markers.generic),
};
})()`);
}
async function waitForCodexProbe(session, timeoutMs = 1800) {
const deadline = Date.now() + timeoutMs;
let probe = null;
while (Date.now() < deadline) {
probe = await probeSession(session);
if (probe?.codex) return probe;
await new Promise((resolve) => setTimeout(resolve, 50));
}
return probe;
}
async function connectTarget(target, port) {
return new CdpSession(target, port).open();
}
async function connectCodexTargets(port, timeoutMs) {
const deadline = Date.now() + timeoutMs;
let lastError;
while (Date.now() < deadline) {
try {
const targets = await listAppTargets(port);
const connected = [];
for (const target of targets) {
let session;
try {
session = await connectTarget(target, port);
const probe = await probeSession(session);
if (probe?.codex) connected.push({ target, session, probe });
else session.close();
} catch (error) {
session?.close();
lastError = error;
}
}
if (connected.length) return connected;
lastError = new Error("No page matched the expected ChatGPT shell markers");
} catch (error) {
lastError = error;
}
await new Promise((resolve) => setTimeout(resolve, 350));
}
throw new Error(`No verified ChatGPT renderer on 127.0.0.1:${port}: ${lastError?.message ?? "timed out"}`);
}
function assertContainedPath(rootPath, candidatePath, label) {
const relative = path.relative(rootPath, candidatePath);
if (
relative === ""
|| (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
) return;
throw new Error(`${label} must stay inside its theme directory`);
}
function sameFileStat(left, right) {
return left.isFile() && right.isFile()
&& left.dev === right.dev
&& left.ino === right.ino
&& left.size === right.size
&& left.mtimeMs === right.mtimeMs
&& left.ctimeMs === right.ctimeMs;
}
async function loadSafeCss(assetsRoot) {
const cssPath = path.join(assetsRoot, "theme.css");
let handle;
try {
handle = await fs.open(cssPath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
} catch (error) {
if (error.code === "ENOENT") return null;
if (error.code === "ELOOP") throw new Error("Theme Safe CSS must not be a symbolic link");
throw error;
}
try {
const before = await handle.stat();
if (!before.isFile() || before.size < 1 || before.size > MAX_SAFE_CSS_BYTES) {
throw new Error(`Theme Safe CSS must be a non-empty file no larger than ${MAX_SAFE_CSS_BYTES} bytes`);
}
const bytes = await handle.readFile();
const after = await handle.stat();
if (!sameFileStat(before, after) || bytes.length !== after.size) {
throw new Error("Theme Safe CSS changed while being loaded");
}
const { source, runtimeSource, validation } = decodeAndValidateSafeCss(bytes);
return { path: cssPath, runtimeSource, source, stat: after, validation };
} finally {
await handle.close();
}
}
export async function loadTheme(themeDir) {
const requestedRoot = themeDir ?? path.join(root, "assets");
const configPath = path.join(requestedRoot, "theme.json");
let assetsRoot;
let canonicalConfigPath;
try {
[assetsRoot, canonicalConfigPath] = await Promise.all([
fs.realpath(requestedRoot),
fs.realpath(configPath),
]);
} catch (error) {
if (themeDir && error.code === "ENOENT") {
throw new Error(`Explicit theme directory is missing theme.json: ${configPath}`);
}
throw error;
}
assertContainedPath(assetsRoot, canonicalConfigPath, "Theme config");
let config;
try {
config = await fs.readFile(canonicalConfigPath, "utf8");
} catch (error) {
if (themeDir && error.code === "ENOENT") {
throw new Error(`Explicit theme directory is missing theme.json: ${configPath}`);
}
throw error;
}
const raw = JSON.parse(config);
if (raw.schemaVersion !== 1 || typeof raw.image !== "string" || !raw.image) {
throw new Error(`${configPath} has an unsupported schema or image field`);
}
if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(raw.image)) {
throw new Error(`${configPath} has an invalid image field`);
}
if (path.basename(raw.image) !== raw.image) throw new Error("Theme image must stay inside its theme directory");
const choice = (value, name, choices) => {
if (value === undefined) return undefined;
if (typeof value !== "string" || !choices.includes(value)) {
throw new Error(`${configPath} has an invalid ${name} field`);
}
return value;
};
const unit = (value, name) => {
if (value === undefined) return undefined;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
throw new Error(`${configPath} has an invalid ${name} field`);
}
return value;
};
const rawColors = raw.colors && typeof raw.colors === "object" && !Array.isArray(raw.colors)
? raw.colors : null;
const colorKeys = [
"background", "panel", "panelAlt", "accent", "accentAlt", "secondary",
"highlight", "text", "muted", "line",
];
const appearance = choice(raw.appearance, "appearance", ["auto", "light", "dark"]);
if (raw.art !== undefined && (!raw.art || typeof raw.art !== "object" || Array.isArray(raw.art))) {
throw new Error(`${configPath} has an invalid art field`);
}
const rawArt = raw.art || {};
const art = {
focusX: unit(rawArt.focusX, "art.focusX"),
focusY: unit(rawArt.focusY, "art.focusY"),
safeArea: choice(rawArt.safeArea, "art.safeArea", ["auto", "left", "right", "center", "none"]),
taskMode: choice(rawArt.taskMode, "art.taskMode", ["auto", "ambient", "banner", "full", "off"]),
};
const theme = {
schemaVersion: 1,
id: normalizeThemeText(raw.id, "custom", 80, "id", configPath),
name: normalizeThemeText(raw.name, "Codex Dream Skin", 80, "name", configPath),
brandSubtitle: normalizeThemeText(raw.brandSubtitle, "CODEX DREAM SKIN", 120, "brandSubtitle", configPath),
tagline: normalizeThemeText(raw.tagline, "Make something wonderful.", 120, "tagline", configPath),
projectPrefix: normalizeThemeText(raw.projectPrefix, "选择项目 · ", 120, "projectPrefix", configPath),
projectLabel: normalizeThemeText(raw.projectLabel, "◉ 选择项目", 120, "projectLabel", configPath),
statusText: normalizeThemeText(raw.statusText, "DREAM SKIN ONLINE", 120, "statusText", configPath),
quote: normalizeThemeText(raw.quote, "MAKE SOMETHING WONDERFUL", 120, "quote", configPath),
image: raw.image,
colorMode: rawColors ? "explicit" : "auto",
explicitColorKeys: rawColors ? colorKeys.filter((key) => Object.hasOwn(rawColors, key)) : [],
colors: {
background: normalizeThemeColor(rawColors?.background, "#071116"),
panel: normalizeThemeColor(rawColors?.panel, "#0b1a20"),
panelAlt: normalizeThemeColor(rawColors?.panelAlt, "#10272c"),
accent: normalizeThemeColor(rawColors?.accent, "#7cff46"),
accentAlt: normalizeThemeColor(rawColors?.accentAlt, "#b8ff3d"),
secondary: normalizeThemeColor(rawColors?.secondary, "#36d7e8"),
highlight: normalizeThemeColor(rawColors?.highlight, "#642a8c"),
text: normalizeThemeColor(rawColors?.text, "#e9fff1"),
muted: normalizeThemeColor(rawColors?.muted, "#9ebdb3"),
line: normalizeThemeColor(rawColors?.line, "rgba(124, 255, 70, .28)"),
},
};
if (appearance !== undefined) theme.appearance = appearance;
if (Object.values(art).some((value) => value !== undefined)) {
theme.art = Object.fromEntries(Object.entries(art).filter(([, value]) => value !== undefined));
}
const requestedImagePath = path.join(assetsRoot, theme.image);
let imagePath;
try {
imagePath = await fs.realpath(requestedImagePath);
} catch (error) {
if (error.code === "ENOENT") throw new Error(`Theme image is missing: ${requestedImagePath}`);
throw error;
}
assertContainedPath(assetsRoot, imagePath, "Theme image");
const imageStat = await fs.stat(imagePath);
const extension = path.extname(theme.image).toLowerCase();
if (![".png", ".jpg", ".jpeg", ".webp"].includes(extension)) {
throw new Error(`Unsupported theme image format: ${extension || "missing"}`);
}
let imageHandle;
try {
imageHandle = await fs.open(imagePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
} catch (error) {
if (error.code === "ELOOP") throw new Error("Theme image changed into a symbolic link while loading");
throw error;
}
try {
const openedStat = await imageHandle.stat();
if (
!imageStat.isFile()
|| !openedStat.isFile()
|| imageStat.dev !== openedStat.dev
|| imageStat.ino !== openedStat.ino
|| openedStat.size < 1
|| openedStat.size > MAX_ART_BYTES
) {
throw new Error(`Theme image must be a stable non-empty file no larger than ${MAX_ART_BYTES} bytes`);
}
const art = await imageHandle.readFile();
if (art.length < 1 || art.length > MAX_ART_BYTES) {
throw new Error(`Theme image must be a non-empty file no larger than ${MAX_ART_BYTES} bytes`);
}
const safeCss = await loadSafeCss(assetsRoot);
return {
art,
assetsRoot,
extension,
imagePath,
safeCss: safeCss?.source ?? "",
safeCssRuntime: safeCss?.runtimeSource ?? "",
safeCssPath: safeCss?.path ?? null,
safeCssStatus: safeCss ? "validated" : "none",
theme,
};
} finally {
await imageHandle.close();
}
}
async function loadStaticPayloadAssets() {
const cacheHit = Boolean(staticPayloadAssets);
if (!staticPayloadAssets) {
staticPayloadAssets = Promise.all([
fs.readFile(path.join(root, "assets", "dream-skin.css"), "utf8"),
fs.readFile(path.join(root, "assets", "renderer-inject.js"), "utf8"),
]).catch((error) => {
staticPayloadAssets = null;
throw error;
});
}
const [css, template] = await staticPayloadAssets;
return { css, template, cacheHit };
}
function invalidateStaticPayloadAssets() {
staticPayloadAssets = null;
}
export async function loadPayload(themeDir) {
const startedAt = performance.now();
const [staticAssets, loaded] = await Promise.all([
loadStaticPayloadAssets(),
loadTheme(themeDir),
]);
const { css, template } = staticAssets;
const { art, extension, safeCssRuntime, safeCssStatus, theme } = loaded;
const combinedCss = safeCssRuntime ? `${css}\n${safeCssRuntime}\n` : css;
const styleRevision = createHash("sha256").update(combinedCss).digest("hex").slice(0, 20);
const artMetadata = readImageMetadata(art, extension);
if (!artMetadata) {
throw new Error("Theme image metadata is invalid or exceeds the 16384px / 50MP safety limit");
}
const artKey = createHash("sha256").update(art).digest("hex").slice(0, 20);
theme.artMetadata = artMetadata;
theme.artKey = artKey;
const mime = extension === ".jpg" || extension === ".jpeg" ? "image/jpeg"
: extension === ".webp" ? "image/webp" : "image/png";
const artDataUrl = `data:${mime};base64,${art.toString("base64")}`;
const revision = createHash("sha256")
.update(SKIN_VERSION)
.update(combinedCss)
.update(template)
.update(JSON.stringify(theme))
.digest("hex")
.slice(0, 20);
// Every replacement value must be supplied as a function. A plain string
// replacement would still interpret `$$`, `$&`, `` $` `` and `$'` inside the
// JSON, so a theme name that legitimately contains `$` could silently corrupt
// or truncate the payload. Function replacements are inserted verbatim.
const payload = template
.replace("__DREAM_SKIN_CSS_JSON__", () => JSON.stringify(combinedCss))
.replace("__DREAM_SKIN_ART_JSON__", () => JSON.stringify(artDataUrl))
.replace("__DREAM_SKIN_THEME_JSON__", () => JSON.stringify(theme))
.replace("__DREAM_SKIN_VERSION_JSON__", () => JSON.stringify(SKIN_VERSION))
.replace("__DREAM_SKIN_STYLE_REVISION_JSON__", () => JSON.stringify(styleRevision))
.replace("__DREAM_SKIN_PAYLOAD_REVISION_JSON__", () => JSON.stringify(revision));
assertPayloadIntegrity(payload);
return {
imageBytes: art.length,
payload,
revision,
safeCssStatus,
theme,
timings: {
buildMs: Number((performance.now() - startedAt).toFixed(3)),
staticCacheHit: staticAssets.cacheHit,
},
};
}
// Fail closed before a payload can reach the renderer. Theme display fields are
// attacker-influenced text, so template substitution is verified structurally
// instead of trusting any single sanitiser:
// 1. no placeholder token may survive substitution;
// 2. the payload must still parse as the standalone expression that
// Runtime.evaluate would receive.
// The second assertion is deliberately generic: it catches any corruption of
// the template, not only the `$` replacement patterns that motivated it.
// `new Script` compiles without running the payload, so nothing executes here.
export function assertPayloadIntegrity(payload) {
if (/__DREAM_SKIN_[A-Z0-9_]+_JSON__/.test(payload)) {
throw new Error("Payload placeholders were not fully replaced");
}
try {
new Script(payload, { filename: "dream-skin-payload.js" });
} catch (error) {
throw new Error(`Payload is not a parsable renderer script: ${error.message}`);
}
return true;
}
async function applyToSession(session, payload) {
return session.evaluate(payload);
}
function nextOperationToken() {
operationSequence += 1;
return `${process.pid}:${Date.now()}:${operationSequence}`;
}
function operationUiExpression(action, token, state = "loading", message = "") {
const config = { action, token, state, message };
return `(() => {
const config = ${JSON.stringify(config)};
const hostId = ${JSON.stringify(OPERATION_UI_HOST_ID)};
const registryKey = ${JSON.stringify(OPERATION_UI_REGISTRY_KEY)};
const css = ${JSON.stringify(OPERATION_UI_CSS)};
const revealDelayMs = 16;
const minimumLoadingMs = 700;
const stateTtl = (value) => value === "loading" ? 180000
: value === "success" ? 1800 : value === "cancelled" ? 2400 : 6000;
const issuedAt = (value) => Number(String(value).split(":")[1]) || 0;
const positionInMainArea = (host) => {
const main = document.querySelector(${selectorLiteral("shell-main")}) ||
document.querySelector('[role="main"]') || document.documentElement;
const rect = main.getBoundingClientRect();
const top = Math.max(0, rect.top);
const left = Math.max(0, rect.left);
const width = Math.max(1, Math.min(innerWidth - left, rect.width || innerWidth));
const height = Math.max(1, Math.min(innerHeight - top, rect.height || innerHeight));
host.style.setProperty("--dream-skin-operation-top", String(top) + "px");
host.style.setProperty("--dream-skin-operation-left", String(left) + "px");
host.style.setProperty("--dream-skin-operation-width", String(width) + "px");
host.style.setProperty("--dream-skin-operation-height", String(height) + "px");
};
const clearTimer = (timer) => { if (timer) clearTimeout(timer); };
const removeHost = (expectedToken, force = false) => {
const host = document.getElementById(hostId);
const registry = window[registryKey];
if (!force && host?.dataset.operationToken !== expectedToken) return false;
if (!force && registry?.token && registry.token !== expectedToken) return false;
clearTimer(registry?.showTimer);
clearTimer(registry?.expiryTimer);
clearTimer(registry?.terminalTimer);
host?.remove();
if (force || registry?.token === expectedToken) delete window[registryKey];
return true;
};
if (config.action === "clear") {
removeHost("", true);
return { visible: false, cleared: true };
}
if (config.action === "hide") {
return { visible: false, removed: removeHost(config.token) };
}
let host = document.getElementById(hostId);
if (config.action === "show") {
const currentIssuedAt = Number(host?.dataset.operationIssuedAt || 0);
if (host?.dataset.operationToken !== config.token && currentIssuedAt > issuedAt(config.token)) {
return { visible: false, stale: true };
}
removeHost("", true);
host = document.createElement("div");
host.id = hostId;
host.dataset.operationToken = config.token;
host.dataset.operationIssuedAt = String(issuedAt(config.token));
host.dataset.state = config.state;
host.setAttribute("role", "status");
host.setAttribute("aria-live", "polite");
host.setAttribute("aria-atomic", "true");
const rgb = getComputedStyle(document.body || document.documentElement).backgroundColor.match(/\\d+(?:\\.\\d+)?/g)?.map(Number);
const light = rgb?.length >= 3
? (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) > 150
: matchMedia("(prefers-color-scheme: light)").matches;
host.dataset.tone = light ? "light" : "dark";
positionInMainArea(host);
const shadow = host.attachShadow({ mode: "open" });
const styleNode = document.createElement("style");
styleNode.textContent = css;
const statusNode = document.createElement("div");
statusNode.className = "status";
const indicator = document.createElement("span");
indicator.className = "indicator";
indicator.setAttribute("aria-hidden", "true");
const messageNode = document.createElement("span");
messageNode.className = "message";
messageNode.textContent = config.message;
statusNode.append(indicator, messageNode);
shadow.append(styleNode, statusNode);
document.documentElement.append(host);
const registry = {
token: config.token,
startedAt: Date.now(),
showTimer: null,
expiryTimer: null,
terminalTimer: null,
};
registry.showTimer = setTimeout(() => {
const current = document.getElementById(hostId);
if (current?.dataset.operationToken === config.token) current.dataset.visible = "true";
}, revealDelayMs);
registry.expiryTimer = setTimeout(() => removeHost(config.token), stateTtl(config.state));
window[registryKey] = registry;
return { visible: true, state: config.state };
}
if (!host || host.dataset.operationToken !== config.token) {
return { visible: false, stale: true };
}
const registry = window[registryKey];
clearTimer(registry?.terminalTimer);
clearTimer(registry?.expiryTimer);
positionInMainArea(host);
const terminal = config.state === "success" || config.state === "error" || config.state === "cancelled";
const remainingLoadingMs = terminal && host.dataset.state === "loading" && registry?.startedAt
? Math.max(0, registry.startedAt + minimumLoadingMs - Date.now())
: 0;
if (remainingLoadingMs > 0 && registry?.token === config.token) {
registry.terminalTimer = setTimeout(() => {
const current = document.getElementById(hostId);
const currentRegistry = window[registryKey];
if (current?.dataset.operationToken !== config.token || currentRegistry?.token !== config.token) return;
current.dataset.state = config.state;
current.dataset.visible = "true";
const currentMessage = current.shadowRoot?.querySelector(".message");
if (currentMessage) currentMessage.textContent = config.message;
clearTimer(currentRegistry.expiryTimer);
currentRegistry.expiryTimer = setTimeout(() => removeHost(config.token), stateTtl(config.state));
}, remainingLoadingMs);
return { visible: true, state: "loading", deferred: true };
}
host.dataset.state = config.state;
host.dataset.visible = "true";
const messageNode = host.shadowRoot?.querySelector(".message");
if (messageNode) messageNode.textContent = config.message;
if (registry?.token === config.token) {
registry.expiryTimer = setTimeout(() => removeHost(config.token), stateTtl(config.state));