The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 19:45 UTC
fix(desktop): browser panel can approve local HTTPS certificates (#24425)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Theo Browne <me@theo.li>
Julius Marminge committed
Nov 12, 2026 at 02:21 UTC
52273b7a04dbf482ea83f761479fe9c1573149c0
6 files changed
+679
-24
apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts
+1
@@ -33,6 +33,7 @@ const layerRejectedBeforeSession = Layer.succeed(
33
isPartition: () => false,
34
getSession: () => Effect.die("getSession must not be reached"),
35
clearCookies: () => Effect.die("clearCookies must not be reached"),
36
+ cookiesCleared: () => Effect.die("cookiesCleared must not be reached"),
37
clearCache: () => Effect.die("clearCache must not be reached"),
38
}),
39
);
apps/desktop/src/preview/BrowserSession.test.ts
+325
-5
@@ -1,8 +1,11 @@
1
import { assert, describe, it } from "@effect/vitest";
2
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
import * as NodeServices from "@effect/platform-node/NodeServices";
4
+import * as Deferred from "effect/Deferred";
5
import * as Effect from "effect/Effect";
6
+import * as FileSystem from "effect/FileSystem";
7
import * as Layer from "effect/Layer";
8
+import * as NodeEvents from "node:events";
9
import { beforeEach, vi } from "vite-plus/test";
10
11
const { fromPartition, sessions } = vi.hoisted(() => ({
@@ -12,6 +15,8 @@ const { fromPartition, sessions } = vi.hoisted(() => ({
15
{
16
readonly clearCache: ReturnType<typeof vi.fn>;
17
readonly clearStorageData: ReturnType<typeof vi.fn>;
18
+ readonly closeAllConnections: ReturnType<typeof vi.fn>;
19
+ readonly storagePath: string | null;
20
readonly getUserAgent: ReturnType<typeof vi.fn<() => string>>;
21
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
22
readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
@@ -21,44 +26,125 @@ const { fromPartition, sessions } = vi.hoisted(() => ({
26
>(),
27
}));
28
29
+const storage = vi.hoisted(() => ({ root: "" }));
30
+
31
const { fromWebContents } = vi.hoisted(() => ({
32
fromWebContents: vi.fn<(webContents: unknown) => unknown>(() => null),
33
}));
34
35
+const { appListeners } = vi.hoisted(() => ({
36
+ appListeners: new Map<string, (...args: unknown[]) => void>(),
37
+}));
38
+
39
vi.mock("electron", () => ({
40
+ app: {
41
+ on: (eventName: string, listener: (...args: unknown[]) => void) => {
42
+ appListeners.set(eventName, listener);
43
+ },
44
+ removeListener: (eventName: string) => {
45
+ appListeners.delete(eventName);
46
+ },
47
+ },
48
BrowserWindow: { fromWebContents },
49
session: {
50
fromPartition,
51
},
52
}));
53
54
+import * as ElectronApp from "../electron/ElectronApp.ts";
55
import * as ElectronDialog from "../electron/ElectronDialog.ts";
56
import * as BrowserSession from "./BrowserSession.ts";
57
38
-const { showMessageBox } = vi.hoisted(() => ({
58
+const { showMessageBox, showErrorBox } = vi.hoisted(() => ({
59
showMessageBox: vi.fn<
40
- (options: Electron.MessageBoxOptions, owner?: Electron.BrowserWindow) => number
60
+ (
61
+ options: Electron.MessageBoxOptions,
62
+ owner?: Electron.BrowserWindow,
63
+ ) => number | Promise<number>
64
>(() => 1),
65
+ showErrorBox: vi.fn<(title: string, content: string) => void>(),
66
}));
67
const layerDialog = Layer.succeed(ElectronDialog.ElectronDialog, {
68
pickFolder: () => Effect.die("unused"),
69
pickFiles: () => Effect.die("unused"),
70
showMessageBox: (options, owner) =>
47
- Effect.sync(() => ({ response: showMessageBox(options, owner), checkboxChecked: false })),
48
- showErrorBox: () => Effect.void,
71
+ Effect.promise(async () => ({
72
+ response: await showMessageBox(options, owner),
73
+ checkboxChecked: false,
74
+ })),
75
+ showErrorBox: (title, content) => Effect.sync(() => showErrorBox(title, content)),
76
});
77
const layer = BrowserSession.layer.pipe(
51
- Layer.provide(Layer.merge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), layerDialog)),
78
+ Layer.provide(
79
+ Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerDialog, ElectronApp.layer),
80
+ ),
81
);
82
83
+const selfSignedCertificate = {
84
+ fingerprint: "sha256/self-signed",
85
+ subjectName: "localhost",
86
+ issuerName: "localhost",
87
+ validStart: 1_735_776_000,
88
+ validExpiry: 1_807_056_000,
89
+} as Electron.Certificate;
90
+
91
+/** Raises Electron's `certificate-error` for a preview guest in `browserSession`. */
92
+const certificateError = (
93
+ browserSession: unknown,
94
+ input: {
95
+ readonly url: string;
96
+ readonly certificate?: Electron.Certificate;
97
+ readonly isMainFrame?: boolean;
98
+ },
99
+) => {
100
+ const listener = appListeners.get("certificate-error");
101
+ assert.isDefined(listener, "preview sessions should handle certificate errors");
102
+ const guest = Object.assign(new NodeEvents.EventEmitter(), {
103
+ session: browserSession,
104
+ hostWebContents: null,
105
+ isDestroyed: () => false,
106
+ });
107
+ const event = { preventDefault: vi.fn() };
108
+ const decision = Deferred.makeUnsafe<boolean>();
109
+ const callback = vi.fn((trusted: boolean) => {
110
+ Deferred.doneUnsafe(decision, Effect.succeed(trusted));
111
+ });
112
+ listener(
113
+ event,
114
+ guest,
115
+ input.url,
116
+ "net::ERR_CERT_AUTHORITY_INVALID",
117
+ input.certificate ?? selfSignedCertificate,
118
+ callback,
119
+ input.isMainFrame ?? true,
120
+ );
121
+ return { guest, event, callback, trusted: Deferred.await(decision) };
122
+};
123
+
124
+/** Answers the certificate prompt with its "Trust…" button. */
125
+const trustCertificateButton = (options: Electron.MessageBoxOptions): number => {
126
+ const index = (options.buttons ?? []).findIndex((label) => label.startsWith("Trust"));
127
+ assert.notStrictEqual(index, -1, "the certificate prompt should offer to trust");
128
+ return index;
129
+};
130
+
131
describe("BrowserSession", () => {
132
beforeEach(() => {
133
sessions.clear();
134
+ appListeners.clear();
135
+ storage.root = "";
136
+ showErrorBox.mockReset();
137
fromPartition.mockReset();
138
fromPartition.mockImplementation((partition: string) => {
139
const browserSession = {
140
clearCache: vi.fn(() => Promise.resolve()),
141
clearStorageData: vi.fn(() => Promise.resolve()),
142
+ closeAllConnections: vi.fn(() => Promise.resolve()),
143
+ // Like Electron, only a `persist:` partition has storage on disk.
144
+ storagePath:
145
+ storage.root !== "" && partition.startsWith("persist:")
146
+ ? `${storage.root}/Partitions/${partition}`
147
+ : null,
148
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
149
setPermissionRequestHandler: vi.fn(),
150
setPermissionCheckHandler: vi.fn(),
@@ -129,6 +215,8 @@ describe("BrowserSession", () => {
215
const browserSession = {
216
clearCache: vi.fn(() => Promise.resolve()),
217
clearStorageData: vi.fn(() => Promise.resolve()),
218
+ closeAllConnections: vi.fn(() => Promise.resolve()),
219
+ storagePath: null,
220
getUserAgent: vi.fn(() => userAgent),
221
setPermissionRequestHandler: vi.fn(),
222
setPermissionCheckHandler: vi.fn(),
@@ -333,4 +421,236 @@ describe("BrowserSession", () => {
421
assert.strictEqual(vi.mocked(other.clearStorageData).mock.calls.length, 0);
422
}).pipe(Effect.provide(layer)),
423
);
424
+
425
+ it.effect("asks before trusting an untrusted certificate and remembers the approval", () =>
426
+ Effect.gen(function* () {
427
+ const browserSessions = yield* BrowserSession.BrowserSession;
428
+ const partition = yield* browserSessions.getPartition("scope-a");
429
+ yield* browserSessions.getSession("scope-a");
430
+ const browserSession = sessions.get(partition);
431
+
432
+ showMessageBox.mockReset();
433
+ showMessageBox.mockImplementation(trustCertificateButton);
434
+ const first = certificateError(browserSession, { url: "https://localhost:18443/" });
435
+ assert.strictEqual(first.event.preventDefault.mock.calls.length, 1);
436
+ assert.isTrue(yield* first.trusted);
437
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
438
+
439
+ // The approval covers this origin, port, and certificate in this profile.
440
+ const again = certificateError(browserSession, { url: "https://localhost:18443/other" });
441
+ assert.isTrue(yield* again.trusted);
442
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
443
+ // Its sockets reach the same TLS endpoint, and cannot ask on their own.
444
+ const socket = certificateError(browserSession, {
445
+ url: "wss://localhost:18443/hmr",
446
+ isMainFrame: false,
447
+ });
448
+ assert.isTrue(yield* socket.trusted);
449
+ const otherSocket = certificateError(browserSession, {
450
+ url: "wss://localhost:18444/hmr",
451
+ isMainFrame: false,
452
+ });
453
+ assert.isFalse(yield* otherSocket.trusted);
454
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
455
+
456
+ showMessageBox.mockReset();
457
+ showMessageBox.mockReturnValue(1);
458
+ const otherPort = certificateError(browserSession, { url: "https://localhost:18444/" });
459
+ assert.isFalse(yield* otherPort.trusted);
460
+ const renewed = certificateError(browserSession, {
461
+ url: "https://localhost:18443/",
462
+ certificate: { ...selfSignedCertificate, fingerprint: "sha256/renewed" },
463
+ });
464
+ assert.isFalse(yield* renewed.trusted);
465
+ assert.strictEqual(showMessageBox.mock.calls.length, 2);
466
+
467
+ // A Session that is not a preview profile keeps Electron's denial.
468
+ const appSession = certificateError({}, { url: "https://localhost:18443/" });
469
+ assert.strictEqual(appSession.event.preventDefault.mock.calls.length, 0);
470
+ assert.strictEqual(appSession.callback.mock.calls.length, 0);
471
+ }).pipe(Effect.provide(layer)),
472
+ );
473
+
474
+ it.effect("revokes certificate approvals when cookies are cleared, not the cache", () =>
475
+ Effect.gen(function* () {
476
+ const browserSessions = yield* BrowserSession.BrowserSession;
477
+ const partition = yield* browserSessions.getPartition("scope-a");
478
+ yield* browserSessions.getSession("scope-a");
479
+ const browserSession = sessions.get(partition);
480
+ const url = "https://localhost:18443/";
481
+
482
+ showMessageBox.mockReset();
483
+ showMessageBox.mockImplementation(trustCertificateButton);
484
+ assert.isTrue(yield* certificateError(browserSession, { url }).trusted);
485
+
486
+ yield* browserSessions.clearCache([partition]);
487
+ assert.isTrue(yield* certificateError(browserSession, { url }).trusted);
488
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
489
+
490
+ // A failed storage clear still forgets the approvals the user asked to clear.
491
+ browserSession!.clearStorageData.mockRejectedValueOnce(new Error("disk busy"));
492
+ const failure = yield* browserSessions.clearCookies([partition]).pipe(Effect.flip);
493
+ assert.strictEqual(failure._tag, "BrowserSessionStorageClearError");
494
+ showMessageBox.mockReset();
495
+ showMessageBox.mockReturnValue(1);
496
+ assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
497
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
498
+ }).pipe(Effect.provide(layer)),
499
+ );
500
+
501
+ it.effect("remembers approvals across restarts, but not incognito ones", () =>
502
+ Effect.gen(function* () {
503
+ storage.root = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
504
+ const url = "https://localhost:18443/";
505
+ const approve = Effect.gen(function* () {
506
+ const browserSessions = yield* BrowserSession.BrowserSession;
507
+ const persistent = yield* browserSessions.getPartition("scope-a");
508
+ const incognito = yield* browserSessions.getPartition("scope-a", false);
509
+ yield* browserSessions.getSession("scope-a");
510
+ yield* browserSessions.getSession("scope-a", false);
511
+ showMessageBox.mockReset();
512
+ showMessageBox.mockImplementation(trustCertificateButton);
513
+ assert.isTrue(yield* certificateError(sessions.get(persistent), { url }).trusted);
514
+ assert.isTrue(yield* certificateError(sessions.get(incognito), { url }).trusted);
515
+ return { persistent, incognito };
516
+ });
517
+ const { persistent, incognito } = yield* approve.pipe(Effect.provide(layer));
518
+
519
+ // A restarted app gets fresh Session objects and reads approvals from disk.
520
+ sessions.clear();
521
+ appListeners.clear();
522
+ yield* Effect.gen(function* () {
523
+ const browserSessions = yield* BrowserSession.BrowserSession;
524
+ yield* browserSessions.getSession("scope-a");
525
+ yield* browserSessions.getSession("scope-a", false);
526
+ showMessageBox.mockReset();
527
+ showMessageBox.mockReturnValue(1);
528
+ assert.isTrue(yield* certificateError(sessions.get(persistent), { url }).trusted);
529
+ assert.strictEqual(showMessageBox.mock.calls.length, 0);
530
+ assert.isFalse(yield* certificateError(sessions.get(incognito), { url }).trusted);
531
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
532
+ }).pipe(Effect.provide(layer));
533
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
534
+ );
535
+
536
+ it.effect("an answer to a prompt opened before cookies were cleared does not trust", () =>
537
+ Effect.gen(function* () {
538
+ storage.root = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
539
+ const browserSessions = yield* BrowserSession.BrowserSession;
540
+ const partition = yield* browserSessions.getPartition("scope-a");
541
+ yield* browserSessions.getSession("scope-a");
542
+ const browserSession = sessions.get(partition);
543
+ const url = "https://localhost:18443/";
544
+
545
+ const asked = yield* Deferred.make<void>();
546
+ let answer = () => {};
547
+ const answered = new Promise<void>((resolve) => {
548
+ answer = resolve;
549
+ });
550
+ showMessageBox.mockReset();
551
+ showMessageBox.mockImplementation((options) => {
552
+ Deferred.doneUnsafe(asked, Effect.void);
553
+ return answered.then(() => trustCertificateButton(options));
554
+ });
555
+ const pending = certificateError(browserSession, { url });
556
+ yield* Deferred.await(asked);
557
+ yield* browserSessions.clearCookies([partition]);
558
+ answer();
559
+ assert.isFalse(yield* pending.trusted);
560
+
561
+ showMessageBox.mockReset();
562
+ showMessageBox.mockReturnValue(1);
563
+ assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
564
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
565
+ assert.isFalse(
566
+ yield* (yield* FileSystem.FileSystem).exists(
567
+ `${browserSession!.storagePath}/t3code-certificate-approvals.json`,
568
+ ),
569
+ );
570
+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))),
571
+ );
572
+
573
+ it.effect("a tab that closes or navigates away dismisses its certificate prompt", () =>
574
+ Effect.gen(function* () {
575
+ const browserSessions = yield* BrowserSession.BrowserSession;
576
+ const partition = yield* browserSessions.getPartition("scope-a");
577
+ yield* browserSessions.getSession("scope-a");
578
+ const browserSession = sessions.get(partition);
579
+ const url = "https://localhost:18443/";
580
+
581
+ for (const leave of [
582
+ (guest: NodeEvents.EventEmitter) =>
583
+ guest.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }),
584
+ (guest: NodeEvents.EventEmitter) => guest.emit("destroyed"),
585
+ ]) {
586
+ showMessageBox.mockReset();
587
+ // Answering "Trust" as the tab leaves must not approve the certificate.
588
+ showMessageBox.mockImplementation(
589
+ (options) =>
590
+ new Promise((resolve) =>
591
+ options.signal?.addEventListener("abort", () =>
592
+ resolve(trustCertificateButton(options)),
593
+ ),
594
+ ),
595
+ );
596
+ const pending = certificateError(browserSession, { url });
597
+ pending.guest.emit("did-start-navigation", { isMainFrame: true, isSameDocument: true });
598
+ leave(pending.guest);
599
+ assert.isFalse(yield* pending.trusted);
600
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
601
+ }
602
+ }).pipe(Effect.provide(layer)),
603
+ );
604
+
605
+ it.effect("does not trust a certificate whose approval cannot be saved", () =>
606
+ Effect.gen(function* () {
607
+ const fileSystem = yield* FileSystem.FileSystem;
608
+ // A file where the profile directory should be makes every write fail.
609
+ const root = yield* fileSystem.makeTempDirectoryScoped();
610
+ yield* fileSystem.writeFileString(`${root}/Partitions`, "");
611
+ storage.root = root;
612
+ const browserSessions = yield* BrowserSession.BrowserSession;
613
+ const partition = yield* browserSessions.getPartition("scope-a");
614
+ yield* browserSessions.getSession("scope-a");
615
+ const browserSession = sessions.get(partition);
616
+ const url = "https://localhost:18443/";
617
+
618
+ showMessageBox.mockReset();
619
+ showMessageBox.mockImplementation(trustCertificateButton);
620
+ assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
621
+ assert.strictEqual(showErrorBox.mock.calls.length, 1);
622
+ // Nothing was trusted for this run either, so the next visit asks again.
623
+ showMessageBox.mockReset();
624
+ showMessageBox.mockReturnValue(1);
625
+ assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
626
+ assert.strictEqual(showMessageBox.mock.calls.length, 1);
627
+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))),
628
+ );
629
+
630
+ it.effect("clearing cookies deletes a saved approval even when none are loaded", () =>
631
+ Effect.gen(function* () {
632
+ const fileSystem = yield* FileSystem.FileSystem;
633
+ storage.root = yield* fileSystem.makeTempDirectoryScoped();
634
+ const browserSessions = yield* BrowserSession.BrowserSession;
635
+ const partition = yield* browserSessions.getPartition("scope-a");
636
+ yield* browserSessions.getSession("scope-a");
637
+ const browserSession = sessions.get(partition);
638
+ // What a clear whose removal failed leaves behind: memory forgot, the file did not.
639
+ const file = `${browserSession!.storagePath}/t3code-certificate-approvals.json`;
640
+ yield* fileSystem.makeDirectory(browserSession!.storagePath!, { recursive: true });
641
+ yield* fileSystem.writeFileString(
642
+ file,
643
+ JSON.stringify([
644
+ {
645
+ origin: "https://localhost:18443",
646
+ fingerprint: selfSignedCertificate.fingerprint,
647
+ error: "net::ERR_CERT_AUTHORITY_INVALID",
648
+ },
649
+ ]),
650
+ );
651
+
652
+ yield* browserSessions.clearCookies([partition]);
653
+ assert.isFalse(yield* fileSystem.exists(file));
654
+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))),
655
+ );
656
});
apps/desktop/src/preview/BrowserSession.ts
+337
-15
@@ -1,14 +1,21 @@
1
-import type { Session, WebContents } from "electron";
1
+import * as HostProcess from "@t3tools/shared/HostProcess";
2
+import type { Certificate, Session, WebContents } from "electron";
3
import { BrowserWindow, session } from "electron";
4
import * as Context from "effect/Context";
5
+import * as DateTime from "effect/DateTime";
6
import * as Digest from "effect/crypto/Digest";
7
import * as Effect from "effect/Effect";
8
import * as Hex from "effect/encoding/Hex";
9
+import * as FileSystem from "effect/FileSystem";
10
import * as Layer from "effect/Layer";
11
+import * as Path from "effect/Path";
12
import * as PlatformError from "effect/PlatformError";
13
+import * as Result from "effect/Result";
14
import * as Schema from "effect/Schema";
15
+import * as Semaphore from "effect/Semaphore";
16
import * as SynchronizedRef from "effect/SynchronizedRef";
17
18
+import * as ElectronApp from "../electron/ElectronApp.ts";
19
import * as ElectronDialog from "../electron/ElectronDialog.ts";
20
21
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
@@ -73,6 +80,64 @@ const permissionOrigin = (rawUrl: string | undefined): string | null => {
80
}
81
};
82
83
+/**
84
+ * Certificate errors a user may accept for a preview page, with the reason the
85
+ * prompt shows. Every other error keeps Electron's denial.
86
+ */
87
+const OVERRIDABLE_CERTIFICATE_ERRORS: ReadonlyMap<string, string> = new Map([
88
+ ["net::ERR_CERT_AUTHORITY_INVALID", "No trusted authority issued this certificate."],
89
+ ["net::ERR_CERT_COMMON_NAME_INVALID", "This certificate is not for this address."],
90
+ ["net::ERR_CERT_DATE_INVALID", "This certificate has expired or is not valid yet."],
91
+]);
92
+
93
+/**
94
+ * A `wss:` socket reaches the same TLS endpoint as the page, so it shares the
95
+ * `https:` origin. It must: a socket is never a main frame, so it could not be
96
+ * approved on its own, and a page's dev-server socket would stay blocked.
97
+ */
98
+const certificateOrigin = (rawUrl: string): string | null => {
99
+ try {
100
+ const url = new URL(rawUrl);
101
+ return url.protocol === "https:" || url.protocol === "wss:" ? `https://${url.host}` : null;
102
+ } catch {
103
+ return null;
104
+ }
105
+};
106
+
107
+const CertificateApproval = Schema.Struct({
108
+ origin: Schema.String,
109
+ fingerprint: Schema.String,
110
+ error: Schema.String,
111
+});
112
+type CertificateApproval = typeof CertificateApproval.Type;
113
+const CertificateApprovalsJson = Schema.fromJsonString(Schema.Array(CertificateApproval));
114
+const decodeCertificateApprovals = Schema.decodeEffect(CertificateApprovalsJson);
115
+const encodeCertificateApprovals = Schema.encodeEffect(CertificateApprovalsJson);
116
+
117
+const certificateApprovalKey = ({ origin, fingerprint, error }: CertificateApproval): string =>
118
+ JSON.stringify([origin, fingerprint, error]);
119
+
120
+/** Kept beside the profile's cookies, so it lives and dies with them. */
121
+const CERTIFICATE_APPROVALS_FILE = "t3code-certificate-approvals.json";
122
+
123
+/** Server-chosen certificate names must not add lines or flood the prompt. */
124
+const promptCertificateName = (name: string): string => {
125
+ const flat = name.replace(/\s+/g, " ").trim();
126
+ return flat.length > 120 ? `${flat.slice(0, 120)}…` : flat;
127
+};
128
+
129
+const promptCertificateDate = (seconds: number): string =>
130
+ DateTime.formatIsoDateUtc(DateTime.makeUnsafe(seconds * 1000));
131
+
132
+/** The certificates a user accepted in one preview Session. */
133
+interface CertificateTrust {
134
+ /** `null` for an incognito Session, whose approvals end with the process. */
135
+ readonly file: string | null;
136
+ readonly approvals: Map<string, CertificateApproval>;
137
+ /** Bumped by each revocation, so an answer to an older prompt cannot restore trust. */
138
+ revocations: number;
139
+}
140
+
141
export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()(
142
"BrowserSessionPartitionDerivationError",
143
{
@@ -154,6 +219,10 @@ export class BrowserSession extends Context.Service<
219
readonly clearCookies: (
220
partitions?: ReadonlyArray<string>,
221
) => Effect.Effect<void, BrowserSessionStorageClearError>;
222
+ /** For cookies cleared outside `clearCookies`, such as over a tab's CDP session. */
223
+ readonly cookiesCleared: (
224
+ browserSession: Session,
225
+ ) => Effect.Effect<void, BrowserSessionStorageClearError>;
226
readonly clearCache: (
227
partitions?: ReadonlyArray<string>,
228
) => Effect.Effect<void, BrowserSessionCacheClearError>;
@@ -190,7 +259,11 @@ const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined
259
/** @public */
260
export const make = Effect.gen(function* BrowserSessionMake() {
261
const crypto = yield* Digest.Digest;
262
+ const electronApp = yield* ElectronApp.ElectronApp;
263
const electronDialog = yield* ElectronDialog.ElectronDialog;
264
+ const fileSystem = yield* FileSystem.FileSystem;
265
+ const path = yield* Path.Path;
266
+ const platform = yield* HostProcess.Platform;
267
const runFork = Effect.runForkWith(yield* Effect.context<never>());
268
// One prompt at a time, so a page cannot stack dialogs by looping a deep link.
269
let permissionPromptOpen = false;
@@ -257,6 +330,229 @@ export const make = Effect.gen(function* BrowserSessionMake() {
330
(answer) => callback(answer === true),
331
);
332
};
333
+
334
+ const certificateTrust = new WeakMap<Session, CertificateTrust>();
335
+ const writeCertificateApprovals = yield* Semaphore.make(1);
336
+ const loadCertificateTrust = Effect.fn("BrowserSession.loadCertificateTrust")(function* (
337
+ browserSession: Session,
338
+ ) {
339
+ const file =
340
+ browserSession.storagePath == null
341
+ ? null
342
+ : path.join(browserSession.storagePath, CERTIFICATE_APPROVALS_FILE);
343
+ const approvals: ReadonlyArray<CertificateApproval> =
344
+ file === null
345
+ ? []
346
+ : yield* fileSystem.readFileString(file).pipe(
347
+ Effect.flatMap(decodeCertificateApprovals),
348
+ Effect.catchTags({
349
+ PlatformError: (error) =>
350
+ error.reason._tag === "NotFound" ? Effect.succeed([]) : Effect.fail(error),
351
+ }),
352
+ Effect.catch((cause) =>
353
+ Effect.logWarning("Ignored saved certificate approvals.", { file, cause }).pipe(
354
+ Effect.as([]),
355
+ ),
356
+ ),
357
+ );
358
+ const trust: CertificateTrust = {
359
+ file,
360
+ approvals: new Map(approvals.map((approval) => [certificateApprovalKey(approval), approval])),
361
+ revocations: 0,
362
+ };
363
+ return trust;
364
+ });
365
+ const writeApprovalsFile = Effect.fn("BrowserSession.writeApprovalsFile")(function* (
366
+ file: string,
367
+ approvals: ReadonlyMap<string, CertificateApproval>,
368
+ ) {
369
+ if (approvals.size === 0) return yield* fileSystem.remove(file, { force: true });
370
+ yield* fileSystem.makeDirectory(path.dirname(file), { recursive: true });
371
+ yield* fileSystem.writeFileString(
372
+ file,
373
+ yield* encodeCertificateApprovals([...approvals.values()]),
374
+ );
375
+ });
376
+ /**
377
+ * Saved before it is trusted, so a failed write cannot leave an approval that
378
+ * silently ends at restart. Writes share one lock, so a slower write cannot
379
+ * restore stale data.
380
+ */
381
+ const rememberCertificate = Effect.fn("BrowserSession.rememberCertificate")(function* (
382
+ trust: CertificateTrust,
383
+ key: string,
384
+ approval: CertificateApproval,
385
+ revocations: number,
386
+ ) {
387
+ if (trust.revocations !== revocations) return false;
388
+ if (trust.file !== null) {
389
+ yield* writeApprovalsFile(trust.file, new Map(trust.approvals).set(key, approval));
390
+ // A revocation during the write queues its own rewrite behind this one.
391
+ if (trust.revocations !== revocations) return false;
392
+ }
393
+ trust.approvals.set(key, approval);
394
+ return true;
395
+ }, writeCertificateApprovals.withPermits(1));
396
+ /**
397
+ * Rewrites the file from memory. Clearing cookies runs this even when memory
398
+ * is already empty, so retrying after a failed removal still deletes the file.
399
+ */
400
+ const saveCertificateApprovals = Effect.fn("BrowserSession.saveCertificateApprovals")(function* (
401
+ trust: CertificateTrust,
402
+ ) {
403
+ if (trust.file !== null) yield* writeApprovalsFile(trust.file, trust.approvals);
404
+ }, writeCertificateApprovals.withPermits(1));
405
+
406
+ // One prompt at a time; tabs that hit the same certificate wait on it.
407
+ let certificatePrompt: {
408
+ readonly trust: CertificateTrust;
409
+ readonly key: string;
410
+ readonly callbacks: Array<(trusted: boolean) => void>;
411
+ } | null = null;
412
+ const confirmCertificate = (
413
+ contents: WebContents,
414
+ trust: CertificateTrust,
415
+ approval: CertificateApproval,
416
+ certificate: Certificate,
417
+ reason: string,
418
+ callback: (trusted: boolean) => void,
419
+ ): void => {
420
+ const key = certificateApprovalKey(approval);
421
+ if (certificatePrompt !== null) {
422
+ if (certificatePrompt.trust === trust && certificatePrompt.key === key) {
423
+ certificatePrompt.callbacks.push(callback);
424
+ } else {
425
+ callback(false);
426
+ }
427
+ return;
428
+ }
429
+ const prompt = { trust, key, callbacks: [callback] };
430
+ certificatePrompt = prompt;
431
+ // A prompt for a tab that closed or moved on would approve a page nobody is waiting for.
432
+ const dismiss = new AbortController();
433
+ const abandon = () => dismiss.abort();
434
+ const navigated = (
435
+ event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
436
+ ) => {
437
+ if (event.isMainFrame && !event.isSameDocument) abandon();
438
+ };
439
+ contents.once("destroyed", abandon);
440
+ contents.on("did-start-navigation", navigated);
441
+ const settle = (trusted: boolean) =>
442
+ Effect.sync(() => {
443
+ certificatePrompt = null;
444
+ if (!contents.isDestroyed()) {
445
+ contents.off("destroyed", abandon);
446
+ contents.off("did-start-navigation", navigated);
447
+ }
448
+ for (const waiter of prompt.callbacks) waiter(trusted);
449
+ });
450
+ const host = new URL(approval.origin).host;
451
+ const revocations = trust.revocations;
452
+ runFork(
453
+ electronDialog
454
+ .showMessageBox(
455
+ {
456
+ type: "warning",
457
+ buttons: ["Trust and Remember", "Cancel"],
458
+ defaultId: 1,
459
+ cancelId: 1,
460
+ signal: dismiss.signal,
461
+ message: `${host} has an untrusted certificate`,
462
+ detail: [
463
+ reason,
464
+ "",
465
+ `Issued to: ${promptCertificateName(certificate.subjectName)}`,
466
+ `Issued by: ${promptCertificateName(certificate.issuerName)}`,
467
+ `Valid: ${promptCertificateDate(certificate.validStart)} – ${promptCertificateDate(certificate.validExpiry)}`,
468
+ `Fingerprint: ${approval.fingerprint}`,
469
+ "",
470
+ "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.",
471
+ ].join("\n"),
472
+ },
473
+ // In the reporter's Windows test, a box owned by the host window
474
+ // blocked all mouse input, its own buttons included, until it closed.
475
+ platform === "win32" ? undefined : previewHostWindow(contents),
476
+ )
477
+ .pipe(
478
+ Effect.flatMap(({ response }) =>
479
+ response === 0 && !dismiss.signal.aborted
480
+ ? rememberCertificate(trust, key, approval, revocations).pipe(
481
+ Effect.catch((cause) =>
482
+ Effect.logWarning("Failed to save a certificate approval.", { cause }).pipe(
483
+ Effect.andThen(
484
+ electronDialog.showErrorBox(
485
+ `Could not trust the certificate for ${host}`,
486
+ "T3 Code could not save this approval, so the page stays blocked. Check that the disk is not full and its data folder is writable, then try again.",
487
+ ),
488
+ ),
489
+ Effect.as(false),
490
+ ),
491
+ ),
492
+ )
493
+ : Effect.succeed(false),
494
+ ),
495
+ Effect.orElseSucceed(() => false),
496
+ Effect.flatMap(settle),
497
+ Effect.onInterrupt(() => settle(false)),
498
+ ),
499
+ );
500
+ };
501
+ yield* electronApp.on(
502
+ "certificate-error",
503
+ (
504
+ event: Electron.Event,
505
+ contents: WebContents,
506
+ url: string,
507
+ error: string,
508
+ certificate: Certificate,
509
+ callback: (trusted: boolean) => void,
510
+ isMainFrame: boolean,
511
+ ) => {
512
+ if (contents.isDestroyed()) return;
513
+ // Sessions this service did not create keep Electron's denial.
514
+ const trust = certificateTrust.get(contents.session);
515
+ const origin = certificateOrigin(url);
516
+ const reason = OVERRIDABLE_CERTIFICATE_ERRORS.get(error);
517
+ if (trust === undefined || origin === null || reason === undefined) return;
518
+ const approval = { origin, fingerprint: certificate.fingerprint, error };
519
+ event.preventDefault();
520
+ if (trust.approvals.has(certificateApprovalKey(approval))) {
521
+ callback(true);
522
+ return;
523
+ }
524
+ // Only a page navigation asks; a subresource the user has not accepted stays blocked.
525
+ if (!isMainFrame) {
526
+ callback(false);
527
+ return;
528
+ }
529
+ confirmCertificate(contents, trust, approval, certificate, reason, callback);
530
+ },
531
+ );
532
+
533
+ /** Clearing a profile's cookies also forgets the certificates its user trusted. */
534
+ const revokeCertificates = Effect.fn("BrowserSession.revokeCertificates")(function* (
535
+ partition: string,
536
+ browserSession: Session,
537
+ ) {
538
+ const trust = certificateTrust.get(browserSession);
539
+ if (trust === undefined) return;
540
+ const hadApprovals = trust.approvals.size > 0;
541
+ trust.revocations += 1;
542
+ trust.approvals.clear();
543
+ const saved = yield* saveCertificateApprovals(trust).pipe(Effect.result);
544
+ // An open connection already passed its certificate check.
545
+ if (hadApprovals) {
546
+ yield* Effect.tryPromise({
547
+ try: () => browserSession.closeAllConnections(),
548
+ catch: (cause) => new BrowserSessionStorageClearError({ partition, cause }),
549
+ });
550
+ }
551
+ if (Result.isFailure(saved)) {
552
+ return yield* new BrowserSessionStorageClearError({ partition, cause: saved.failure });
553
+ }
554
+ });
555
+
556
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
557
558
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
@@ -361,9 +657,7 @@ export const make = Effect.gen(function* BrowserSessionMake() {
657
});
658
},
659
);
364
- const next = new Map(sessions);
365
- next.set(partition, browserSession);
366
- return [browserSession, next] as const;
660
+ return browserSession;
661
},
662
catch: (cause) =>
663
new BrowserSessionCreationError({
@@ -371,7 +665,18 @@ export const make = Effect.gen(function* BrowserSessionMake() {
665
partition,
666
cause,
667
}),
374
- });
668
+ }).pipe(
669
+ Effect.flatMap((browserSession) =>
670
+ loadCertificateTrust(browserSession).pipe(
671
+ Effect.map((trust) => {
672
+ certificateTrust.set(browserSession, trust);
673
+ const next = new Map(sessions);
674
+ next.set(partition, browserSession);
675
+ return [browserSession, next] as const;
676
+ }),
677
+ ),
678
+ ),
679
+ );
680
});
681
});
682
@@ -386,20 +691,37 @@ export const make = Effect.gen(function* BrowserSessionMake() {
691
yield* Effect.forEach(
692
selectSessions(sessions, partitions),
693
([partition, browserSession]) =>
389
- Effect.tryPromise({
390
- try: () =>
391
- browserSession.clearStorageData({
392
- storages: ["cookies", "localstorage", "indexdb", "serviceworkers", "cachestorage"],
393
- }),
394
- catch: (cause) =>
395
- new BrowserSessionStorageClearError({
396
- partition,
397
- cause,
398
- }),
694
+ Effect.gen(function* () {
695
+ const cleared = yield* Effect.tryPromise({
696
+ try: () =>
697
+ browserSession.clearStorageData({
698
+ storages: [
699
+ "cookies",
700
+ "localstorage",
701
+ "indexdb",
702
+ "serviceworkers",
703
+ "cachestorage",
704
+ ],
705
+ }),
706
+ catch: (cause) =>
707
+ new BrowserSessionStorageClearError({
708
+ partition,
709
+ cause,
710
+ }),
711
+ }).pipe(Effect.result);
712
+ // Approvals go even when the storage clear fails, since the user asked to forget them.
713
+ yield* revokeCertificates(partition, browserSession);
714
+ if (Result.isFailure(cleared)) return yield* cleared.failure;
715
}),
716
{ concurrency: "unbounded", discard: true },
717
);
718
}),
719
+ cookiesCleared: Effect.fn("BrowserSession.cookiesCleared")(function* (browserSession) {
720
+ const sessions = yield* SynchronizedRef.get(sessionsRef);
721
+ for (const [partition, candidate] of sessions) {
722
+ if (candidate === browserSession) yield* revokeCertificates(partition, browserSession);
723
+ }
724
+ }),
725
clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
726
const sessions = yield* SynchronizedRef.get(sessionsRef);
727
yield* Effect.forEach(
apps/desktop/src/preview/DesktopBrowserHost.ts
+8
-3
@@ -40,6 +40,8 @@ export interface DesktopBrowserTabKey {
40
export interface DesktopBrowserTabDebugger {
41
readonly webContents: Electron.WebContents;
42
readonly debugger: Electron.Debugger;
43
+ /** Runs after the server clears the tab's cookies, so state kept beside them goes too. */
44
+ readonly cookiesCleared?: () => Promise<void>;
45
}
46
47
const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`;
@@ -315,9 +317,12 @@ export const make = Effect.gen(function* () {
317
318
const relayFor = (tab: AttachedTab) => {
319
if (tab.relay) return tab.relay;
318
- const { webContents, debugger: debuggee } = tab.debuggee;
319
- const send = (method: string, params: Record<string, unknown>, sessionId?: string) =>
320
- sendPageCommand(webContents, debuggee, method, params, sessionId);
320
+ const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee;
321
+ const send = async (method: string, params: Record<string, unknown>, sessionId?: string) => {
322
+ const result = await sendPageCommand(webContents, debuggee, method, params, sessionId);
323
+ if (method === "Network.clearBrowserCookies") await cookiesCleared?.();
324
+ return result;
325
+ };
326
const detachedOwners = new Set<string>();
327
/** Viewers and recordings stream; the agent's own sessions never do. */
328
const streamingOwners = new Set<string>();
apps/desktop/src/preview/Manager.test.ts
+1
@@ -205,6 +205,7 @@ const layerBrowserSession = Layer.succeed(
205
isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
206
getSession: () => Effect.succeed(previewSession as unknown as Electron.Session),
207
clearCookies: () => Effect.void,
208
+ cookiesCleared: () => Effect.void,
209
clearCache: () => Effect.void,
210
}),
211
);
apps/desktop/src/preview/Manager.ts
+7
-1
@@ -563,9 +563,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
563
const random = yield* SecureRandom.SecureRandom;
564
const parentScope = yield* Scope.Scope;
565
const browserHost = yield* DesktopBrowserHost.DesktopBrowserHost;
566
+ const browserSession = yield* BrowserSession.BrowserSession;
567
const passkeys = yield* PreviewPasskeys.PreviewPasskeys;
568
const context = yield* Effect.context<never>();
569
const runFork = Effect.runForkWith(context);
570
+ const runPromise = Effect.runPromiseWith(context);
571
const resolvedArtifactDirectory = path.resolve(artifactDirectory);
572
573
let forwardedShortcuts: ReadonlyArray<PreviewForwardedShortcut> = [];
@@ -2472,7 +2474,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
2474
return;
2475
}
2476
if (afterAttach.serverTab) {
2475
- browserHost.attach(afterAttach.serverTab, { webContents: wc, debugger: control.debugger });
2477
+ browserHost.attach(afterAttach.serverTab, {
2478
+ webContents: wc,
2479
+ debugger: control.debugger,
2480
+ cookiesCleared: () => runPromise(browserSession.cookiesCleared(wc.session)),
2481
+ });
2482
// CDP cannot recover a failure that happened before it attached.
2483
const { navStatus } = afterAttach;
2484
if (navStatus.kind === "LoadFailed") {