-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathinjector.mjs
More file actions
1799 lines (1735 loc) · 75.8 KB
/
Copy pathinjector.mjs
File metadata and controls
1799 lines (1735 loc) · 75.8 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 } from "node:fs";
import { createHash } from "node:crypto";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { readImageMetadata } from "./image-metadata.mjs";
import {
normalizeThemeColor,
normalizeThemeText,
} from "../assets/theme-package-validator.mjs";
import { decodeAndValidateSafeCss } from "../assets/safe-css-validator.mjs";
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 MAX_ART_BYTES = 10 * 1024 * 1024;
const MAX_SAFE_CSS_BYTES = 256 * 1024;
const STRONG_THEME_AUDIT_MS = 30000;
const MIN_RENDERER_VIEWPORT_WIDTH = 320;
const MIN_RENDERER_VIEWPORT_HEIGHT = 240;
const VISIBLE_WINDOW_STATES = new Set(["normal", "maximized", "fullscreen"]);
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
const BROWSER_ID_PATTERN = /^[A-Za-z0-9._-]{1,200}$/;
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"]);
// Shared with macOS: in-renderer progress for pause/apply so both platforms feel the same.
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: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei 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;
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 operationSequence = 0;
class CdpIdentityMismatchError extends Error {}
function parseArgs(argv) {
const options = {
port: 9335,
mode: "watch",
timeoutMs: 30000,
screenshot: null,
reload: false,
browserId: null,
themeDir: path.join(root, "assets"),
pauseFile: 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 === "--timeout-ms") options.timeoutMs = Number(argv[++i]);
else if (arg === "--browser-id") options.browserId = argv[++i];
else if (arg === "--theme-dir") options.themeDir = path.resolve(argv[++i]);
else if (arg === "--pause-file") options.pauseFile = path.resolve(argv[++i]);
else if (arg === "--screenshot") options.screenshot = 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 if (arg === "--self-test") options.mode = "self-test";
else if (arg === "--check-payload") options.mode = "check-payload";
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.isInteger(options.timeoutMs) || options.timeoutMs < 250 || options.timeoutMs > 120000) {
throw new Error(`Invalid timeout: ${options.timeoutMs}`);
}
if (options.browserId !== null && !BROWSER_ID_PATTERN.test(options.browserId)) {
throw new Error(`Invalid browser ID: ${options.browserId}`);
}
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") {
if (!OPERATION_KINDS.has(options.operationKind)) {
throw new Error("Begin operation requires --operation-kind apply, pause, or switch");
}
if (!options.browserId) throw new Error("--browser-id is required in begin-operation mode");
}
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");
}
if (!options.browserId) throw new Error("--browser-id is required in finish-operation mode");
}
if (["watch", "once", "verify", "remove"].includes(options.mode) && !options.browserId) {
throw new Error(`--browser-id is required in ${options.mode} mode`);
}
return options;
}
function validatedDebuggerUrl(target, port) {
const url = new URL(target.webSocketDebuggerUrl);
const pathIsValid = /^\/devtools\/(?:page|browser)\/[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 endpoint shape");
}
return url.href;
}
function parseCdpMessage(data) {
try {
const message = JSON.parse(String(data));
return message && typeof message === "object" ? message : null;
} catch {
return null;
}
}
function browserIdFromVersion(version, port) {
const url = validatedDebuggerUrl(version, port);
const parsed = new URL(url);
const match = parsed.pathname.match(/^\/devtools\/browser\/([A-Za-z0-9._-]{1,200})$/);
if (!match || parsed.search || parsed.hash || !BROWSER_ID_PATTERN.test(match[1])) {
throw new Error("Rejected an invalid CDP browser identity URL");
}
return match[1];
}
function isValidCdpPageTarget(item, port) {
if (item?.type !== "page" || !item.url?.startsWith("app://") || typeof item.id !== "string" ||
!BROWSER_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) {
const message = parseCdpMessage(event.data);
if (!message) {
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) {
// Keep the numeric CDP code on the rejection: classifyNativeWindowError
// reads it directly instead of re-parsing the human-readable message,
// which Codex builds are free to reword at any time.
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) ?? []) listener(message.params ?? {});
}
on(method, listener) {
const listeners = this.listeners.get(method) ?? [];
listeners.push(listener);
this.listeners.set(method, listeners);
}
send(method, params = {}) {
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}`));
}, 10000);
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) {
const result = await this.send("Runtime.evaluate", {
expression,
awaitPromise: true,
returnByValue: true,
userGesture: false,
});
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;
}
}
class BrowserIdentityAnchor {
constructor(url) {
this.ws = new WebSocket(url);
this.closed = false;
this.ws.addEventListener("close", () => { this.closed = true; });
this.ws.addEventListener("error", () => {
this.closed = true;
try { this.ws.close(); } catch {}
});
}
async open() {
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
this.close();
reject(new Error("CDP browser identity WebSocket open timed out"));
}, 5000);
this.ws.addEventListener("open", () => { clearTimeout(timeout); resolve(); }, { once: true });
this.ws.addEventListener("error", () => {
clearTimeout(timeout);
reject(new Error("CDP browser identity WebSocket open failed"));
}, { once: true });
this.ws.addEventListener("close", () => {
clearTimeout(timeout);
reject(new Error("CDP browser identity WebSocket closed during startup"));
}, { once: true });
});
if (this.closed) throw new Error("CDP browser identity WebSocket is already closed");
return this;
}
close() {
if (!this.closed) {
try { this.ws.close(); } catch {}
}
this.closed = true;
}
}
async function fetchCdpJson(port, resource) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 2000);
try {
const response = await fetch(`http://127.0.0.1:${port}${resource}`, {
redirect: "error",
signal: controller.signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} finally {
clearTimeout(timeout);
}
}
async function listAppTargets(port, expectedBrowserId = null) {
const targets = await fetchCdpJson(port, "/json/list");
if (!Array.isArray(targets)) throw new Error("CDP target list is not an array");
if (expectedBrowserId) {
const version = await fetchCdpJson(port, "/json/version");
const actualBrowserId = browserIdFromVersion(version, port);
if (actualBrowserId !== expectedBrowserId) {
throw new CdpIdentityMismatchError(
`CDP browser identity changed from ${expectedBrowserId} to ${actualBrowserId}`,
);
}
}
return targets.filter((item) => isValidCdpPageTarget(item, port));
}
async function connectBrowserIdentityAnchor(port, expectedBrowserId) {
const version = await fetchCdpJson(port, "/json/version");
const actualBrowserId = browserIdFromVersion(version, port);
if (actualBrowserId !== expectedBrowserId) {
throw new CdpIdentityMismatchError(
`CDP browser identity changed from ${expectedBrowserId} to ${actualBrowserId}`,
);
}
return new BrowserIdentityAnchor(validatedDebuggerUrl(version, port)).open();
}
const THEME_CHOICES = {
appearance: new Set(["auto", "light", "dark"]),
safeArea: new Set(["auto", "left", "right", "center", "none"]),
taskMode: new Set(["auto", "ambient", "banner", "full", "off"]),
};
function normalizedUnit(value, name) {
if (value === null || value === undefined || value === "") return null;
const number = Number(value);
if (!Number.isFinite(number) || number < 0 || number > 1) {
throw new Error(`${name} must be null or a number between 0 and 1`);
}
return number;
}
function normalizedChoice(value, name, choices, fallback) {
if (value === null || value === undefined || value === "") return fallback;
if (!choices.has(value)) throw new Error(`${name} has an unsupported value: ${value}`);
return value;
}
function normalizedText(value, name, fallback, maxLength = 120) {
if (value === null || value === undefined || value === "") return fallback;
if (typeof value !== "string" || value.length > maxLength || /[\u0000-\u001f]/.test(value)) {
throw new Error(`${name} must be a short single-line string`);
}
return value;
}
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(themeRoot) {
const cssPath = path.join(themeRoot, "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 realThemeDir = await fs.realpath(themeDir);
const themePath = path.join(realThemeDir, "theme.json");
const themeText = await fs.readFile(themePath, "utf8");
const raw = JSON.parse(themeText);
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
throw new Error("Theme root must be an object");
}
const image = normalizedText(raw.image, "image", null, 240);
if (!image || path.isAbsolute(image)) throw new Error("Theme image must be a relative path");
const imagePath = path.resolve(realThemeDir, image);
const relativeImage = path.relative(realThemeDir, imagePath);
if (!relativeImage || relativeImage.startsWith("..") || path.isAbsolute(relativeImage)) {
throw new Error("Theme image must remain inside the selected theme directory");
}
const extension = path.extname(imagePath).toLowerCase();
if (![".png", ".jpg", ".jpeg", ".webp"].includes(extension)) {
throw new Error(`Unsupported theme image format: ${extension || "missing"}`);
}
const realImagePath = await fs.realpath(imagePath);
const realRelativeImage = path.relative(realThemeDir, realImagePath);
if (!realRelativeImage || realRelativeImage.startsWith("..") || path.isAbsolute(realRelativeImage)) {
throw new Error("Theme image cannot escape through a link or junction");
}
const art = raw.art && typeof raw.art === "object" && !Array.isArray(raw.art) ? raw.art : {};
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 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)"),
};
const theme = {
id: normalizeThemeText(raw.id, "custom", 80, "id", themePath),
name: normalizeThemeText(raw.name, "Codex Dream Skin", 80, "name", themePath),
brandSubtitle: normalizeThemeText(raw.brandSubtitle, "CODEX DREAM SKIN", 120, "brandSubtitle", themePath),
tagline: normalizeThemeText(raw.tagline, "Make something wonderful.", 120, "tagline", themePath),
projectPrefix: normalizeThemeText(raw.projectPrefix, "选择项目 · ", 120, "projectPrefix", themePath),
projectLabel: normalizeThemeText(raw.projectLabel, "◉ 选择项目", 120, "projectLabel", themePath),
statusText: normalizeThemeText(raw.statusText, "DREAM SKIN ONLINE", 120, "statusText", themePath),
quote: normalizeThemeText(raw.quote, "MAKE SOMETHING WONDERFUL", 120, "quote", themePath),
image,
appearance: normalizedChoice(raw.appearance, "appearance", THEME_CHOICES.appearance, "auto"),
art: {
focusX: normalizedUnit(art.focusX, "art.focusX"),
focusY: normalizedUnit(art.focusY, "art.focusY"),
safeArea: normalizedChoice(art.safeArea, "art.safeArea", THEME_CHOICES.safeArea, "auto"),
taskMode: normalizedChoice(art.taskMode, "art.taskMode", THEME_CHOICES.taskMode, "auto"),
},
colorMode: rawColors ? "explicit" : "auto",
explicitColorKeys: rawColors ? colorKeys.filter((key) => Object.hasOwn(rawColors, key)) : [],
colors,
};
const [themeStat, imageStat, safeCss] = await Promise.all([
fs.stat(themePath),
fs.stat(realImagePath),
loadSafeCss(realThemeDir),
]);
if (!imageStat.isFile()) throw new Error("Theme image is not a file");
if (imageStat.size < 1) throw new Error("Theme image cannot be empty");
if (imageStat.size > MAX_ART_BYTES) {
throw new Error(`Theme image exceeds the ${MAX_ART_BYTES / 1024 / 1024} MB limit`);
}
const imageBytes = await fs.readFile(realImagePath);
if (imageBytes.length < 1 || imageBytes.length > MAX_ART_BYTES) {
throw new Error(`Theme image must be between 1 byte and ${MAX_ART_BYTES / 1024 / 1024} MB`);
}
const artMetadata = readImageMetadata(imageBytes, extension);
if (!artMetadata) {
throw new Error("Theme image metadata is invalid or exceeds the 16384px / 50MP safety limit");
}
theme.artMetadata = artMetadata;
const fingerprint = createHash("sha256")
.update(themeText, "utf8")
.update("\0")
.update(imageBytes)
.update("\0")
.update(safeCss?.source ?? "")
.digest("hex");
return {
theme,
themePath,
imagePath: realImagePath,
imageBytes,
safeCss: safeCss?.source ?? "",
safeCssRuntime: safeCss?.runtimeSource ?? "",
safeCssPath: safeCss?.path ?? null,
safeCssStatus: safeCss ? "validated" : "none",
fingerprint,
sourceStamp: `${themeStat.size}:${themeStat.mtimeMs}:${imageStat.size}:${imageStat.mtimeMs}:` +
(safeCss ? `${safeCss.stat.size}:${safeCss.stat.mtimeMs}` : "none"),
};
}
export async function loadPayload(themeDir = path.join(root, "assets"), candidateTheme = null) {
const loadedTheme = candidateTheme ?? await loadTheme(themeDir);
const [css, template] = await Promise.all([
fs.readFile(path.join(root, "assets", "dream-skin.css"), "utf8"),
fs.readFile(path.join(root, "assets", "renderer-inject.js"), "utf8"),
]);
const combinedCss = loadedTheme.safeCssRuntime
? `${css}\n${loadedTheme.safeCssRuntime}\n` : css;
const extension = path.extname(loadedTheme.imagePath).toLowerCase();
const mime = extension === ".jpg" || extension === ".jpeg" ? "image/jpeg"
: extension === ".webp" ? "image/webp" : "image/png";
const artDataUrl = `data:${mime};base64,${loadedTheme.imageBytes.toString("base64")}`;
const styleRevision = createHash("sha256").update(combinedCss).digest("hex").slice(0, 20);
loadedTheme.theme.artKey = createHash("sha256")
.update(loadedTheme.imageBytes).digest("hex").slice(0, 20);
const revision = createHash("sha256")
.update(SKIN_VERSION)
.update(combinedCss)
.update(template)
.update(JSON.stringify(loadedTheme.theme))
.digest("hex")
.slice(0, 20);
// Every replacement uses a function so String.prototype.replace never
// interprets $$, $&, $` or $' inside the substituted JSON. Theme text is
// user-controlled (theme.json legitimately allows "$"), and a literal-string
// replacement would splice the template source back into the payload -- a
// stray "$`" produced a SyntaxError, while "$&"/"$$" silently corrupted the
// theme name.
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(loadedTheme.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));
// Defence in depth for every caller, not just --check-payload: a template
// splice leaves an unreplaced placeholder token behind and usually breaks the
// syntax outright, so refuse to hand a corrupted script to the renderer.
if (/__DREAM_SKIN_[A-Z0-9_]+_JSON__/.test(payload)) {
throw new Error("Payload placeholders were not fully replaced");
}
try {
// Compile-only: this parses the payload and discards the result. It never
// runs the renderer script here.
new Function(payload);
} catch (error) {
throw new Error(`Payload failed to parse as JavaScript: ${error.message}`);
}
const { imageBytes: _imageBytes, ...themeState } = loadedTheme;
return { ...themeState, payload, revision };
}
async function fileExists(filePath) {
if (!filePath) return false;
try {
return (await fs.stat(filePath)).isFile();
} catch (error) {
if (error?.code === "ENOENT") return false;
throw error;
}
}
async function readThemeSourceStamp(loadedTheme) {
const [themeStat, imageStat, cssStat] = await Promise.all([
fs.stat(loadedTheme.themePath),
fs.stat(loadedTheme.imagePath),
fs.stat(path.join(path.dirname(loadedTheme.themePath), "theme.css")).catch((error) => {
if (error.code === "ENOENT") return null;
throw error;
}),
]);
return `${themeStat.size}:${themeStat.mtimeMs}:${imageStat.size}:${imageStat.mtimeMs}:` +
(cssStat ? `${cssStat.size}:${cssStat.mtimeMs}` : "none");
}
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) {
try {
probe = await probeSession(session);
if (probe?.codex) return probe;
} catch {
// The renderer may be between documents while the early payload waits.
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
return probe;
}
async function connectTarget(target, port) {
return new CdpSession(target, port).open();
}
function unavailableNativeWindow(error) {
const message = String(error?.message ?? "");
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) answers -32000 "Browser window not found" for
// the app's real, focused, on-screen window -- verified live via CDP: the
// error is identical before and after actually activating the window, while
// documentVisibility correctly flips hidden -> visible. The domain exists but
// this build never resolves a window for our target, so -32000 is exactly as
// uninformative here as -32601 elsewhere. Treat both the same way and lean on
// documentVisible, which stays a hard requirement in windowPass below, as the
// real visibility signal. Matches macOS classifyNativeWindowError. See #256.
const windowNotFound = cdpCode === -32000
|| /\(-32000\)\s*$/.test(message)
|| /^browser window not found$/i.test(withoutCode)
|| /^no window with given target found$/i.test(withoutCode);
return {
pass: false,
bound: false,
unsupported: domainUnsupported || windowNotFound,
reason: domainUnsupported ? "browser-window-api-unavailable"
: windowNotFound ? "browser-window-not-found"
: "target-window-unavailable",
};
}
export async function inspectTargetWindow(session, targetId) {
if (typeof targetId !== "string" || !BROWSER_ID_PATTERN.test(targetId)) {
return { pass: false, bound: false, reason: "invalid-target-id" };
}
let binding;
try {
binding = await session.send("Browser.getWindowForTarget", { targetId });
} catch (error) {
return unavailableNativeWindow(error);
}
if (!Number.isInteger(binding?.windowId) || binding.windowId <= 0) {
return { pass: false, bound: false, reason: "invalid-window-binding" };
}
let latest;
try {
latest = await session.send("Browser.getWindowBounds", { windowId: binding.windowId });
} catch (error) {
return unavailableNativeWindow(error);
}
const bounds = { ...(binding.bounds ?? {}), ...(latest?.bounds ?? {}) };
const state = typeof bounds.windowState === "string" ? bounds.windowState : null;
const width = Number.isFinite(bounds.width) ? Number(bounds.width) : null;
const height = Number.isFinite(bounds.height) ? Number(bounds.height) : null;
const statePass = VISIBLE_WINDOW_STATES.has(state);
const boundsPass = width !== null && height !== null &&
width >= MIN_RENDERER_VIEWPORT_WIDTH && height >= MIN_RENDERER_VIEWPORT_HEIGHT;
return {
pass: statePass && boundsPass,
bound: true,
windowId: binding.windowId,
state,
width,
height,
reason: !statePass ? "window-not-visible" : !boundsPass ? "window-bounds-too-small" : null,
};
}
async function connectCodexTargets(port, timeoutMs, expectedBrowserId) {
const deadline = Date.now() + timeoutMs;
let lastError;
while (Date.now() < deadline) {
try {
const targets = await listAppTargets(port, expectedBrowserId);
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 Codex shell markers");
} catch (error) {
if (error instanceof CdpIdentityMismatchError) throw error;
lastError = error;
}
await new Promise((resolve) => setTimeout(resolve, 350));
}
throw new Error(`No verified Codex renderer on 127.0.0.1:${port}: ${lastError?.message ?? "timed out"}`);
}
async function applyToSession(session, payload) {
return session.evaluate(payload);
}
export function earlyPayloadFor(payload, revision) {
return `(() => {
const generationKey = "__CODEX_DREAM_SKIN_EARLY_GENERATION__";
const appliedKey = "__CODEX_DREAM_SKIN_EARLY_APPLIED__";
const generation = ${JSON.stringify(revision)};
window[generationKey] = generation;
let bootstrapTimer = null;
let timeout = null;
const stop = () => {
if (bootstrapTimer) clearInterval(bootstrapTimer);
bootstrapTimer = null;
if (timeout) clearTimeout(timeout);
timeout = null;
};
const hasCodexSurface = () => {
if (location.protocol !== "app:") return false;
const shell = document.querySelector(${selectorLiteral("shell-main")});
const sidebar = document.querySelector(${selectorLiteral("left-panel")});
const main = document.querySelector(${selectorLiteral("home-route")});
const settings = document.querySelector(${selectorLiteral("settings-panel")}) ||
document.querySelector(${selectorLiteral("appearance-radio")}) ||
document.querySelector(${stableTestidLiteral("theme-preview")});
const genericMain = document.querySelector('main, [role="main"]');
const genericInput = document.querySelector('textarea, [contenteditable="true"], [role="textbox"]');
const branded = Boolean(document.querySelector(
${stableTestidLiteral("app-shell-header-context-menu-surface")},
));
return Boolean((shell && sidebar) || settings || main ||
(genericMain && genericInput && branded));
};
const install = () => {
if (window[generationKey] !== generation) { stop(); return true; }
const root = document.documentElement;
// The shared renderer can install against documentElement before body is
// committed; requiring body here would create a visible unskinned first
// frame on cold navigation.
if (!root || !hasCodexSurface()) return false;
stop();
${payload};
window[appliedKey] = generation;
return true;
};
if (install()) return;
document.addEventListener?.("DOMContentLoaded", install, { once: true });
bootstrapTimer = setInterval(install, 250);
timeout = setTimeout(stop, 10000);
})()`;
}
async function registerEarlyPayload(session, payload, revision) {
const result = await session.send("Page.addScriptToEvaluateOnNewDocument", {
source: earlyPayloadFor(payload, revision),
});
return result.identifier ?? null;
}
async function removeEarlyPayload(session, identifier) {
if (!identifier || session.closed) return;
await session.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => {});
}
function nextOperationToken() {
operationSequence += 1;
return `${process.pid}:${Date.now()}:${operationSequence}`;
}
function operationKindMessage(kind) {
if (kind === "pause") return "正在暂停皮肤…";
if (kind === "switch") return "正在切换主题…";
return "正在应用皮肤…";
}
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("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(),