glidercli 0.4.35 → 0.4.37

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,222 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+
7
+ from mitmproxy import ctx
8
+
9
+
10
+ SCHEMA = "glider-mitm-exact/v1"
11
+
12
+
13
+ class ExactCapture:
14
+ def __init__(self):
15
+ self.capture_dir = None
16
+ self.body_dir = None
17
+ self.index_path = None
18
+ self.terminal_count = 0
19
+ self.response_count = 0
20
+ self.error_count = 0
21
+ self.capture_error_count = 0
22
+
23
+ def load(self, loader):
24
+ loader.add_option(
25
+ "glider_capture_dir",
26
+ str,
27
+ "",
28
+ "Private directory for Glider byte-exact proxy evidence.",
29
+ )
30
+
31
+ def running(self):
32
+ configured = ctx.options.glider_capture_dir
33
+ if not configured:
34
+ raise RuntimeError("glider_capture_dir is required")
35
+ self.capture_dir = Path(configured).resolve()
36
+ self.body_dir = self.capture_dir / "bodies"
37
+ self.index_path = self.capture_dir / "flows.jsonl"
38
+ self.capture_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
39
+ self.body_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
40
+ os.chmod(self.capture_dir, 0o700)
41
+ os.chmod(self.body_dir, 0o700)
42
+ descriptor = os.open(
43
+ self.index_path,
44
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY,
45
+ 0o600,
46
+ )
47
+ os.close(descriptor)
48
+ self._write_json(
49
+ self.capture_dir / "ready.json",
50
+ {
51
+ "schema": SCHEMA,
52
+ "readyAt": self._now(),
53
+ "pid": os.getpid(),
54
+ },
55
+ )
56
+
57
+ def response(self, flow):
58
+ self._record_terminal(flow, "response")
59
+
60
+ def error(self, flow):
61
+ self._record_terminal(flow, "error")
62
+
63
+ def done(self):
64
+ if self.capture_dir is None:
65
+ return
66
+ self._write_json(
67
+ self.capture_dir / "final.json",
68
+ {
69
+ "schema": SCHEMA,
70
+ "finishedAt": self._now(),
71
+ "terminalCount": self.terminal_count,
72
+ "responseCount": self.response_count,
73
+ "errorCount": self.error_count,
74
+ "captureErrorCount": self.capture_error_count,
75
+ },
76
+ )
77
+
78
+ def _record_terminal(self, flow, terminal):
79
+ try:
80
+ request_body = self._store_body("request", flow.request.raw_content)
81
+ response_body = None
82
+ if flow.response is not None:
83
+ response_body = self._store_body(
84
+ "response",
85
+ flow.response.raw_content,
86
+ )
87
+ row = {
88
+ "schema": SCHEMA,
89
+ "flowId": flow.id,
90
+ "terminal": terminal,
91
+ "observedAt": self._now(),
92
+ "method": flow.request.method,
93
+ "url": flow.request.pretty_url,
94
+ "status": flow.response.status_code if flow.response is not None else None,
95
+ "timestamps": {
96
+ "requestStart": flow.request.timestamp_start,
97
+ "requestEnd": flow.request.timestamp_end,
98
+ "responseStart": (
99
+ flow.response.timestamp_start
100
+ if flow.response is not None
101
+ else None
102
+ ),
103
+ "responseEnd": (
104
+ flow.response.timestamp_end
105
+ if flow.response is not None
106
+ else None
107
+ ),
108
+ },
109
+ "requestBody": request_body,
110
+ "responseBody": response_body,
111
+ "error": (
112
+ {
113
+ "message": flow.error.msg,
114
+ "timestamp": flow.error.timestamp,
115
+ }
116
+ if flow.error is not None
117
+ else None
118
+ ),
119
+ }
120
+ self._append_json(row)
121
+ self.terminal_count += 1
122
+ if terminal == "response":
123
+ self.response_count += 1
124
+ else:
125
+ self.error_count += 1
126
+ except Exception as error:
127
+ self.capture_error_count += 1
128
+ self._append_capture_error(flow, terminal, error)
129
+ raise
130
+
131
+ def _store_body(self, kind, content):
132
+ if content is None:
133
+ return None
134
+ digest = hashlib.sha256(content).hexdigest()
135
+ relative = Path("bodies") / f"{kind}-{digest}.body"
136
+ destination = self.capture_dir / relative
137
+ if destination.exists():
138
+ existing = destination.read_bytes()
139
+ if len(existing) != len(content) or hashlib.sha256(existing).hexdigest() != digest:
140
+ raise RuntimeError(f"existing body artifact failed validation: {relative}")
141
+ else:
142
+ temporary = self.capture_dir / f".{kind}-{digest}-{os.getpid()}.partial"
143
+ descriptor = os.open(
144
+ temporary,
145
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY,
146
+ 0o600,
147
+ )
148
+ try:
149
+ with os.fdopen(descriptor, "wb", closefd=True) as output:
150
+ output.write(content)
151
+ output.flush()
152
+ os.fsync(output.fileno())
153
+ os.replace(temporary, destination)
154
+ os.chmod(destination, 0o600)
155
+ finally:
156
+ if temporary.exists():
157
+ temporary.unlink()
158
+ return {
159
+ "artifact": relative.as_posix(),
160
+ "bytes": len(content),
161
+ "sha256": digest,
162
+ }
163
+
164
+ def _append_json(self, value):
165
+ payload = (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()
166
+ descriptor = os.open(self.index_path, os.O_APPEND | os.O_WRONLY)
167
+ with os.fdopen(descriptor, "ab", closefd=True) as output:
168
+ output.write(payload)
169
+ output.flush()
170
+ os.fsync(output.fileno())
171
+
172
+ def _append_capture_error(self, flow, terminal, error):
173
+ path = self.capture_dir / "capture-errors.jsonl"
174
+ payload = (
175
+ json.dumps(
176
+ {
177
+ "schema": SCHEMA,
178
+ "flowId": getattr(flow, "id", None),
179
+ "terminal": terminal,
180
+ "observedAt": self._now(),
181
+ "error": f"{type(error).__name__}: {error}",
182
+ },
183
+ sort_keys=True,
184
+ separators=(",", ":"),
185
+ )
186
+ + "\n"
187
+ ).encode()
188
+ descriptor = os.open(
189
+ path,
190
+ os.O_APPEND | os.O_CREAT | os.O_WRONLY,
191
+ 0o600,
192
+ )
193
+ with os.fdopen(descriptor, "ab", closefd=True) as output:
194
+ output.write(payload)
195
+ output.flush()
196
+ os.fsync(output.fileno())
197
+
198
+ def _write_json(self, destination, value):
199
+ temporary = destination.with_name(f".{destination.name}-{os.getpid()}.partial")
200
+ payload = (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()
201
+ descriptor = os.open(
202
+ temporary,
203
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY,
204
+ 0o600,
205
+ )
206
+ try:
207
+ with os.fdopen(descriptor, "wb", closefd=True) as output:
208
+ output.write(payload)
209
+ output.flush()
210
+ os.fsync(output.fileno())
211
+ os.replace(temporary, destination)
212
+ os.chmod(destination, 0o600)
213
+ finally:
214
+ if temporary.exists():
215
+ temporary.unlink()
216
+
217
+ @staticmethod
218
+ def _now():
219
+ return datetime.now(timezone.utc).isoformat()
220
+
221
+
222
+ addons = [ExactCapture()]
@@ -0,0 +1,54 @@
1
+ 'use strict';
2
+
3
+ function targetInfo(target) {
4
+ return target && target.targetInfo && typeof target.targetInfo === 'object'
5
+ ? target.targetInfo
6
+ : {};
7
+ }
8
+
9
+ function targetType(target) {
10
+ return (target && target.type) || targetInfo(target).type || '';
11
+ }
12
+
13
+ function attachedTabs(catalog) {
14
+ if (!catalog || !Array.isArray(catalog.windows)) return [];
15
+ return catalog.windows.flatMap((window) => (
16
+ Array.isArray(window.tabs) ? window.tabs.filter((tab) => tab.attached) : []
17
+ ));
18
+ }
19
+
20
+ function summarizeStatus(catalog, targets) {
21
+ const rawTargets = Array.isArray(targets) ? targets : [];
22
+ const catalogAvailable = Boolean(catalog && Array.isArray(catalog.windows));
23
+ const tabs = attachedTabs(catalog);
24
+ const debuggerOnlyPages = catalogAvailable && Array.isArray(catalog.attached)
25
+ ? catalog.attached.filter((target) => targetType(target) === 'page')
26
+ : [];
27
+ const childTargets = catalogAvailable
28
+ ? [
29
+ ...(Array.isArray(catalog.iframes) ? catalog.iframes : []),
30
+ ...(Array.isArray(catalog.other) ? catalog.other : []),
31
+ ]
32
+ : [];
33
+ const staleTargets = catalogAvailable && Array.isArray(catalog.stale)
34
+ ? catalog.stale
35
+ : [];
36
+ const fallbackPages = catalogAvailable
37
+ ? []
38
+ : rawTargets.filter((target) => targetType(target) === 'page');
39
+
40
+ return {
41
+ catalogAvailable,
42
+ tabs,
43
+ debuggerOnlyPages,
44
+ childTargets,
45
+ staleTargets,
46
+ fallbackPages,
47
+ connectedPageCount: catalogAvailable
48
+ ? tabs.length + debuggerOnlyPages.length
49
+ : fallbackPages.length,
50
+ rawTargetCount: rawTargets.length,
51
+ };
52
+ }
53
+
54
+ module.exports = { attachedTabs, summarizeStatus, targetType };
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ function targetInfo(target) {
4
+ return target && target.targetInfo && typeof target.targetInfo === 'object'
5
+ ? target.targetInfo
6
+ : {};
7
+ }
8
+
9
+ function tabIdOf(target) {
10
+ const value = Number(target && (target.tabId ?? targetInfo(target).tabId));
11
+ return Number.isInteger(value) && value > 0 ? value : 0;
12
+ }
13
+
14
+ function targetType(target) {
15
+ return (target && target.type) || targetInfo(target).type || '';
16
+ }
17
+
18
+ function isSyntheticTabTarget(target) {
19
+ const tabId = tabIdOf(target);
20
+ const info = targetInfo(target);
21
+ return Boolean(
22
+ tabId
23
+ && (info.synthetic === true || target.targetId === `tab-${tabId}`),
24
+ );
25
+ }
26
+
27
+ function recordFromAttached(params) {
28
+ const info = params && params.targetInfo;
29
+ if (!params || !params.sessionId || !info || !info.targetId) return null;
30
+ const tabId = Number(params.tabId || info.tabId) || 0;
31
+ return {
32
+ sessionId: params.sessionId,
33
+ targetId: info.targetId,
34
+ tabId,
35
+ targetInfo: info,
36
+ };
37
+ }
38
+
39
+ function reconcileAttachedTarget(targets, params) {
40
+ const incoming = recordFromAttached(params);
41
+ if (!incoming) return { stored: false, ignored: true, removedSessionIds: [] };
42
+
43
+ const tabId = tabIdOf(incoming);
44
+ const page = targetType(incoming) === 'page';
45
+ const peers = page && tabId
46
+ ? Array.from(targets.values()).filter((target) => (
47
+ target.sessionId !== incoming.sessionId
48
+ && targetType(target) === 'page'
49
+ && tabIdOf(target) === tabId
50
+ ))
51
+ : [];
52
+
53
+ if (isSyntheticTabTarget(incoming)) {
54
+ const real = peers.find((target) => !isSyntheticTabTarget(target));
55
+ if (real) {
56
+ return {
57
+ stored: false,
58
+ ignored: true,
59
+ record: real,
60
+ removedSessionIds: [],
61
+ };
62
+ }
63
+ }
64
+
65
+ const removedSessionIds = [];
66
+ for (const peer of peers) {
67
+ targets.delete(peer.sessionId);
68
+ removedSessionIds.push(peer.sessionId);
69
+ }
70
+ targets.set(incoming.sessionId, incoming);
71
+ return { stored: true, ignored: false, record: incoming, removedSessionIds };
72
+ }
73
+
74
+ function updateTargetInfo(targets, { sessionId, targetInfo: nextInfo, tabId } = {}) {
75
+ if (!nextInfo || typeof nextInfo !== 'object') return null;
76
+ const nextTabId = Number(tabId || nextInfo.tabId) || 0;
77
+ let target = sessionId ? targets.get(sessionId) : null;
78
+ if (!target && nextInfo.targetId) {
79
+ target = Array.from(targets.values())
80
+ .find((entry) => entry.targetId === nextInfo.targetId);
81
+ }
82
+ if (!target && nextTabId) {
83
+ target = Array.from(targets.values())
84
+ .find((entry) => tabIdOf(entry) === nextTabId && targetType(entry) === 'page');
85
+ }
86
+ if (!target) return null;
87
+
88
+ target.targetInfo = { ...targetInfo(target), ...nextInfo };
89
+ target.targetId = nextInfo.targetId || target.targetId;
90
+ target.tabId = nextTabId || tabIdOf(target);
91
+ return target;
92
+ }
93
+
94
+ module.exports = {
95
+ isSyntheticTabTarget,
96
+ reconcileAttachedTarget,
97
+ tabIdOf,
98
+ targetType,
99
+ updateTargetInfo,
100
+ };
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.4.35",
3
+ "version": "0.4.37",
4
4
  "description": "Browser automation CLI. Control a configured Chromium browser through an extension CDP relay, run YAML tasks, and execute bounded autonomous loops.",
5
5
  "bin": {
6
6
  "glider": "bin/glider.js"
7
7
  },
8
8
  "scripts": {
9
9
  "test": "node --test tests/*.test.js",
10
- "test:syntax": "node --check bin/glider.js && node --check lib/bserve.js && node --check lib/bexplore.js && node --check lib/tab-catalog.js && node --check lib/tab-tui.js && node --check lib/tab-map.js && node --check lib/pin-machine.js && node --check lib/relay-heal.js && node --check lib/pkg-update.js && node --check lib/cookie-jar.js && node --check lib/headless-runtime.js",
11
- "test:regression": "node --test tests/browser-config.test.js tests/core.test.js tests/cli-regression.test.js tests/relay-integration.test.js tests/tab-tui-color-regression.test.js tests/tab-map.test.js tests/tab-catalog.test.js",
10
+ "test:syntax": "node --check bin/glider.js && node --check lib/bserve.js && node --check lib/bexplore.js && node --check lib/tab-catalog.js && node --check lib/tab-tui.js && node --check lib/tab-map.js && node --check lib/pin-machine.js && node --check lib/relay-heal.js && node --check lib/status-model.js && node --check lib/target-registry.js && node --check lib/pkg-update.js && node --check lib/cookie-jar.js && node --check lib/headless-runtime.js",
11
+ "test:regression": "node --test tests/browser-config.test.js tests/core.test.js tests/cli-regression.test.js tests/relay-integration.test.js tests/target-registry.test.js tests/tab-tui-color-regression.test.js tests/tab-map.test.js tests/tab-catalog.test.js",
12
12
  "test:integration": "node --test tests/relay-integration.test.js tests/daemon-lifecycle.test.js",
13
13
  "test:pack": "node --test tests/npm-tarball.test.js",
14
14
  "test:smoke": "node tests/live-browser.smoke.js",