chatccc 0.2.183 → 0.2.185

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,299 @@
1
+ import WebSocket from "ws";
2
+
3
+ import { config } from "./config.ts";
4
+ import { probeChromeCdp, type ChromeCdpProbeStatus } from "./chrome-devtools-guard.ts";
5
+
6
+ const CDP_HOST = "127.0.0.1";
7
+ const DEFAULT_CDP_PORT = 15166;
8
+ const CDP_TIMEOUT_MS = 10_000;
9
+ const CHATGPT_URL = "https://chatgpt.com/";
10
+
11
+ type FetchLike = typeof fetch;
12
+
13
+ export type ChatGptSubscriptionCode =
14
+ | "ok"
15
+ | "chrome_cdp_disabled"
16
+ | "chrome_cdp_unreachable"
17
+ | "chrome_cdp_occupied"
18
+ | "chatgpt_page_missing"
19
+ | "chatgpt_session_missing"
20
+ | "chatgpt_subscription_failed";
21
+
22
+ export interface ChatGptSubscriptionResult {
23
+ ok: boolean;
24
+ code: ChatGptSubscriptionCode;
25
+ reason?: string;
26
+ chromeCdp: {
27
+ enabled: boolean;
28
+ port: number;
29
+ status: ChromeCdpProbeStatus | "skipped";
30
+ };
31
+ chatgpt?: {
32
+ sessionOk: boolean;
33
+ maskedEmail?: string;
34
+ sessionExpiresAt?: string;
35
+ };
36
+ subscription?: {
37
+ active: boolean;
38
+ plan: string | null;
39
+ expiresAt: string | null;
40
+ willRenew: boolean | null;
41
+ purchaseOriginPlatform: string | null;
42
+ remainingDays: number | null;
43
+ };
44
+ }
45
+
46
+ interface ChromeCdpPage {
47
+ id: string;
48
+ type: string;
49
+ title?: string;
50
+ url: string;
51
+ webSocketDebuggerUrl?: string;
52
+ }
53
+
54
+ interface BrowserProbeValue {
55
+ sessionStatus?: number;
56
+ sessionOk?: boolean;
57
+ hasAccessToken?: boolean;
58
+ maskedEmail?: string;
59
+ sessionExpires?: string;
60
+ account?: {
61
+ status: number;
62
+ ok: boolean;
63
+ entitlement: {
64
+ has_active_subscription?: unknown;
65
+ subscription_plan?: unknown;
66
+ expires_at?: unknown;
67
+ } | null;
68
+ last_active_subscription: {
69
+ will_renew?: unknown;
70
+ purchase_origin_platform?: unknown;
71
+ } | null;
72
+ detail?: unknown;
73
+ bodyPrefix?: string;
74
+ };
75
+ error?: string;
76
+ }
77
+
78
+ export interface ChatGptSubscriptionDeps {
79
+ fetchImpl?: FetchLike;
80
+ probeChromeCdpImpl?: typeof probeChromeCdp;
81
+ evaluateInPage?: (webSocketDebuggerUrl: string, expression: string) => Promise<unknown>;
82
+ now?: () => Date;
83
+ }
84
+
85
+ function normalizePort(value: unknown): number {
86
+ const port = Number(value);
87
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
88
+ }
89
+
90
+ function cdpBaseUrl(port: number): string {
91
+ return `http://${CDP_HOST}:${port}`;
92
+ }
93
+
94
+ function maskEmail(value: unknown): string | undefined {
95
+ if (typeof value !== "string" || !value.includes("@")) return undefined;
96
+ const [name, domain] = value.split("@");
97
+ if (!name || !domain) return undefined;
98
+ return `${name.slice(0, 2)}***@${domain}`;
99
+ }
100
+
101
+ function calculateRemainingDays(expiresAt: string | null, now: Date): number | null {
102
+ if (!expiresAt) return null;
103
+ const expires = new Date(expiresAt).getTime();
104
+ if (!Number.isFinite(expires)) return null;
105
+ return Math.max(0, Math.ceil((expires - now.getTime()) / 86_400_000));
106
+ }
107
+
108
+ async function fetchJson<T>(url: string, fetchImpl: FetchLike, init?: RequestInit): Promise<T> {
109
+ const response = await fetchImpl(url, init);
110
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
111
+ return await response.json() as T;
112
+ }
113
+
114
+ async function listCdpPages(port: number, fetchImpl: FetchLike): Promise<ChromeCdpPage[]> {
115
+ const pages = await fetchJson<unknown>(`${cdpBaseUrl(port)}/json/list`, fetchImpl);
116
+ return Array.isArray(pages)
117
+ ? pages.flatMap((raw): ChromeCdpPage[] => {
118
+ if (!raw || typeof raw !== "object") return [];
119
+ const page = raw as Partial<ChromeCdpPage>;
120
+ if (typeof page.id !== "string" || typeof page.type !== "string" || typeof page.url !== "string") return [];
121
+ return [{
122
+ id: page.id,
123
+ type: page.type,
124
+ title: typeof page.title === "string" ? page.title : undefined,
125
+ url: page.url,
126
+ webSocketDebuggerUrl: typeof page.webSocketDebuggerUrl === "string" ? page.webSocketDebuggerUrl : undefined,
127
+ }];
128
+ })
129
+ : [];
130
+ }
131
+
132
+ async function createChatGptPage(port: number, fetchImpl: FetchLike): Promise<ChromeCdpPage | null> {
133
+ const url = `${cdpBaseUrl(port)}/json/new?${encodeURIComponent(CHATGPT_URL)}`;
134
+ const response = await fetchImpl(url, { method: "PUT" });
135
+ if (!response.ok) return null;
136
+ const page = await response.json() as Partial<ChromeCdpPage>;
137
+ if (typeof page.id !== "string" || typeof page.webSocketDebuggerUrl !== "string") return null;
138
+ return {
139
+ id: page.id,
140
+ type: typeof page.type === "string" ? page.type : "page",
141
+ title: typeof page.title === "string" ? page.title : undefined,
142
+ url: typeof page.url === "string" ? page.url : CHATGPT_URL,
143
+ webSocketDebuggerUrl: page.webSocketDebuggerUrl,
144
+ };
145
+ }
146
+
147
+ async function closeCdpPage(port: number, pageId: string, fetchImpl: FetchLike): Promise<void> {
148
+ try {
149
+ await fetchImpl(`${cdpBaseUrl(port)}/json/close/${encodeURIComponent(pageId)}`);
150
+ } catch {
151
+ // Closing a temporary tab is best effort and must not change the query result.
152
+ }
153
+ }
154
+
155
+ function subscriptionProbeExpression(): string {
156
+ return `(async()=>{try{const sResp=await fetch('/api/auth/session',{credentials:'include',headers:{Accept:'application/json'}});const sText=await sResp.text();let s=null;try{s=JSON.parse(sText)}catch{}const token=s&&typeof s.accessToken==='string'?s.accessToken:'';const email=s&&s.user&&typeof s.user.email==='string'?s.user.email:'';let account=null;if(token){const r=await fetch('/backend-api/accounts/check/v4-2023-04-27?timezone_offset_min=-480',{credentials:'include',headers:{Accept:'application/json',Authorization:'Bearer '+token}});const text=await r.text();let data=null;try{data=JSON.parse(text)}catch{}const accounts=data&&data.accounts&&typeof data.accounts==='object'?data.accounts:null;const keys=accounts?Object.keys(accounts):[];const acc=accounts&&(accounts.default||accounts[keys[0]]);const ent=acc&&acc.entitlement;const last=acc&&acc.last_active_subscription;account={status:r.status,ok:r.ok,entitlement:ent?{has_active_subscription:ent.has_active_subscription,subscription_plan:ent.subscription_plan,expires_at:ent.expires_at}:null,last_active_subscription:last?{will_renew:last.will_renew,purchase_origin_platform:last.purchase_origin_platform}:null,detail:data&&data.detail?data.detail:undefined,bodyPrefix:data?undefined:text.slice(0,120)};}return {sessionStatus:sResp.status,sessionOk:sResp.ok,hasAccessToken:!!token,maskedEmail:(${maskEmail.toString()})(email),sessionExpires:s&&s.expires,account};}catch(e){return {error:String(e&&e.message||e)}}})()`;
157
+ }
158
+
159
+ async function evaluateInPage(webSocketDebuggerUrl: string, expression: string): Promise<unknown> {
160
+ return await new Promise((resolve, reject) => {
161
+ const ws = new WebSocket(webSocketDebuggerUrl);
162
+ const id = 1;
163
+ const timer = setTimeout(() => {
164
+ ws.close();
165
+ reject(new Error("CDP Runtime.evaluate timed out"));
166
+ }, CDP_TIMEOUT_MS);
167
+
168
+ ws.on("open", () => {
169
+ ws.send(JSON.stringify({
170
+ id,
171
+ method: "Runtime.evaluate",
172
+ params: { expression, awaitPromise: true, returnByValue: true },
173
+ }));
174
+ });
175
+ ws.on("message", (data) => {
176
+ const msg = JSON.parse(String(data)) as {
177
+ id?: number;
178
+ error?: unknown;
179
+ result?: { result?: { value?: unknown } };
180
+ };
181
+ if (msg.id !== id) return;
182
+ clearTimeout(timer);
183
+ ws.close();
184
+ if (msg.error) {
185
+ reject(new Error(JSON.stringify(msg.error)));
186
+ } else {
187
+ resolve(msg.result?.result?.value);
188
+ }
189
+ });
190
+ ws.on("error", (err) => {
191
+ clearTimeout(timer);
192
+ reject(err);
193
+ });
194
+ });
195
+ }
196
+
197
+ function failure(
198
+ code: Exclude<ChatGptSubscriptionCode, "ok">,
199
+ reason: string,
200
+ chromeCdp: ChatGptSubscriptionResult["chromeCdp"],
201
+ extra: Partial<ChatGptSubscriptionResult> = {},
202
+ ): ChatGptSubscriptionResult {
203
+ return { ok: false, code, reason, chromeCdp, ...extra };
204
+ }
205
+
206
+ export function isExpectedSubscriptionFailure(code: ChatGptSubscriptionCode): boolean {
207
+ return code !== "chatgpt_subscription_failed";
208
+ }
209
+
210
+ export async function getChatGptSubscriptionStatus(
211
+ deps: ChatGptSubscriptionDeps = {},
212
+ ): Promise<ChatGptSubscriptionResult> {
213
+ const cfg = config.chromeDevtools;
214
+ const port = normalizePort(cfg.port);
215
+ const baseChromeCdp = { enabled: cfg.enabled, port };
216
+ const fetchImpl = deps.fetchImpl ?? fetch;
217
+
218
+ if (!cfg.enabled) {
219
+ return failure("chrome_cdp_disabled", "Chrome CDP guard is disabled in ChatCCC config.", {
220
+ ...baseChromeCdp,
221
+ status: "skipped",
222
+ });
223
+ }
224
+
225
+ const probe = await (deps.probeChromeCdpImpl ?? probeChromeCdp)(port, { fetchImpl });
226
+ const chromeCdp = { ...baseChromeCdp, status: probe };
227
+ if (probe === "unreachable") {
228
+ return failure("chrome_cdp_unreachable", `Chrome CDP endpoint is unreachable on port ${port}.`, chromeCdp);
229
+ }
230
+ if (probe === "occupied") {
231
+ return failure("chrome_cdp_occupied", `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`, chromeCdp);
232
+ }
233
+
234
+ let temporaryPage: ChromeCdpPage | null = null;
235
+ try {
236
+ const existingPages = await listCdpPages(port, fetchImpl);
237
+ let page = existingPages.find((p) =>
238
+ p.type === "page" &&
239
+ p.webSocketDebuggerUrl &&
240
+ p.url.startsWith(CHATGPT_URL)
241
+ ) ?? null;
242
+ if (!page) {
243
+ temporaryPage = await createChatGptPage(port, fetchImpl);
244
+ page = temporaryPage;
245
+ }
246
+ if (!page?.webSocketDebuggerUrl) {
247
+ return failure("chatgpt_page_missing", "No usable chatgpt.com page is available from Chrome CDP.", chromeCdp);
248
+ }
249
+
250
+ const raw = await (deps.evaluateInPage ?? evaluateInPage)(page.webSocketDebuggerUrl, subscriptionProbeExpression()) as BrowserProbeValue;
251
+ if (!raw || typeof raw !== "object") {
252
+ return failure("chatgpt_subscription_failed", "Chrome CDP returned an empty subscription probe result.", chromeCdp);
253
+ }
254
+ if (raw.error) {
255
+ return failure("chatgpt_subscription_failed", raw.error, chromeCdp);
256
+ }
257
+
258
+ const chatgpt = {
259
+ sessionOk: raw.sessionOk === true,
260
+ maskedEmail: raw.maskedEmail || undefined,
261
+ sessionExpiresAt: typeof raw.sessionExpires === "string" ? raw.sessionExpires : undefined,
262
+ };
263
+ if (!raw.hasAccessToken) {
264
+ return failure("chatgpt_session_missing", "ChatGPT browser session has no access token.", chromeCdp, { chatgpt });
265
+ }
266
+ if (!raw.account?.ok || !raw.account.entitlement) {
267
+ return failure(
268
+ "chatgpt_subscription_failed",
269
+ `ChatGPT account check failed${raw.account?.status ? ` with HTTP ${raw.account.status}` : ""}.`,
270
+ chromeCdp,
271
+ { chatgpt },
272
+ );
273
+ }
274
+
275
+ const entitlement = raw.account.entitlement;
276
+ const last = raw.account.last_active_subscription;
277
+ const expiresAt = typeof entitlement.expires_at === "string" ? entitlement.expires_at : null;
278
+ return {
279
+ ok: true,
280
+ code: "ok",
281
+ chromeCdp,
282
+ chatgpt,
283
+ subscription: {
284
+ active: entitlement.has_active_subscription === true,
285
+ plan: typeof entitlement.subscription_plan === "string" ? entitlement.subscription_plan : null,
286
+ expiresAt,
287
+ willRenew: typeof last?.will_renew === "boolean" ? last.will_renew : null,
288
+ purchaseOriginPlatform: typeof last?.purchase_origin_platform === "string" ? last.purchase_origin_platform : null,
289
+ remainingDays: calculateRemainingDays(expiresAt, deps.now?.() ?? new Date()),
290
+ },
291
+ };
292
+ } catch (err) {
293
+ return failure("chatgpt_subscription_failed", (err as Error).message, chromeCdp);
294
+ } finally {
295
+ if (temporaryPage) {
296
+ await closeCdpPage(port, temporaryPage.id, fetchImpl);
297
+ }
298
+ }
299
+ }
@@ -0,0 +1,242 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { existsSync, mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ import { appendStartupTrace } from "./shared.ts";
6
+ import { config, ts, USER_DATA_DIR, type ChromeDevtoolsConfig } from "./config.ts";
7
+
8
+ const CDP_HOST = "127.0.0.1";
9
+ const DEFAULT_CDP_PORT = 15166;
10
+ const HEALTH_TIMEOUT_MS = 3000;
11
+ const START_VERIFY_ATTEMPTS = 10;
12
+ const START_VERIFY_DELAY_MS = 500;
13
+ const GUARD_INTERVAL_MS = 60_000;
14
+
15
+ type FetchLike = typeof fetch;
16
+
17
+ export interface ChromeDevtoolsGuardDeps {
18
+ fetchImpl?: FetchLike;
19
+ spawnImpl?: typeof spawn;
20
+ existsSyncImpl?: typeof existsSync;
21
+ mkdirSyncImpl?: typeof mkdirSync;
22
+ platform?: NodeJS.Platform;
23
+ env?: NodeJS.ProcessEnv;
24
+ log?: (message: string) => void;
25
+ }
26
+
27
+ export interface ChromeCdpEnsureResult {
28
+ ok: boolean;
29
+ started: boolean;
30
+ port: number;
31
+ error?: string;
32
+ }
33
+
34
+ export type ChromeCdpProbeStatus = "healthy" | "occupied" | "unreachable";
35
+
36
+ let guardTimer: ReturnType<typeof setInterval> | null = null;
37
+ let ensureInFlight: Promise<ChromeCdpEnsureResult> | null = null;
38
+
39
+ function normalizePort(value: unknown): number {
40
+ const port = Number(value);
41
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : DEFAULT_CDP_PORT;
42
+ }
43
+
44
+ function chromeCandidates(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string[] {
45
+ if (platform === "win32") {
46
+ return [
47
+ env.ProgramFiles ? join(env.ProgramFiles, "Google", "Chrome", "Application", "chrome.exe") : "",
48
+ env["ProgramFiles(x86)"] ? join(env["ProgramFiles(x86)"]!, "Google", "Chrome", "Application", "chrome.exe") : "",
49
+ env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe") : "",
50
+ ].filter(Boolean);
51
+ }
52
+
53
+ if (platform === "darwin") {
54
+ return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
55
+ }
56
+
57
+ return [
58
+ "/usr/bin/google-chrome",
59
+ "/usr/bin/google-chrome-stable",
60
+ "/usr/bin/chromium",
61
+ "/usr/bin/chromium-browser",
62
+ ];
63
+ }
64
+
65
+ export function resolveChromeExecutable(
66
+ chromePath: string | undefined,
67
+ deps: Pick<ChromeDevtoolsGuardDeps, "existsSyncImpl" | "platform" | "env"> = {},
68
+ ): string | null {
69
+ const exists = deps.existsSyncImpl ?? existsSync;
70
+ const explicit = chromePath?.trim();
71
+ if (explicit) return exists(explicit) ? explicit : null;
72
+
73
+ for (const candidate of chromeCandidates(deps.platform ?? process.platform, deps.env ?? process.env)) {
74
+ if (exists(candidate)) return candidate;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ export function resolveChromeUserDataDir(port: number, env: NodeJS.ProcessEnv = process.env): string {
80
+ const root = env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "chatccc") : join(USER_DATA_DIR, "chrome-cdp");
81
+ return join(root, `chrome-cdp-${port}`);
82
+ }
83
+
84
+ async function fetchWithTimeout(url: string, fetchImpl: FetchLike, timeoutMs: number): Promise<Response> {
85
+ const controller = new AbortController();
86
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
87
+ try {
88
+ return await fetchImpl(url, { signal: controller.signal });
89
+ } finally {
90
+ clearTimeout(timer);
91
+ }
92
+ }
93
+
94
+ export async function probeChromeCdp(
95
+ port: number,
96
+ deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
97
+ ): Promise<ChromeCdpProbeStatus> {
98
+ const normalizedPort = normalizePort(port);
99
+ try {
100
+ const response = await fetchWithTimeout(
101
+ `http://${CDP_HOST}:${normalizedPort}/json/version`,
102
+ deps.fetchImpl ?? fetch,
103
+ HEALTH_TIMEOUT_MS,
104
+ );
105
+ if (!response.ok) return "occupied";
106
+ const data = await response.json() as Record<string, unknown>;
107
+ return typeof data.Browser === "string" || typeof data.webSocketDebuggerUrl === "string"
108
+ ? "healthy"
109
+ : "occupied";
110
+ } catch {
111
+ return "unreachable";
112
+ }
113
+ }
114
+
115
+ export async function isChromeCdpHealthy(
116
+ port: number,
117
+ deps: Pick<ChromeDevtoolsGuardDeps, "fetchImpl"> = {},
118
+ ): Promise<boolean> {
119
+ return (await probeChromeCdp(port, deps)) === "healthy";
120
+ }
121
+
122
+ function startChromeForCdp(
123
+ cfg: ChromeDevtoolsConfig,
124
+ deps: ChromeDevtoolsGuardDeps = {},
125
+ ): { ok: true; child: ChildProcess } | { ok: false; error: string } {
126
+ const port = normalizePort(cfg.port);
127
+ const chromeExe = resolveChromeExecutable(cfg.chromePath, deps);
128
+ if (!chromeExe) {
129
+ return { ok: false, error: "Cannot find chrome executable. Configure chromeDevtools.chromePath." };
130
+ }
131
+
132
+ const userDataDir = resolveChromeUserDataDir(port, deps.env ?? process.env);
133
+ try {
134
+ (deps.mkdirSyncImpl ?? mkdirSync)(userDataDir, { recursive: true });
135
+ } catch (err) {
136
+ return { ok: false, error: `Cannot create Chrome user data dir: ${(err as Error).message}` };
137
+ }
138
+
139
+ const args = [
140
+ `--remote-debugging-address=${CDP_HOST}`,
141
+ `--remote-debugging-port=${port}`,
142
+ `--user-data-dir=${userDataDir}`,
143
+ "--no-first-run",
144
+ "--no-default-browser-check",
145
+ "--new-window",
146
+ "about:blank",
147
+ ];
148
+
149
+ try {
150
+ const child = (deps.spawnImpl ?? spawn)(chromeExe, args, {
151
+ detached: true,
152
+ stdio: "ignore",
153
+ windowsHide: true,
154
+ });
155
+ child.unref();
156
+ return { ok: true, child };
157
+ } catch (err) {
158
+ return { ok: false, error: `Failed to start Chrome: ${(err as Error).message}` };
159
+ }
160
+ }
161
+
162
+ function sleep(ms: number): Promise<void> {
163
+ return new Promise((resolve) => setTimeout(resolve, ms));
164
+ }
165
+
166
+ export async function ensureChromeCdpRunning(
167
+ cfg: ChromeDevtoolsConfig = config.chromeDevtools,
168
+ deps: ChromeDevtoolsGuardDeps = {},
169
+ ): Promise<ChromeCdpEnsureResult> {
170
+ const port = normalizePort(cfg.port);
171
+ if (!cfg.enabled) return { ok: true, started: false, port };
172
+
173
+ const probe = await probeChromeCdp(port, deps);
174
+ if (probe === "healthy") {
175
+ return { ok: true, started: false, port };
176
+ }
177
+ if (probe === "occupied") {
178
+ return {
179
+ ok: false,
180
+ started: false,
181
+ port,
182
+ error: `Port ${port} is reachable but is not a healthy Chrome CDP endpoint.`,
183
+ };
184
+ }
185
+
186
+ const started = startChromeForCdp({ ...cfg, port }, deps);
187
+ if (!started.ok) return { ok: false, started: false, port, error: started.error };
188
+
189
+ for (let i = 0; i < START_VERIFY_ATTEMPTS; i++) {
190
+ await sleep(START_VERIFY_DELAY_MS);
191
+ if (await isChromeCdpHealthy(port, deps)) {
192
+ return { ok: true, started: true, port };
193
+ }
194
+ }
195
+
196
+ return { ok: false, started: true, port, error: "Chrome started but CDP endpoint is not healthy yet." };
197
+ }
198
+
199
+ async function runGuardOnce(reason: string, deps: ChromeDevtoolsGuardDeps = {}): Promise<void> {
200
+ if (ensureInFlight) return;
201
+ const log = deps.log ?? ((message: string) => console.log(message));
202
+ ensureInFlight = ensureChromeCdpRunning(config.chromeDevtools, deps);
203
+ try {
204
+ const result = await ensureInFlight;
205
+ appendStartupTrace("chrome-devtools-guard: ensure result", {
206
+ reason,
207
+ enabled: config.chromeDevtools.enabled,
208
+ port: result.port,
209
+ ok: result.ok,
210
+ started: result.started,
211
+ error: result.error,
212
+ });
213
+ if (!config.chromeDevtools.enabled) return;
214
+ if (result.ok && result.started) {
215
+ log(`[${ts()}] [Chrome CDP] Started Chrome for http://${CDP_HOST}:${result.port}/json/version`);
216
+ } else if (!result.ok) {
217
+ log(`[${ts()}] [Chrome CDP] Guard failed: ${result.error}`);
218
+ }
219
+ } finally {
220
+ ensureInFlight = null;
221
+ }
222
+ }
223
+
224
+ export function startChromeDevtoolsGuard(deps: ChromeDevtoolsGuardDeps = {}): void {
225
+ stopChromeDevtoolsGuard();
226
+ if (!config.chromeDevtools.enabled) {
227
+ appendStartupTrace("chrome-devtools-guard: disabled");
228
+ return;
229
+ }
230
+
231
+ void runGuardOnce("startup", deps);
232
+ guardTimer = setInterval(() => {
233
+ void runGuardOnce("interval", deps);
234
+ }, GUARD_INTERVAL_MS);
235
+ }
236
+
237
+ export function stopChromeDevtoolsGuard(): void {
238
+ if (guardTimer) {
239
+ clearInterval(guardTimer);
240
+ guardTimer = null;
241
+ }
242
+ }