glidercli 0.4.33 → 0.4.35
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.
- package/README.md +20 -4
- package/bin/glider.js +35 -2
- package/lib/headless-runtime.js +815 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -146,6 +146,22 @@ glider cookie-jar read chat.example.com
|
|
|
146
146
|
|
|
147
147
|
Offline curl: `COOKIE_FILE=~/.glider/cookies/HOST/header.txt`. Index: `glider cookie-jar rebuild` scans `$GLIDER/warch/**/glider.json` for `cookie_jar.enabled`. Optional extra tree: set `GLIDER_EXTRA_WARCH_ROOT` (path-separated).
|
|
148
148
|
|
|
149
|
+
### Isolated headless subscribers
|
|
150
|
+
|
|
151
|
+
Glider owns the browser lifecycle, CDP client, cookie import/export, network
|
|
152
|
+
capture, private artifacts, and temporary-profile cleanup. Domain packages
|
|
153
|
+
subscribe to that runtime and keep only their site-specific behavior:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
glider headless contract
|
|
157
|
+
glider headless run ./subscriber.mjs -- inspect --entity-id 123
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Subscribers export `apiVersion = "headless-subscriber/v1"`, `configure()`, and
|
|
161
|
+
`run()`. The runtime never attaches to, creates, or focuses a tab in the
|
|
162
|
+
operator's GUI browser. Cookie rotation is exported only after the subscriber
|
|
163
|
+
calls `markAuthenticated()`.
|
|
164
|
+
|
|
149
165
|
| Env | Default | Role |
|
|
150
166
|
|-----|---------|------|
|
|
151
167
|
| `GLIDER` | `~/.glider` | home: config, cache, warch |
|
|
@@ -208,8 +224,8 @@ CLI 0.4.18 expects an extension with `listTabs` plus `incognito` on tabs/windows
|
|
|
208
224
|
| `glider click` | click |
|
|
209
225
|
| `glider type` | type |
|
|
210
226
|
| `glider screenshot` | PNG |
|
|
211
|
-
| `glider frozen` | detect frozen tab |
|
|
212
|
-
| `glider thaw` | unfreeze tab |
|
|
227
|
+
| `glider frozen` | detect frozen tab (detect only; unknown flags/args fail closed) |
|
|
228
|
+
| `glider thaw` | unfreeze tab (`--verify` / `--all`). Not a subcommand of `frozen` |
|
|
213
229
|
| `glider explore` | crawl + HAR |
|
|
214
230
|
| `glider resolve` | host warch |
|
|
215
231
|
| `glider run` | YAML task |
|
|
@@ -235,9 +251,9 @@ Incomplete event-stream features fail closed: `wait --network-idle`, console str
|
|
|
235
251
|
|
|
236
252
|
| status | item |
|
|
237
253
|
|--------|------|
|
|
238
|
-
| done | CDP relay, YAML tasks, loop, daemon, multi-tab, `resolve`, `glider tabs` catalog |
|
|
254
|
+
| done | CDP relay, YAML tasks, loop, daemon, multi-tab, `resolve`, `glider tabs` catalog, isolated headless subscriber runtime |
|
|
239
255
|
| planned | Linux and Windows browser launch |
|
|
240
|
-
| | headless
|
|
256
|
+
| | remote headless workers |
|
|
241
257
|
| | task chaining |
|
|
242
258
|
|
|
243
259
|
---
|
package/bin/glider.js
CHANGED
|
@@ -3056,6 +3056,9 @@ async function cmdCorsFetch(url, opts = []) {
|
|
|
3056
3056
|
// Semantics: 'hidden|true' → macrotasks (setTimeout/fetch/XHR/workers) will not fire.
|
|
3057
3057
|
// Exit code: 0 if visible, 1 if hidden (chainable in scripts).
|
|
3058
3058
|
async function cmdFrozen(opts = []) {
|
|
3059
|
+
// Detect only. Unknown flags/positionals fail closed (never silent-ignore).
|
|
3060
|
+
// Wrong form `glider frozen thaw` must die here with the correct verb tip —
|
|
3061
|
+
// no compatibility redirect.
|
|
3059
3062
|
let sessionId = null;
|
|
3060
3063
|
for (let i = 0; i < opts.length; i++) {
|
|
3061
3064
|
const a = opts[i];
|
|
@@ -3064,7 +3067,22 @@ async function cmdFrozen(opts = []) {
|
|
|
3064
3067
|
console.log('Usage: glider frozen [--session <id>]');
|
|
3065
3068
|
console.log(' Detect whether the attached tab is macrotask-frozen (hidden).');
|
|
3066
3069
|
console.log(' Exit code: 0 = visible, 1 = hidden (frozen).');
|
|
3070
|
+
console.log(' Detect only. To unfreeze: glider thaw [--session <id>] [--all] [--verify]');
|
|
3067
3071
|
return;
|
|
3072
|
+
} else if (a.startsWith('-')) {
|
|
3073
|
+
log.fail(`unknown flag: ${a}`);
|
|
3074
|
+
console.log('Usage: glider frozen [--session <id>]');
|
|
3075
|
+
console.log(' Detect only. To unfreeze: glider thaw [--verify]');
|
|
3076
|
+
process.exit(2);
|
|
3077
|
+
} else {
|
|
3078
|
+
log.fail(`unknown argument: ${a}`);
|
|
3079
|
+
console.log('Usage: glider frozen [--session <id>]');
|
|
3080
|
+
if (a === 'thaw' || a === 'unfreeze' || a === 'wake' || a === 'activate' || a === 'restore') {
|
|
3081
|
+
console.log(` '${a}' is not a frozen subcommand. Use: glider thaw [--session <id>] [--all] [--verify]`);
|
|
3082
|
+
} else {
|
|
3083
|
+
console.log(` '${a}' is not a frozen subcommand. To unfreeze: glider thaw [--verify]`);
|
|
3084
|
+
}
|
|
3085
|
+
process.exit(2);
|
|
3068
3086
|
}
|
|
3069
3087
|
}
|
|
3070
3088
|
if (!await ensureConnected()) process.exit(1);
|
|
@@ -3134,6 +3152,14 @@ async function cmdThaw(opts = []) {
|
|
|
3134
3152
|
console.log(' --verify re-check visibility + async liveness after thawing');
|
|
3135
3153
|
console.log(' Reverse of `glider frozen` (detect). Idempotent.');
|
|
3136
3154
|
return;
|
|
3155
|
+
} else if (a.startsWith('-')) {
|
|
3156
|
+
log.fail(`unknown flag: ${a}`);
|
|
3157
|
+
console.log('Usage: glider thaw [--session <id>] [--all] [--verify]');
|
|
3158
|
+
process.exit(2);
|
|
3159
|
+
} else {
|
|
3160
|
+
log.fail(`unknown argument: ${a}`);
|
|
3161
|
+
console.log('Usage: glider thaw [--session <id>] [--all] [--verify]');
|
|
3162
|
+
process.exit(2);
|
|
3137
3163
|
}
|
|
3138
3164
|
}
|
|
3139
3165
|
if (!await ensureConnected()) process.exit(1);
|
|
@@ -4336,6 +4362,9 @@ ${B5}EXTRACTION PATTERNS${NC} ${DIM}(bulletproof, domain-agnostic)${NC}
|
|
|
4336
4362
|
${B5}AUTOMATION${NC}
|
|
4337
4363
|
${BW}run${NC} <task.yaml> Execute YAML task file
|
|
4338
4364
|
${BW}loop${NC} <task.yaml> Loop until marker
|
|
4365
|
+
${BW}headless run${NC} <subscriber.mjs> -- [args]
|
|
4366
|
+
Run a versioned subscriber in an isolated Chromium profile
|
|
4367
|
+
${BW}headless contract${NC} Print the subscriber API contract
|
|
4339
4368
|
|
|
4340
4369
|
${B5}EXAMPLES${NC}
|
|
4341
4370
|
${DIM}$${NC} glider install ${DIM}# one-time setup${NC}
|
|
@@ -4377,6 +4406,7 @@ ${YELLOW}RALPH WIGGUM PATTERN:${NC}
|
|
|
4377
4406
|
${YELLOW}REQUIREMENTS:${NC}
|
|
4378
4407
|
- Node.js 18+
|
|
4379
4408
|
- Glider extension from Chrome Web Store connected in a Chromium browser
|
|
4409
|
+
- Headless subscribers use a local Chromium binary and do not require the extension
|
|
4380
4410
|
|
|
4381
4411
|
${YELLOW}DOMAIN EXTENSIONS:${NC}
|
|
4382
4412
|
Add custom domain commands via $GLIDER/config/domains.json:
|
|
@@ -5831,7 +5861,7 @@ async function main() {
|
|
|
5831
5861
|
|
|
5832
5862
|
const relayIndependent = new Set([
|
|
5833
5863
|
'help', '--help', '-h', 'update', 'version', '-v', '--version',
|
|
5834
|
-
'config', 'domains', 'resolve', 'cookie-jar',
|
|
5864
|
+
'config', 'domains', 'resolve', 'cookie-jar', 'headless',
|
|
5835
5865
|
]);
|
|
5836
5866
|
if (relayConfigError && !relayIndependent.has(cmd)) {
|
|
5837
5867
|
throw relayConfigError;
|
|
@@ -5849,7 +5879,7 @@ async function main() {
|
|
|
5849
5879
|
'start', 'stop', 'restart', 'status', 'test', 'doctor', 'heal', 'connect',
|
|
5850
5880
|
'install', 'uninstall', 'config',
|
|
5851
5881
|
'help', '--help', '-h', 'update', 'version', '-v', '--version',
|
|
5852
|
-
'domains', 'resolve', 'cookie-jar',
|
|
5882
|
+
'domains', 'resolve', 'cookie-jar', 'headless',
|
|
5853
5883
|
]);
|
|
5854
5884
|
if (!noRelayPreflight.has(cmd)) {
|
|
5855
5885
|
if (!await checkServer()) {
|
|
@@ -6065,6 +6095,9 @@ async function main() {
|
|
|
6065
6095
|
case 'cookie-jar':
|
|
6066
6096
|
await cmdCookieJar(args.slice(1));
|
|
6067
6097
|
break;
|
|
6098
|
+
case 'headless':
|
|
6099
|
+
await require(path.join(LIB_DIR, 'headless-runtime.js')).cmdHeadless(args.slice(1));
|
|
6100
|
+
break;
|
|
6068
6101
|
case 'spawn':
|
|
6069
6102
|
await cmdSpawn(args.slice(1));
|
|
6070
6103
|
break;
|
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { spawn } = require('node:child_process');
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const fsp = require('node:fs/promises');
|
|
6
|
+
const os = require('node:os');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const { pathToFileURL } = require('node:url');
|
|
9
|
+
|
|
10
|
+
const SUBSCRIBER_API = 'headless-subscriber/v1';
|
|
11
|
+
|
|
12
|
+
function delay(milliseconds) {
|
|
13
|
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
class CdpClient {
|
|
17
|
+
constructor(commandStream, eventStream) {
|
|
18
|
+
this.commandStream = commandStream;
|
|
19
|
+
this.eventStream = eventStream;
|
|
20
|
+
this.sessionId = null;
|
|
21
|
+
this.nextId = 1;
|
|
22
|
+
this.pending = new Map();
|
|
23
|
+
this.listeners = new Map();
|
|
24
|
+
this.buffer = '';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async connect() {
|
|
28
|
+
const rejectPending = (error) => {
|
|
29
|
+
for (const pending of this.pending.values()) pending.reject(error);
|
|
30
|
+
this.pending.clear();
|
|
31
|
+
};
|
|
32
|
+
this.eventStream.on('data', (chunk) => {
|
|
33
|
+
this.buffer += chunk.toString('utf8');
|
|
34
|
+
let delimiter;
|
|
35
|
+
while ((delimiter = this.buffer.indexOf('\0')) !== -1) {
|
|
36
|
+
const raw = this.buffer.slice(0, delimiter);
|
|
37
|
+
this.buffer = this.buffer.slice(delimiter + 1);
|
|
38
|
+
if (!raw) continue;
|
|
39
|
+
const message = JSON.parse(raw);
|
|
40
|
+
this.handleMessage(message);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
this.eventStream.once('error', rejectPending);
|
|
44
|
+
this.eventStream.once('close', () => {
|
|
45
|
+
rejectPending(new Error('CDP pipe closed'));
|
|
46
|
+
});
|
|
47
|
+
this.commandStream.once('error', rejectPending);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
handleMessage(message) {
|
|
51
|
+
if (message.id) {
|
|
52
|
+
const pending = this.pending.get(message.id);
|
|
53
|
+
if (!pending) return;
|
|
54
|
+
this.pending.delete(message.id);
|
|
55
|
+
if (message.error) {
|
|
56
|
+
pending.reject(new Error(`${pending.method}: ${message.error.message}`));
|
|
57
|
+
} else {
|
|
58
|
+
pending.resolve(message.result);
|
|
59
|
+
}
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
for (const listener of this.listeners.get(message.method) || []) {
|
|
63
|
+
listener(message.params || {});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
call(method, params = {}, options = {}) {
|
|
68
|
+
const id = this.nextId++;
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
this.pending.set(id, { method, resolve, reject });
|
|
71
|
+
const message = { id, method, params };
|
|
72
|
+
const sessionId = options.browserCommand ? null : this.sessionId;
|
|
73
|
+
if (sessionId) message.sessionId = sessionId;
|
|
74
|
+
this.commandStream.write(`${JSON.stringify(message)}\0`);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
useSession(sessionId) {
|
|
79
|
+
this.sessionId = sessionId;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
on(method, listener) {
|
|
83
|
+
const listeners = this.listeners.get(method) || [];
|
|
84
|
+
listeners.push(listener);
|
|
85
|
+
this.listeners.set(method, listeners);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
close() {
|
|
89
|
+
this.commandStream?.end();
|
|
90
|
+
this.eventStream?.destroy();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function parseNetscapeCookieJar(text) {
|
|
95
|
+
const cookies = [];
|
|
96
|
+
for (const originalLine of text.split(/\r?\n/)) {
|
|
97
|
+
if (!originalLine.trim()) continue;
|
|
98
|
+
const httpOnly = originalLine.startsWith('#HttpOnly_');
|
|
99
|
+
if (originalLine.startsWith('#') && !httpOnly) continue;
|
|
100
|
+
const line = httpOnly ? originalLine.slice('#HttpOnly_'.length) : originalLine;
|
|
101
|
+
const fields = line.split('\t');
|
|
102
|
+
if (fields.length < 7) continue;
|
|
103
|
+
const [domain, , cookiePath, secure, expires, name, ...valueParts] = fields;
|
|
104
|
+
const cookie = {
|
|
105
|
+
name,
|
|
106
|
+
value: valueParts.join('\t'),
|
|
107
|
+
domain,
|
|
108
|
+
path: cookiePath || '/',
|
|
109
|
+
secure: secure.toUpperCase() === 'TRUE',
|
|
110
|
+
httpOnly,
|
|
111
|
+
};
|
|
112
|
+
const expiry = Number(expires);
|
|
113
|
+
if (Number.isFinite(expiry) && expiry > 0) cookie.expires = expiry;
|
|
114
|
+
cookies.push(cookie);
|
|
115
|
+
}
|
|
116
|
+
return cookies;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function chromeCookieToCdp(cookie, defaultDomain) {
|
|
120
|
+
const domain = cookie.domain || defaultDomain;
|
|
121
|
+
if (!domain) throw new Error(`cookie ${cookie.name || '<unnamed>'} has no domain`);
|
|
122
|
+
const result = {
|
|
123
|
+
name: cookie.name,
|
|
124
|
+
value: cookie.value ?? '',
|
|
125
|
+
domain,
|
|
126
|
+
path: cookie.path || '/',
|
|
127
|
+
secure: cookie.secure === true,
|
|
128
|
+
httpOnly: cookie.httpOnly === true,
|
|
129
|
+
};
|
|
130
|
+
const expires = cookie.expires ?? cookie.expirationDate;
|
|
131
|
+
if (Number.isFinite(expires) && expires > 0) result.expires = expires;
|
|
132
|
+
if (cookie.sameSite && cookie.sameSite !== 'unspecified') {
|
|
133
|
+
const normalized = String(cookie.sameSite).toLowerCase();
|
|
134
|
+
result.sameSite = normalized === 'no_restriction'
|
|
135
|
+
? 'None'
|
|
136
|
+
: normalized[0].toUpperCase() + normalized.slice(1);
|
|
137
|
+
}
|
|
138
|
+
return result;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function parseCookieSource(text, defaultDomain) {
|
|
142
|
+
const trimmed = text.trim();
|
|
143
|
+
if (!trimmed) throw new Error('cookie source is empty');
|
|
144
|
+
if (trimmed.startsWith('[')) {
|
|
145
|
+
const rows = JSON.parse(trimmed);
|
|
146
|
+
if (!Array.isArray(rows)) throw new Error('cookie JSON must be an array');
|
|
147
|
+
return {
|
|
148
|
+
format: 'json',
|
|
149
|
+
cookies: rows.map((cookie) => chromeCookieToCdp(cookie, defaultDomain)),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
const netscape = parseNetscapeCookieJar(text);
|
|
153
|
+
if (netscape.length) return { format: 'netscape', cookies: netscape };
|
|
154
|
+
if (!defaultDomain) {
|
|
155
|
+
throw new Error('Cookie-header import requires cookieDomain');
|
|
156
|
+
}
|
|
157
|
+
const header = trimmed.replace(/^Cookie:\s*/i, '').split(/\r?\n/)[0];
|
|
158
|
+
const cookies = header.split(';').map((part) => {
|
|
159
|
+
const separator = part.indexOf('=');
|
|
160
|
+
if (separator <= 0) return null;
|
|
161
|
+
return {
|
|
162
|
+
name: part.slice(0, separator).trim(),
|
|
163
|
+
value: part.slice(separator + 1),
|
|
164
|
+
domain: defaultDomain,
|
|
165
|
+
path: '/',
|
|
166
|
+
secure: true,
|
|
167
|
+
httpOnly: false,
|
|
168
|
+
};
|
|
169
|
+
}).filter(Boolean);
|
|
170
|
+
if (!cookies.length) throw new Error('cookie source has no parseable cookies');
|
|
171
|
+
return { format: 'header', cookies };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function normalizedDomain(domain) {
|
|
175
|
+
return String(domain || '').replace(/^\./, '').toLowerCase();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function cookieDomainAllowed(domain, allowedDomains) {
|
|
179
|
+
const normalized = normalizedDomain(domain);
|
|
180
|
+
return allowedDomains.some((allowed) => normalized === normalizedDomain(allowed));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function serializeCookies(format, cookies) {
|
|
184
|
+
if (format === 'json') {
|
|
185
|
+
return `${JSON.stringify(cookies.map((cookie) => ({
|
|
186
|
+
name: cookie.name,
|
|
187
|
+
value: cookie.value,
|
|
188
|
+
domain: cookie.domain,
|
|
189
|
+
path: cookie.path || '/',
|
|
190
|
+
secure: cookie.secure === true,
|
|
191
|
+
httpOnly: cookie.httpOnly === true,
|
|
192
|
+
sameSite: cookie.sameSite,
|
|
193
|
+
expirationDate: Number.isFinite(cookie.expires) && cookie.expires > 0
|
|
194
|
+
? cookie.expires
|
|
195
|
+
: undefined,
|
|
196
|
+
})), null, 2)}\n`;
|
|
197
|
+
}
|
|
198
|
+
if (format === 'header') {
|
|
199
|
+
return `${cookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; ')}\n`;
|
|
200
|
+
}
|
|
201
|
+
const lines = [
|
|
202
|
+
'# Netscape HTTP Cookie File',
|
|
203
|
+
'# Refreshed by Glider isolated headless runtime.',
|
|
204
|
+
...cookies.map((cookie) => {
|
|
205
|
+
const prefix = cookie.httpOnly ? '#HttpOnly_' : '';
|
|
206
|
+
const includeSubdomains = cookie.domain.startsWith('.') ? 'TRUE' : 'FALSE';
|
|
207
|
+
const secure = cookie.secure ? 'TRUE' : 'FALSE';
|
|
208
|
+
const expires = Number.isFinite(cookie.expires) && cookie.expires > 0
|
|
209
|
+
? Math.floor(cookie.expires)
|
|
210
|
+
: 0;
|
|
211
|
+
return [
|
|
212
|
+
`${prefix}${cookie.domain}`,
|
|
213
|
+
includeSubdomains,
|
|
214
|
+
cookie.path || '/',
|
|
215
|
+
secure,
|
|
216
|
+
expires,
|
|
217
|
+
cookie.name,
|
|
218
|
+
cookie.value,
|
|
219
|
+
].join('\t');
|
|
220
|
+
}),
|
|
221
|
+
'',
|
|
222
|
+
];
|
|
223
|
+
return lines.join('\n');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function atomicWrite(filePath, data, mode = 0o600) {
|
|
227
|
+
await fsp.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
228
|
+
const temporary = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
229
|
+
await fsp.writeFile(temporary, data, { mode, flag: 'wx' });
|
|
230
|
+
await fsp.rename(temporary, filePath);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function prepareOutputDir(outputDir) {
|
|
234
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : null;
|
|
235
|
+
const assertTrustedAncestors = async (target) => {
|
|
236
|
+
let current = path.resolve(target);
|
|
237
|
+
while (true) {
|
|
238
|
+
try {
|
|
239
|
+
const stat = await fsp.lstat(current);
|
|
240
|
+
if (stat.isSymbolicLink()) {
|
|
241
|
+
throw new Error(`headless output ancestor is a symlink: ${current}`);
|
|
242
|
+
}
|
|
243
|
+
if ((stat.mode & 0o022) !== 0) {
|
|
244
|
+
throw new Error(`headless output ancestor is group/world writable: ${current}`);
|
|
245
|
+
}
|
|
246
|
+
if (uid != null && stat.uid !== uid && stat.uid !== 0) {
|
|
247
|
+
throw new Error(`headless output ancestor has an untrusted owner: ${current}`);
|
|
248
|
+
}
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (error.code !== 'ENOENT') throw error;
|
|
251
|
+
}
|
|
252
|
+
const parent = path.dirname(current);
|
|
253
|
+
if (parent === current) break;
|
|
254
|
+
current = parent;
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
await assertTrustedAncestors(path.dirname(outputDir));
|
|
258
|
+
try {
|
|
259
|
+
await fsp.lstat(outputDir);
|
|
260
|
+
throw new Error(`headless output directory already exists: ${outputDir}`);
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error.code !== 'ENOENT') throw error;
|
|
263
|
+
await fsp.mkdir(outputDir, { recursive: true, mode: 0o700 });
|
|
264
|
+
}
|
|
265
|
+
const resolved = await fsp.realpath(outputDir);
|
|
266
|
+
await assertTrustedAncestors(resolved);
|
|
267
|
+
const stat = await fsp.lstat(resolved);
|
|
268
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
269
|
+
throw new Error(`headless output must be a real directory: ${resolved}`);
|
|
270
|
+
}
|
|
271
|
+
if (uid != null && stat.uid !== uid) {
|
|
272
|
+
throw new Error(`headless output directory has an untrusted owner: ${resolved}`);
|
|
273
|
+
}
|
|
274
|
+
await fsp.chmod(resolved, 0o700);
|
|
275
|
+
return resolved;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function browserCandidates() {
|
|
279
|
+
if (process.platform === 'darwin') {
|
|
280
|
+
return [
|
|
281
|
+
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
|
282
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
283
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
284
|
+
];
|
|
285
|
+
}
|
|
286
|
+
if (process.platform === 'win32') {
|
|
287
|
+
return [
|
|
288
|
+
path.join(process.env.PROGRAMFILES || '', 'Microsoft/Edge/Application/msedge.exe'),
|
|
289
|
+
path.join(process.env.PROGRAMFILES || '', 'Google/Chrome/Application/chrome.exe'),
|
|
290
|
+
];
|
|
291
|
+
}
|
|
292
|
+
return [
|
|
293
|
+
'/usr/bin/microsoft-edge',
|
|
294
|
+
'/usr/bin/google-chrome',
|
|
295
|
+
'/usr/bin/chromium',
|
|
296
|
+
'/usr/bin/chromium-browser',
|
|
297
|
+
];
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function resolveBrowserBinary(configured) {
|
|
301
|
+
const resolved = configured
|
|
302
|
+
? path.resolve(configured)
|
|
303
|
+
: browserCandidates().find((candidate) => candidate && fs.existsSync(candidate));
|
|
304
|
+
if (!resolved) {
|
|
305
|
+
throw new Error('no supported Chromium binary found; pass --browser or configure browserBinary');
|
|
306
|
+
}
|
|
307
|
+
const stat = fs.statSync(resolved);
|
|
308
|
+
if (!stat.isFile()) throw new Error(`browser binary is not a file: ${resolved}`);
|
|
309
|
+
fs.accessSync(resolved, fs.constants.X_OK);
|
|
310
|
+
return resolved;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function stopProcess(child) {
|
|
314
|
+
if (!child || child.exitCode !== null || child.signalCode !== null) return;
|
|
315
|
+
const exited = new Promise((resolve) => child.once('exit', resolve));
|
|
316
|
+
child.kill('SIGTERM');
|
|
317
|
+
let timer;
|
|
318
|
+
const graceful = await Promise.race([
|
|
319
|
+
exited.then(() => true),
|
|
320
|
+
new Promise((resolve) => {
|
|
321
|
+
timer = setTimeout(() => resolve(false), 5_000);
|
|
322
|
+
}),
|
|
323
|
+
]);
|
|
324
|
+
if (timer) clearTimeout(timer);
|
|
325
|
+
if (!graceful && child.exitCode === null && child.signalCode === null) {
|
|
326
|
+
child.kill('SIGKILL');
|
|
327
|
+
await exited;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function parseRuntimeArgs(argv) {
|
|
332
|
+
const separator = argv.indexOf('--');
|
|
333
|
+
const runtimeArgs = separator === -1 ? argv : argv.slice(0, separator);
|
|
334
|
+
const subscriberArgs = separator === -1 ? [] : argv.slice(separator + 1);
|
|
335
|
+
const options = {
|
|
336
|
+
action: runtimeArgs[0] || 'help',
|
|
337
|
+
subscriber: runtimeArgs[1] || '',
|
|
338
|
+
outputDir: '',
|
|
339
|
+
cookieJar: '',
|
|
340
|
+
cookieDomain: '',
|
|
341
|
+
browserBinary: '',
|
|
342
|
+
cookieExport: true,
|
|
343
|
+
subscriberArgs,
|
|
344
|
+
};
|
|
345
|
+
const valueAfter = (index, option) => {
|
|
346
|
+
const value = runtimeArgs[index + 1];
|
|
347
|
+
if (!value || value.startsWith('--')) {
|
|
348
|
+
throw new Error(`${option} requires a value`);
|
|
349
|
+
}
|
|
350
|
+
return value;
|
|
351
|
+
};
|
|
352
|
+
for (let index = 2; index < runtimeArgs.length; index += 1) {
|
|
353
|
+
const argument = runtimeArgs[index];
|
|
354
|
+
if (argument === '--out') options.outputDir = path.resolve(valueAfter(index++, argument));
|
|
355
|
+
else if (argument === '--cookie-jar') options.cookieJar = path.resolve(valueAfter(index++, argument));
|
|
356
|
+
else if (argument === '--cookie-domain') options.cookieDomain = valueAfter(index++, argument);
|
|
357
|
+
else if (argument === '--browser') options.browserBinary = valueAfter(index++, argument);
|
|
358
|
+
else if (argument === '--no-cookie-export') options.cookieExport = false;
|
|
359
|
+
else throw new Error(`unknown headless runtime argument: ${argument}`);
|
|
360
|
+
}
|
|
361
|
+
return options;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function headlessHelp() {
|
|
365
|
+
return [
|
|
366
|
+
'Usage: glider headless run <subscriber.mjs> [runtime options] -- [subscriber args]',
|
|
367
|
+
' glider headless contract',
|
|
368
|
+
'',
|
|
369
|
+
'Runtime options:',
|
|
370
|
+
' --out PATH Override subscriber output directory',
|
|
371
|
+
' --cookie-jar PATH Override subscriber cookie source',
|
|
372
|
+
' --cookie-domain HOST Domain for Cookie-header sources',
|
|
373
|
+
' --browser PATH Chromium-family browser binary',
|
|
374
|
+
' --no-cookie-export Do not persist rotated cookies',
|
|
375
|
+
'',
|
|
376
|
+
`Subscriber API: ${SUBSCRIBER_API}`,
|
|
377
|
+
].join('\n');
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async function loadSubscriber(modulePath) {
|
|
381
|
+
const resolved = path.resolve(modulePath);
|
|
382
|
+
if (!fs.existsSync(resolved)) throw new Error(`headless subscriber not found: ${resolved}`);
|
|
383
|
+
const imported = await import(pathToFileURL(resolved).href);
|
|
384
|
+
const subscriber = imported.default && typeof imported.default === 'object'
|
|
385
|
+
? imported.default
|
|
386
|
+
: imported;
|
|
387
|
+
if (subscriber.apiVersion !== SUBSCRIBER_API) {
|
|
388
|
+
throw new Error(`subscriber must export apiVersion="${SUBSCRIBER_API}"`);
|
|
389
|
+
}
|
|
390
|
+
if (typeof subscriber.configure !== 'function' || typeof subscriber.run !== 'function') {
|
|
391
|
+
throw new Error('subscriber must export configure() and run()');
|
|
392
|
+
}
|
|
393
|
+
return { subscriber, resolved };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function evaluate(client, expression, awaitPromise = true) {
|
|
397
|
+
const result = await client.call('Runtime.evaluate', {
|
|
398
|
+
expression,
|
|
399
|
+
awaitPromise,
|
|
400
|
+
returnByValue: true,
|
|
401
|
+
userGesture: false,
|
|
402
|
+
});
|
|
403
|
+
if (result.exceptionDetails) {
|
|
404
|
+
const detail = result.exceptionDetails.exception?.description
|
|
405
|
+
|| result.exceptionDetails.text
|
|
406
|
+
|| 'evaluation failed';
|
|
407
|
+
throw new Error(detail);
|
|
408
|
+
}
|
|
409
|
+
return result.result.value;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function waitForExpression(client, expression, timeoutMs, description) {
|
|
413
|
+
const deadline = Date.now() + timeoutMs;
|
|
414
|
+
let lastValue;
|
|
415
|
+
while (Date.now() < deadline) {
|
|
416
|
+
lastValue = await evaluate(
|
|
417
|
+
client,
|
|
418
|
+
`(() => { try { return Boolean(${expression}); } catch { return false; } })()`,
|
|
419
|
+
);
|
|
420
|
+
if (lastValue) return;
|
|
421
|
+
await delay(250);
|
|
422
|
+
}
|
|
423
|
+
throw new Error(`timed out waiting for ${description}; last=${lastValue}`);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async function physicalClick(client, elementExpression, description) {
|
|
427
|
+
const pointExpression = `(() => {
|
|
428
|
+
const element = ${elementExpression};
|
|
429
|
+
if (!element) return null;
|
|
430
|
+
element.scrollIntoView({ block: "center", inline: "center" });
|
|
431
|
+
const rect = element.getBoundingClientRect();
|
|
432
|
+
if (!rect.width || !rect.height) return null;
|
|
433
|
+
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
|
|
434
|
+
})()`;
|
|
435
|
+
let point = await evaluate(client, pointExpression);
|
|
436
|
+
if (!point) throw new Error(`cannot click ${description}: element not visible`);
|
|
437
|
+
await client.call('Input.dispatchMouseEvent', {
|
|
438
|
+
type: 'mouseMoved',
|
|
439
|
+
x: point.x,
|
|
440
|
+
y: point.y,
|
|
441
|
+
});
|
|
442
|
+
await delay(50);
|
|
443
|
+
point = await evaluate(client, pointExpression);
|
|
444
|
+
if (!point) throw new Error(`cannot click ${description}: element moved`);
|
|
445
|
+
await client.call('Input.dispatchMouseEvent', {
|
|
446
|
+
type: 'mousePressed',
|
|
447
|
+
x: point.x,
|
|
448
|
+
y: point.y,
|
|
449
|
+
button: 'left',
|
|
450
|
+
buttons: 1,
|
|
451
|
+
clickCount: 1,
|
|
452
|
+
pointerType: 'mouse',
|
|
453
|
+
});
|
|
454
|
+
await client.call('Input.dispatchMouseEvent', {
|
|
455
|
+
type: 'mouseReleased',
|
|
456
|
+
x: point.x,
|
|
457
|
+
y: point.y,
|
|
458
|
+
button: 'left',
|
|
459
|
+
buttons: 0,
|
|
460
|
+
clickCount: 1,
|
|
461
|
+
pointerType: 'mouse',
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async function pressKey(client, key, code, virtualKeyCode) {
|
|
466
|
+
await client.call('Input.dispatchKeyEvent', {
|
|
467
|
+
type: 'rawKeyDown',
|
|
468
|
+
key,
|
|
469
|
+
code,
|
|
470
|
+
windowsVirtualKeyCode: virtualKeyCode,
|
|
471
|
+
nativeVirtualKeyCode: virtualKeyCode,
|
|
472
|
+
});
|
|
473
|
+
await client.call('Input.dispatchKeyEvent', {
|
|
474
|
+
type: 'keyUp',
|
|
475
|
+
key,
|
|
476
|
+
code,
|
|
477
|
+
windowsVirtualKeyCode: virtualKeyCode,
|
|
478
|
+
nativeVirtualKeyCode: virtualKeyCode,
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function compileBodyPatterns(patterns) {
|
|
483
|
+
return (patterns || []).map((pattern) => (
|
|
484
|
+
pattern instanceof RegExp ? pattern : new RegExp(pattern)
|
|
485
|
+
));
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async function runSubscriber(options) {
|
|
489
|
+
const { subscriber, resolved: subscriberPath } = await loadSubscriber(options.subscriber);
|
|
490
|
+
const configured = await subscriber.configure({
|
|
491
|
+
args: options.subscriberArgs,
|
|
492
|
+
env: process.env,
|
|
493
|
+
apiVersion: SUBSCRIBER_API,
|
|
494
|
+
});
|
|
495
|
+
if (configured?.help) {
|
|
496
|
+
console.log(configured.help);
|
|
497
|
+
return { skipped: true, reason: 'help' };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
const configuredOutputDir = options.outputDir || configured.outputDir || '';
|
|
501
|
+
if (!configuredOutputDir) {
|
|
502
|
+
throw new Error('subscriber must configure outputDir or receive --out');
|
|
503
|
+
}
|
|
504
|
+
const outputDir = await prepareOutputDir(path.resolve(configuredOutputDir));
|
|
505
|
+
const browserBinary = resolveBrowserBinary(options.browserBinary || configured.browserBinary);
|
|
506
|
+
const cookieJar = options.cookieJar || configured.cookieJar || '';
|
|
507
|
+
const cookieDomain = options.cookieDomain || configured.cookieDomain || '';
|
|
508
|
+
const cookieExport = options.cookieExport && configured.cookieExport !== false;
|
|
509
|
+
const bodyPatterns = compileBodyPatterns(configured.responseBodyPatterns);
|
|
510
|
+
const requiredCookieNames = configured.requiredCookieNames || [];
|
|
511
|
+
|
|
512
|
+
const profileDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'glider-headless-'));
|
|
513
|
+
const stderrPath = path.join(outputDir, 'browser.stderr.log');
|
|
514
|
+
const stderrFd = fs.openSync(stderrPath, 'wx', 0o600);
|
|
515
|
+
let browser;
|
|
516
|
+
let client;
|
|
517
|
+
let cookieSource;
|
|
518
|
+
let authenticated = false;
|
|
519
|
+
let primaryError;
|
|
520
|
+
let cleanupError;
|
|
521
|
+
const network = [];
|
|
522
|
+
const requests = new Map();
|
|
523
|
+
const pendingBodyReads = new Set();
|
|
524
|
+
try {
|
|
525
|
+
browser = spawn(browserBinary, [
|
|
526
|
+
'--headless=new',
|
|
527
|
+
'--remote-debugging-pipe',
|
|
528
|
+
`--user-data-dir=${profileDir}`,
|
|
529
|
+
'--no-first-run',
|
|
530
|
+
'--no-default-browser-check',
|
|
531
|
+
'--disable-background-networking',
|
|
532
|
+
'--disable-component-update',
|
|
533
|
+
'--disable-default-apps',
|
|
534
|
+
'--disable-sync',
|
|
535
|
+
'--metrics-recording-only',
|
|
536
|
+
...(configured.browserArgs || []),
|
|
537
|
+
], {
|
|
538
|
+
detached: false,
|
|
539
|
+
stdio: ['ignore', 'ignore', stderrFd, 'pipe', 'pipe'],
|
|
540
|
+
});
|
|
541
|
+
let spawnError;
|
|
542
|
+
browser.once('error', (error) => { spawnError = error; });
|
|
543
|
+
client = new CdpClient(browser.stdio[3], browser.stdio[4]);
|
|
544
|
+
await client.connect();
|
|
545
|
+
await delay(0);
|
|
546
|
+
if (spawnError) throw spawnError;
|
|
547
|
+
const target = await client.call(
|
|
548
|
+
'Target.createTarget',
|
|
549
|
+
{ url: 'about:blank' },
|
|
550
|
+
{ browserCommand: true },
|
|
551
|
+
);
|
|
552
|
+
const attached = await client.call(
|
|
553
|
+
'Target.attachToTarget',
|
|
554
|
+
{ targetId: target.targetId, flatten: true },
|
|
555
|
+
{ browserCommand: true },
|
|
556
|
+
);
|
|
557
|
+
client.useSession(attached.sessionId);
|
|
558
|
+
await Promise.all([
|
|
559
|
+
client.call('Page.enable'),
|
|
560
|
+
client.call('Runtime.enable'),
|
|
561
|
+
client.call('Network.enable', {
|
|
562
|
+
maxTotalBufferSize: 100_000_000,
|
|
563
|
+
maxResourceBufferSize: 10_000_000,
|
|
564
|
+
maxPostDataSize: 10_000_000,
|
|
565
|
+
}),
|
|
566
|
+
]);
|
|
567
|
+
|
|
568
|
+
client.on('Network.requestWillBeSent', (event) => {
|
|
569
|
+
if (event.redirectResponse) {
|
|
570
|
+
const previous = requests.get(event.requestId);
|
|
571
|
+
if (previous) {
|
|
572
|
+
previous.response = {
|
|
573
|
+
status: event.redirectResponse.status,
|
|
574
|
+
statusText: event.redirectResponse.statusText,
|
|
575
|
+
mimeType: event.redirectResponse.mimeType,
|
|
576
|
+
protocol: event.redirectResponse.protocol,
|
|
577
|
+
fromDiskCache: event.redirectResponse.fromDiskCache,
|
|
578
|
+
fromServiceWorker: event.redirectResponse.fromServiceWorker,
|
|
579
|
+
};
|
|
580
|
+
previous.redirectedTo = event.request.url;
|
|
581
|
+
network.push(previous);
|
|
582
|
+
requests.delete(event.requestId);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
requests.set(event.requestId, {
|
|
586
|
+
requestId: event.requestId,
|
|
587
|
+
timestamp: event.timestamp,
|
|
588
|
+
wallTime: event.wallTime,
|
|
589
|
+
type: event.type,
|
|
590
|
+
method: event.request.method,
|
|
591
|
+
url: event.request.url,
|
|
592
|
+
postData: event.request.postData,
|
|
593
|
+
initiator: event.initiator,
|
|
594
|
+
});
|
|
595
|
+
});
|
|
596
|
+
client.on('Network.responseReceived', (event) => {
|
|
597
|
+
const record = requests.get(event.requestId) || {
|
|
598
|
+
requestId: event.requestId,
|
|
599
|
+
url: event.response.url,
|
|
600
|
+
};
|
|
601
|
+
record.response = {
|
|
602
|
+
status: event.response.status,
|
|
603
|
+
statusText: event.response.statusText,
|
|
604
|
+
mimeType: event.response.mimeType,
|
|
605
|
+
protocol: event.response.protocol,
|
|
606
|
+
fromDiskCache: event.response.fromDiskCache,
|
|
607
|
+
fromServiceWorker: event.response.fromServiceWorker,
|
|
608
|
+
};
|
|
609
|
+
requests.set(event.requestId, record);
|
|
610
|
+
});
|
|
611
|
+
client.on('Network.loadingFailed', (event) => {
|
|
612
|
+
const record = requests.get(event.requestId) || { requestId: event.requestId };
|
|
613
|
+
record.failure = {
|
|
614
|
+
errorText: event.errorText,
|
|
615
|
+
canceled: event.canceled,
|
|
616
|
+
blockedReason: event.blockedReason,
|
|
617
|
+
};
|
|
618
|
+
requests.set(event.requestId, record);
|
|
619
|
+
});
|
|
620
|
+
client.on('Network.loadingFinished', (event) => {
|
|
621
|
+
const work = (async () => {
|
|
622
|
+
const record = requests.get(event.requestId);
|
|
623
|
+
if (!record) return;
|
|
624
|
+
if (record.response && bodyPatterns.some((pattern) => pattern.test(record.url || ''))) {
|
|
625
|
+
try {
|
|
626
|
+
const body = await client.call('Network.getResponseBody', {
|
|
627
|
+
requestId: event.requestId,
|
|
628
|
+
});
|
|
629
|
+
record.response.body = body.body;
|
|
630
|
+
record.response.base64Encoded = body.base64Encoded;
|
|
631
|
+
} catch (error) {
|
|
632
|
+
record.response.bodyError = error.message;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
network.push(record);
|
|
636
|
+
requests.delete(event.requestId);
|
|
637
|
+
})();
|
|
638
|
+
pendingBodyReads.add(work);
|
|
639
|
+
work.finally(() => pendingBodyReads.delete(work));
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
if (cookieJar) {
|
|
643
|
+
cookieSource = parseCookieSource(
|
|
644
|
+
await fsp.readFile(cookieJar, 'utf8'),
|
|
645
|
+
cookieDomain,
|
|
646
|
+
);
|
|
647
|
+
await client.call('Network.setCookies', { cookies: cookieSource.cookies });
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const artifactPath = (name) => {
|
|
651
|
+
if (!name || path.basename(name) !== name) {
|
|
652
|
+
throw new Error(`artifact name must be a flat filename: ${name}`);
|
|
653
|
+
}
|
|
654
|
+
const resolved = path.resolve(outputDir, name);
|
|
655
|
+
if (resolved !== outputDir && !resolved.startsWith(`${outputDir}${path.sep}`)) {
|
|
656
|
+
throw new Error(`artifact path escapes output directory: ${name}`);
|
|
657
|
+
}
|
|
658
|
+
return resolved;
|
|
659
|
+
};
|
|
660
|
+
const context = {
|
|
661
|
+
apiVersion: SUBSCRIBER_API,
|
|
662
|
+
subscriberPath,
|
|
663
|
+
outputDir,
|
|
664
|
+
network,
|
|
665
|
+
requests,
|
|
666
|
+
delay,
|
|
667
|
+
cdp: (method, params = {}) => client.call(method, params),
|
|
668
|
+
evaluate: (expression, awaitPromise = true) => evaluate(client, expression, awaitPromise),
|
|
669
|
+
waitFor: (expression, timeoutMs, description) => (
|
|
670
|
+
waitForExpression(client, expression, timeoutMs, description)
|
|
671
|
+
),
|
|
672
|
+
click: (expression, description) => physicalClick(client, expression, description),
|
|
673
|
+
pressKey: (key, code, virtualKeyCode) => pressKey(client, key, code, virtualKeyCode),
|
|
674
|
+
pressTab: () => pressKey(client, 'Tab', 'Tab', 9),
|
|
675
|
+
markAuthenticated: () => { authenticated = true; },
|
|
676
|
+
artifactPath,
|
|
677
|
+
writeArtifact: async (name, value) => {
|
|
678
|
+
const payload = Buffer.isBuffer(value)
|
|
679
|
+
? value
|
|
680
|
+
: typeof value === 'string'
|
|
681
|
+
? value
|
|
682
|
+
: `${JSON.stringify(value, null, 2)}\n`;
|
|
683
|
+
await atomicWrite(artifactPath(name), payload);
|
|
684
|
+
},
|
|
685
|
+
navigate: async (url, waitOptions = {}) => {
|
|
686
|
+
await client.call('Page.navigate', { url });
|
|
687
|
+
await waitForExpression(
|
|
688
|
+
client,
|
|
689
|
+
'document.readyState === "complete"',
|
|
690
|
+
waitOptions.timeoutMs || 60_000,
|
|
691
|
+
waitOptions.description || 'document readiness',
|
|
692
|
+
);
|
|
693
|
+
if (waitOptions.expression) {
|
|
694
|
+
await waitForExpression(
|
|
695
|
+
client,
|
|
696
|
+
waitOptions.expression,
|
|
697
|
+
waitOptions.timeoutMs || 60_000,
|
|
698
|
+
waitOptions.description || 'navigation condition',
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
},
|
|
702
|
+
screenshot: async (name = 'page.png', options = {}) => {
|
|
703
|
+
const screenshot = await client.call('Page.captureScreenshot', {
|
|
704
|
+
format: options.format || 'png',
|
|
705
|
+
captureBeyondViewport: options.captureBeyondViewport !== false,
|
|
706
|
+
fromSurface: true,
|
|
707
|
+
});
|
|
708
|
+
await atomicWrite(
|
|
709
|
+
artifactPath(name),
|
|
710
|
+
Buffer.from(screenshot.data, 'base64'),
|
|
711
|
+
);
|
|
712
|
+
},
|
|
713
|
+
};
|
|
714
|
+
|
|
715
|
+
const result = await subscriber.run(context, configured.subscriberConfig ?? configured);
|
|
716
|
+
await context.writeArtifact('result.json', {
|
|
717
|
+
ok: true,
|
|
718
|
+
subscriber: subscriberPath,
|
|
719
|
+
result: result ?? null,
|
|
720
|
+
});
|
|
721
|
+
return { outputDir, result };
|
|
722
|
+
} catch (error) {
|
|
723
|
+
primaryError = error;
|
|
724
|
+
throw error;
|
|
725
|
+
} finally {
|
|
726
|
+
if (client) {
|
|
727
|
+
await Promise.allSettled([...pendingBodyReads]);
|
|
728
|
+
for (const record of requests.values()) network.push(record);
|
|
729
|
+
try {
|
|
730
|
+
await atomicWrite(
|
|
731
|
+
path.join(outputDir, 'network.json'),
|
|
732
|
+
`${JSON.stringify(network, null, 2)}\n`,
|
|
733
|
+
);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
if (!primaryError) cleanupError = error;
|
|
736
|
+
else console.error(`headless capture warning: ${error.message}`);
|
|
737
|
+
}
|
|
738
|
+
if (authenticated && cookieJar && cookieSource && cookieExport) {
|
|
739
|
+
try {
|
|
740
|
+
const result = await client.call('Network.getAllCookies');
|
|
741
|
+
const allowedDomains = [...new Set(cookieSource.cookies.map((cookie) => cookie.domain))];
|
|
742
|
+
const cookies = result.cookies
|
|
743
|
+
.filter((cookie) => cookieDomainAllowed(cookie.domain, allowedDomains))
|
|
744
|
+
.sort((left, right) => (
|
|
745
|
+
`${left.domain}\t${left.path}\t${left.name}`
|
|
746
|
+
.localeCompare(`${right.domain}\t${right.path}\t${right.name}`)
|
|
747
|
+
));
|
|
748
|
+
for (const requiredName of requiredCookieNames) {
|
|
749
|
+
if (!cookies.some((cookie) => cookie.name === requiredName)) {
|
|
750
|
+
throw new Error(`refusing cookie export without required cookie: ${requiredName}`);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
await atomicWrite(cookieJar, serializeCookies(cookieSource.format, cookies));
|
|
754
|
+
} catch (error) {
|
|
755
|
+
if (!primaryError) cleanupError = error;
|
|
756
|
+
else console.error(`headless cookie export warning: ${error.message}`);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
client.close();
|
|
760
|
+
}
|
|
761
|
+
await stopProcess(browser);
|
|
762
|
+
fs.closeSync(stderrFd);
|
|
763
|
+
await fsp.rm(profileDir, { recursive: true, force: true });
|
|
764
|
+
if (!primaryError && cleanupError) throw cleanupError;
|
|
765
|
+
if (
|
|
766
|
+
!primaryError &&
|
|
767
|
+
browser &&
|
|
768
|
+
browser.exitCode !== 0 &&
|
|
769
|
+
browser.signalCode == null
|
|
770
|
+
) {
|
|
771
|
+
throw new Error(`headless browser exited with code ${browser.exitCode}`);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
async function cmdHeadless(argv) {
|
|
777
|
+
const options = parseRuntimeArgs(argv);
|
|
778
|
+
if (options.action === 'help' || options.action === '--help' || options.action === '-h') {
|
|
779
|
+
console.log(headlessHelp());
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
if (options.action === 'contract') {
|
|
783
|
+
console.log(JSON.stringify({
|
|
784
|
+
apiVersion: SUBSCRIBER_API,
|
|
785
|
+
configure: 'configure({ args, env, apiVersion }) -> runtime configuration',
|
|
786
|
+
run: 'run(context, subscriberConfig) -> JSON-serializable result',
|
|
787
|
+
context: [
|
|
788
|
+
'cdp', 'evaluate', 'waitFor', 'click', 'pressKey', 'pressTab',
|
|
789
|
+
'navigate', 'screenshot', 'writeArtifact', 'markAuthenticated',
|
|
790
|
+
'network', 'requests', 'delay',
|
|
791
|
+
],
|
|
792
|
+
}, null, 2));
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
if (options.action !== 'run' || !options.subscriber) {
|
|
796
|
+
throw new Error(headlessHelp());
|
|
797
|
+
}
|
|
798
|
+
const outcome = await runSubscriber(options);
|
|
799
|
+
if (!outcome.skipped) console.log(outcome.outputDir);
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
module.exports = {
|
|
803
|
+
SUBSCRIBER_API,
|
|
804
|
+
CdpClient,
|
|
805
|
+
atomicWrite,
|
|
806
|
+
cmdHeadless,
|
|
807
|
+
headlessHelp,
|
|
808
|
+
parseCookieSource,
|
|
809
|
+
parseNetscapeCookieJar,
|
|
810
|
+
parseRuntimeArgs,
|
|
811
|
+
prepareOutputDir,
|
|
812
|
+
runSubscriber,
|
|
813
|
+
serializeCookies,
|
|
814
|
+
stopProcess,
|
|
815
|
+
};
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "glidercli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.35",
|
|
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",
|
|
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
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",
|
|
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",
|