@blackbelt-technology/pi-dashboard-gmail-plugin 0.9.0 → 0.11.0

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,308 @@
1
+ /**
2
+ * Minimal CDP client for the setup run: one browser-level WebSocket (no
3
+ * `Origin` header — the dedicated proxy refuses one), one flattened session per
4
+ * page, and the handful of page operations the recipe needs. It never logs and
5
+ * never puts a protocol payload into an error: a failure is
6
+ * `CdpError("<method>")` only, because payloads can hold page text, including
7
+ * the client secret. See change: add-gmail-auto-setup.
8
+ */
9
+ import WebSocket from "ws";
10
+
11
+ /** The slice of `ws`'s `WebSocket` the client uses (a fake in tests). */
12
+ export interface WsLike {
13
+ send(data: string): void;
14
+ close(): void;
15
+ on(event: "open" | "close" | "error", cb: () => void): unknown;
16
+ on(event: "message", cb: (data: unknown) => void): unknown;
17
+ }
18
+ export type WsFactory = (url: string) => WsLike;
19
+
20
+ /** No `origin` option → ws sends no Origin header. */
21
+ export const defaultWsFactory: WsFactory = (url) =>
22
+ new WebSocket(url, { perMessageDeflate: false, handshakeTimeout: 10_000 }) as unknown as WsLike;
23
+
24
+ export class CdpError extends Error {
25
+ readonly method: string;
26
+ readonly code?: number;
27
+ constructor(method: string, code?: number) {
28
+ super(`cdp ${method} failed`);
29
+ this.name = "CdpError";
30
+ this.method = method;
31
+ this.code = code;
32
+ }
33
+ }
34
+
35
+ /** `Page.navigate` refused (deny set, allowed domains) or failed at the network layer. */
36
+ export class NavigationError extends Error {
37
+ constructor() {
38
+ super("navigation failed");
39
+ this.name = "NavigationError";
40
+ }
41
+ }
42
+
43
+ export interface CdpEvent {
44
+ method: string;
45
+ params?: Record<string, unknown>;
46
+ sessionId?: string;
47
+ }
48
+
49
+ interface Pending {
50
+ method: string;
51
+ resolve(v: unknown): void;
52
+ reject(e: unknown): void;
53
+ }
54
+
55
+ export class CdpConnection {
56
+ private nextId = 0;
57
+ private readonly pending = new Map<number, Pending>();
58
+ private readonly eventListeners = new Set<(ev: CdpEvent) => void>();
59
+ private readonly closeListeners = new Set<() => void>();
60
+ closed = false;
61
+
62
+ private readonly ws: WsLike;
63
+
64
+ private constructor(ws: WsLike) {
65
+ this.ws = ws;
66
+ ws.on("message", (data) => this.onMessage(data));
67
+ ws.on("close", () => this.onClosed());
68
+ ws.on("error", () => undefined); // a failing socket also emits "close"
69
+ }
70
+
71
+ static connect(url: string, factory: WsFactory = defaultWsFactory): Promise<CdpConnection> {
72
+ return new Promise((resolve, reject) => {
73
+ const ws = factory(url);
74
+ ws.on("open", () => resolve(new CdpConnection(ws)));
75
+ ws.on("error", () => reject(new CdpError("connect")));
76
+ ws.on("close", () => reject(new CdpError("connect")));
77
+ });
78
+ }
79
+
80
+ send<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<T> {
81
+ if (this.closed) return Promise.reject(new CdpError(method));
82
+ const id = ++this.nextId;
83
+ return new Promise<T>((resolve, reject) => {
84
+ this.pending.set(id, { method, resolve: resolve as (v: unknown) => void, reject });
85
+ try {
86
+ this.ws.send(JSON.stringify({ id, method, params, sessionId }));
87
+ } catch {
88
+ this.pending.delete(id);
89
+ reject(new CdpError(method));
90
+ }
91
+ });
92
+ }
93
+
94
+ onEvent(cb: (ev: CdpEvent) => void): void {
95
+ this.eventListeners.add(cb);
96
+ }
97
+
98
+ onClose(cb: () => void): void {
99
+ this.closeListeners.add(cb);
100
+ }
101
+
102
+ close(): void {
103
+ try {
104
+ this.ws.close();
105
+ } catch {
106
+ /* already closed */
107
+ }
108
+ }
109
+
110
+ private onMessage(data: unknown): void {
111
+ let msg: { id?: number; result?: unknown; error?: { code?: number }; method?: string; params?: Record<string, unknown>; sessionId?: string };
112
+ try {
113
+ msg = JSON.parse(typeof data === "string" ? data : String(data));
114
+ } catch {
115
+ return;
116
+ }
117
+ if (typeof msg.id === "number") {
118
+ const p = this.pending.get(msg.id);
119
+ if (!p) return;
120
+ this.pending.delete(msg.id);
121
+ if (msg.error) p.reject(new CdpError(p.method, msg.error.code));
122
+ else p.resolve(msg.result ?? {});
123
+ return;
124
+ }
125
+ if (typeof msg.method === "string") {
126
+ const ev: CdpEvent = { method: msg.method, params: msg.params, sessionId: msg.sessionId };
127
+ for (const l of this.eventListeners) l(ev);
128
+ }
129
+ }
130
+
131
+ private onClosed(): void {
132
+ if (this.closed) return;
133
+ this.closed = true;
134
+ for (const [, p] of this.pending) p.reject(new CdpError(p.method));
135
+ this.pending.clear();
136
+ for (const l of this.closeListeners) l();
137
+ }
138
+ }
139
+
140
+ /** Fixed page expressions; nothing user-controlled is ever interpolated. */
141
+ export const EXPR = {
142
+ /** Cheap keep-alive. */
143
+ ping: "1",
144
+ info: "({href:location.href,lang:document.documentElement.lang,ready:document.readyState})",
145
+ text: "document.body?document.body.innerText:''",
146
+ dialogText: "(document.querySelector('[role=dialog]')||{innerText:''}).innerText",
147
+ } as const;
148
+
149
+ export interface PageInfo {
150
+ href: string;
151
+ lang: string;
152
+ ready: string;
153
+ }
154
+
155
+ export interface AxNode {
156
+ backendNodeId: number;
157
+ role: string;
158
+ name: string;
159
+ checked?: boolean;
160
+ disabled?: boolean;
161
+ }
162
+
163
+ interface RawAxNode {
164
+ ignored?: boolean;
165
+ role?: { value?: string };
166
+ name?: { value?: string };
167
+ backendDOMNodeId?: number;
168
+ properties?: Array<{ name: string; value?: { value?: unknown } }>;
169
+ }
170
+
171
+ const SIGN_IN_PATTERN = {
172
+ urlPattern: "https://accounts.google.com/*",
173
+ resourceType: "Document",
174
+ requestStage: "Request",
175
+ };
176
+
177
+ export class CdpPage {
178
+ private readonly conn: CdpConnection;
179
+ private readonly sessionId: string;
180
+ private readonly targetId: string;
181
+
182
+ private constructor(conn: CdpConnection, sessionId: string, targetId: string) {
183
+ this.conn = conn;
184
+ this.sessionId = sessionId;
185
+ this.targetId = targetId;
186
+ }
187
+
188
+ /**
189
+ * Open the run's own tab (the proxy forces it into the ephemeral context) and
190
+ * arm the redirect guard: a top-level `https://accounts.google.com/*` request
191
+ * is failed BEFORE it renders and `onSignInBlocked` fires, so this tab never
192
+ * shows a password form.
193
+ */
194
+ static async open(conn: CdpConnection, opts: { onSignInBlocked(): void }): Promise<CdpPage> {
195
+ const { targetId } = await conn.send<{ targetId: string }>("Target.createTarget", { url: "about:blank" });
196
+ const { sessionId } = await conn.send<{ sessionId: string }>("Target.attachToTarget", { targetId, flatten: true });
197
+ conn.onEvent((ev) => {
198
+ if (ev.sessionId !== sessionId || ev.method !== "Fetch.requestPaused") return;
199
+ const requestId = ev.params?.requestId;
200
+ if (typeof requestId === "string") {
201
+ conn.send("Fetch.failRequest", { requestId, errorReason: "BlockedByClient" }, sessionId).catch(() => undefined);
202
+ }
203
+ opts.onSignInBlocked();
204
+ });
205
+ // Guard first: nothing may load before the pattern is armed.
206
+ await conn.send("Fetch.enable", { patterns: [SIGN_IN_PATTERN] }, sessionId);
207
+ await conn.send("Page.enable", {}, sessionId);
208
+ await conn.send("DOM.enable", {}, sessionId);
209
+ await conn.send("Accessibility.enable", {}, sessionId);
210
+ return new CdpPage(conn, sessionId, targetId);
211
+ }
212
+
213
+ private send<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>): Promise<T> {
214
+ return this.conn.send<T>(method, params, this.sessionId);
215
+ }
216
+
217
+ async navigate(url: string): Promise<void> {
218
+ let res: { errorText?: string };
219
+ try {
220
+ res = await this.send<{ errorText?: string }>("Page.navigate", { url });
221
+ } catch {
222
+ throw new NavigationError();
223
+ }
224
+ if (res.errorText) throw new NavigationError();
225
+ }
226
+
227
+ async evaluate<T = unknown>(expression: string): Promise<T> {
228
+ const res = await this.send<{ result?: { value?: T }; exceptionDetails?: unknown }>("Runtime.evaluate", {
229
+ expression,
230
+ returnByValue: true,
231
+ awaitPromise: true,
232
+ });
233
+ if (res.exceptionDetails) throw new CdpError("Runtime.evaluate");
234
+ return res.result?.value as T;
235
+ }
236
+
237
+ info(): Promise<PageInfo> {
238
+ return this.evaluate<PageInfo>(EXPR.info);
239
+ }
240
+
241
+ async text(): Promise<string> {
242
+ return String((await this.evaluate<string>(EXPR.text)) ?? "");
243
+ }
244
+
245
+ async dialogText(): Promise<string> {
246
+ return String((await this.evaluate<string>(EXPR.dialogText)) ?? "");
247
+ }
248
+
249
+ async ping(): Promise<void> {
250
+ await this.evaluate(EXPR.ping);
251
+ }
252
+
253
+ /** First non-ignored AX node with exactly this role and accessible name. */
254
+ async queryAXTree(role: string, name: string): Promise<AxNode | undefined> {
255
+ const { root } = await this.send<{ root: { nodeId: number } }>("DOM.getDocument", { depth: 0 });
256
+ const { nodes } = await this.send<{ nodes?: RawAxNode[] }>("Accessibility.queryAXTree", {
257
+ nodeId: root.nodeId,
258
+ accessibleName: name,
259
+ role,
260
+ });
261
+ const raw = (nodes ?? []).find((n) => !n.ignored && typeof n.backendDOMNodeId === "number");
262
+ if (!raw || typeof raw.backendDOMNodeId !== "number") return undefined;
263
+ const prop = (n: string) => raw.properties?.find((p) => p.name === n)?.value?.value;
264
+ const checked = prop("checked");
265
+ return {
266
+ backendNodeId: raw.backendDOMNodeId,
267
+ role: raw.role?.value ?? role,
268
+ name: raw.name?.value ?? name,
269
+ checked: checked === undefined ? undefined : checked === true || checked === "true",
270
+ disabled: prop("disabled") === true,
271
+ };
272
+ }
273
+
274
+ /** Click the centre of the node's content box. */
275
+ async clickNode(node: AxNode): Promise<void> {
276
+ await this.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: node.backendNodeId }).catch(() => undefined);
277
+ const { model } = await this.send<{ model: { content: number[] } }>("DOM.getBoxModel", {
278
+ backendNodeId: node.backendNodeId,
279
+ });
280
+ const q = model.content;
281
+ const x = (q[0]! + q[2]! + q[4]! + q[6]!) / 4;
282
+ const y = (q[1]! + q[3]! + q[5]! + q[7]!) / 4;
283
+ const base = { x, y, button: "left", clickCount: 1 };
284
+ await this.send("Input.dispatchMouseEvent", { type: "mousePressed", ...base });
285
+ await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", ...base });
286
+ }
287
+
288
+ /** Focus + select the field, then insert `text` (replaces the content). */
289
+ async fill(node: AxNode, text: string): Promise<void> {
290
+ const { object } = await this.send<{ object: { objectId: string } }>("DOM.resolveNode", {
291
+ backendNodeId: node.backendNodeId,
292
+ });
293
+ await this.send("Runtime.callFunctionOn", {
294
+ objectId: object.objectId,
295
+ functionDeclaration: "function(){this.focus();if(this.select)this.select();}",
296
+ });
297
+ await this.send("Input.insertText", { text });
298
+ }
299
+
300
+ async bringToFront(): Promise<void> {
301
+ await this.send("Page.bringToFront");
302
+ }
303
+
304
+ /** Best effort; the ephemeral context is discarded on disconnect anyway. */
305
+ async close(): Promise<void> {
306
+ await this.conn.send("Target.closeTarget", { targetId: this.targetId }).catch(() => undefined);
307
+ }
308
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Control-flow errors of a setup run. Never carry page content or secrets: the
3
+ * message is a fixed code. See change: add-gmail-auto-setup.
4
+ */
5
+ import type { HandoffReason, SetupStepId } from "../../shared/auto-setup.js";
6
+
7
+ /** Base class: a step/capture `catch` rethrows these instead of treating them as failures. */
8
+ export class SetupControl extends Error {}
9
+
10
+ /** The run stops and hands off to the manual wizard. `step` defaults to the current step. */
11
+ export class SetupHandoff extends SetupControl {
12
+ readonly reason: HandoffReason;
13
+ readonly step?: SetupStepId;
14
+ constructor(reason: HandoffReason, step?: SetupStepId) {
15
+ super(`handoff:${reason}`);
16
+ this.name = "SetupHandoff";
17
+ this.reason = reason;
18
+ this.step = step;
19
+ }
20
+ }
21
+
22
+ /** Raised on the step's page operations when the redirect guard stopped an accounts.google.com load. */
23
+ export class SignInRequired extends SetupControl {
24
+ constructor() {
25
+ super("sign_in_required");
26
+ this.name = "SignInRequired";
27
+ }
28
+ }
29
+
30
+ /** The run was cancelled/ended; stale attempts and waiters unwind quietly. */
31
+ export class RunAborted extends SetupControl {
32
+ constructor() {
33
+ super("run_aborted");
34
+ this.name = "RunAborted";
35
+ }
36
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * "Genuinely local" request predicate for starting a setup run: the checkpoints
3
+ * need the dedicated Chrome window on THIS host. Mirrors the host rule
4
+ * (`packages/server/src/auth/localhost-guard.ts`): loopback peer AND no proxy
5
+ * forwarding header, so a same-host tunnel counts as remote.
6
+ * See change: add-gmail-auto-setup.
7
+ */
8
+
9
+ function isLoopbackAddress(addr: string | undefined): boolean {
10
+ if (!addr) return false;
11
+ const a = addr.startsWith("::ffff:") ? addr.slice(7) : addr;
12
+ return a === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a);
13
+ }
14
+
15
+ /** Headers a proxy/tunnel injects; `x-forwarded-*` matched by prefix. */
16
+ function isProxyHeader(name: string): boolean {
17
+ const n = name.toLowerCase();
18
+ return n.startsWith("x-forwarded-") || n === "forwarded" || n === "via" || n === "x-real-ip";
19
+ }
20
+
21
+ export function isGenuinelyLocal(
22
+ headers: Record<string, unknown>,
23
+ remoteAddress: string | undefined,
24
+ ): boolean {
25
+ if (!isLoopbackAddress(remoteAddress)) return false;
26
+ return !Object.keys(headers).some(isProxyHeader);
27
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Secret masking for every setup log line and handoff text.
3
+ * See change: add-gmail-auto-setup.
4
+ */
5
+
6
+ /** Google OAuth client secrets: `GOCSPX-` + url-safe base64. */
7
+ const CLIENT_SECRET_RE = /GOCSPX-[A-Za-z0-9_-]+/g;
8
+
9
+ export function maskSecrets(text: string): string {
10
+ return text.replace(CLIENT_SECRET_RE, "GOCSPX-***");
11
+ }