glidercli 0.4.32 → 0.4.34

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 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 |
@@ -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 cloud mode |
256
+ | | remote headless workers |
241
257
  | | task chaining |
242
258
 
243
259
  ---
package/bin/glider.js CHANGED
@@ -3335,11 +3335,14 @@ async function cmdCookies(opts = []) {
3335
3335
  else if (a === '--header' || a === '--as-header') asHeader = true;
3336
3336
  else if (a === '--help') {
3337
3337
  console.log('Usage: glider cookies <url> | --host <h> | --url <u> [--name <n>] [--value] [--header] [--json]');
3338
+ console.log(' glider cookies --set NAME=VAL (--host H | --url U) [--store-id|--session-id|--tab|--incognito]');
3339
+ console.log(' glider cookies --delete NAME (--host H | --url U) [--store-id|--session-id|--tab|--incognito]');
3338
3340
  console.log(' Read cookies (INCLUDING HttpOnly) for a URL via the extension cookies API.');
3339
3341
  console.log(' --host <h> convenience: expands to https://<h>/');
3340
3342
  console.log(' --name <n> filter to a single cookie by exact name');
3341
3343
  console.log(' --value print full cookie value (default: masked)');
3342
3344
  console.log(' --header emit as "Cookie: k=v; k=v" header line');
3345
+ console.log(' Write uses chrome.cookies.set/remove; pin store with --incognito / --session-id for Incognito.');
3343
3346
  return;
3344
3347
  }
3345
3348
  else if (!a.startsWith('-')) positional.push(a);
@@ -3448,12 +3451,14 @@ function maskCookieValue(v) {
3448
3451
  return s.slice(0, 12) + '...(' + (s.length - 20) + ' chars)...' + s.slice(-6);
3449
3452
  }
3450
3453
 
3451
- async function fetchExtensionCookieHeaderLine(host) {
3454
+ async function fetchExtensionCookies(host, storeId = null) {
3452
3455
  const url = /^https?:\/\//i.test(host) ? host : `https://${host}/`;
3453
3456
  if (!await ensureConnected()) process.exit(1);
3457
+ const params = { url };
3458
+ if (storeId != null && storeId !== '') params.storeId = String(storeId);
3454
3459
  const payload = await httpPost('/extension', {
3455
3460
  method: 'getCookies',
3456
- params: { url },
3461
+ params,
3457
3462
  });
3458
3463
  if (!payload || payload.error) {
3459
3464
  throw new Error(payload?.error || 'no response from extension');
@@ -3461,25 +3466,101 @@ async function fetchExtensionCookieHeaderLine(host) {
3461
3466
  let cookies = payload.data || payload.result?.cookies || payload.cookies || [];
3462
3467
  if (!Array.isArray(cookies)) throw new Error('unexpected response shape from extension');
3463
3468
  const nowSec = Math.floor(Date.now() / 1000);
3464
- const line = cookies
3465
- .filter((c) => !c.expirationDate || c.expirationDate >= nowSec)
3466
- .map((c) => `${c.name}=${c.value}`)
3467
- .join('; ');
3468
- return line;
3469
+ const live = cookies.filter((c) => !c.expirationDate || c.expirationDate >= nowSec);
3470
+ const header = live.map((c) => `${c.name}=${c.value}`).join('; ');
3471
+ return { header, cookies: live };
3472
+ }
3473
+
3474
+ async function fetchExtensionCookieHeaderLine(host) {
3475
+ const { header } = await fetchExtensionCookies(host);
3476
+ return header;
3477
+ }
3478
+
3479
+ async function listExtensionCookieStores() {
3480
+ const payload = await httpPost('/extension', { method: 'listCookieStores', params: {} });
3481
+ if (!payload || payload.error) {
3482
+ throw new Error(payload?.error || 'listCookieStores failed (reload CRX for listCookieStores)');
3483
+ }
3484
+ const stores = payload.stores || payload.result?.stores || payload.data || [];
3485
+ if (!Array.isArray(stores)) throw new Error('unexpected listCookieStores shape');
3486
+ return stores;
3487
+ }
3488
+
3489
+ /** Resolve chrome.cookies storeId from --store-id | --session-id | --tab | --incognito. */
3490
+ async function resolveCookieStoreId(opts = {}) {
3491
+ if (opts.storeId != null && opts.storeId !== '') return String(opts.storeId);
3492
+
3493
+ let tabId = opts.tabId != null && opts.tabId !== '' ? Number(opts.tabId) : null;
3494
+ if ((opts.sessionId || opts.incognito) && tabId == null) {
3495
+ try {
3496
+ const catalog = await httpGet('/catalog');
3497
+ const pages = catalog?.pages || [];
3498
+ const windows = catalog?.windows || [];
3499
+ if (opts.sessionId) {
3500
+ const page = pages.find((p) => p.sessionId === opts.sessionId);
3501
+ if (page?.tabId != null && page.tabId !== '') tabId = Number(page.tabId);
3502
+ if (tabId == null) {
3503
+ for (const w of windows) {
3504
+ for (const t of w.tabs || []) {
3505
+ if (t.sessionId === opts.sessionId && t.tabId != null && t.tabId !== '') {
3506
+ tabId = Number(t.tabId);
3507
+ break;
3508
+ }
3509
+ }
3510
+ if (tabId != null) break;
3511
+ }
3512
+ }
3513
+ }
3514
+ if (opts.incognito && tabId == null) {
3515
+ for (const w of windows) {
3516
+ if (!w.incognito) continue;
3517
+ const t = (w.tabs || []).find((x) => x.tabId != null && x.tabId !== '');
3518
+ if (t) { tabId = Number(t.tabId); break; }
3519
+ }
3520
+ }
3521
+ } catch (_) { /* fall through to stores */ }
3522
+ }
3523
+
3524
+ const stores = await listExtensionCookieStores();
3525
+ if (tabId != null && !Number.isNaN(tabId)) {
3526
+ const hit = stores.find((s) => Array.isArray(s.tabIds) && s.tabIds.map(Number).includes(tabId));
3527
+ if (hit) return String(hit.id);
3528
+ throw new Error(`no cookie store contains tabId=${tabId}`);
3529
+ }
3530
+ if (opts.incognito) {
3531
+ const hit = stores.find((s) => !!s.incognito);
3532
+ if (hit) return String(hit.id);
3533
+ throw new Error('no incognito cookie store (open an Incognito window first)');
3534
+ }
3535
+ return null; // default store
3469
3536
  }
3470
3537
 
3471
3538
  async function cmdCookieJar(opts = []) {
3472
3539
  const cj = require(path.join(LIB_DIR, 'cookie-jar.js'));
3473
3540
  const sub = opts[0] || 'sync';
3474
- const arg = opts[1];
3475
- const fetchLive = (domain) => fetchExtensionCookieHeaderLine(domain);
3541
+ const rest = opts.slice(1);
3542
+ const flagOpts = {};
3543
+ const positionals = [];
3544
+ for (let i = 0; i < rest.length; i++) {
3545
+ const a = rest[i];
3546
+ if (a === '--store-id' || a === '--storeId') flagOpts.storeId = rest[++i];
3547
+ else if (a === '--session-id' || a === '--session') flagOpts.sessionId = rest[++i];
3548
+ else if (a === '--tab' || a === '--tab-id') flagOpts.tabId = rest[++i];
3549
+ else if (a === '--incognito') flagOpts.incognito = true;
3550
+ else if (!a.startsWith('-')) positionals.push(a);
3551
+ }
3552
+ const arg = positionals[0];
3553
+
3554
+ const fetchLive = async (domain) => fetchExtensionCookies(domain);
3476
3555
 
3477
3556
  if (sub === '--help' || sub === '-h' || sub === 'help') {
3478
3557
  console.log('Usage: glider cookie-jar sync [domain] | read <domain> | age <domain> | list | add <domain> | rm <domain> | rebuild');
3558
+ console.log(' glider cookie-jar inject <domain> [--store-id ID | --session-id SID | --tab TABID | --incognito]');
3559
+ console.log(' inject: write jar cookies into a Chromium cookie store (Incognito needs --incognito or --session-id)');
3479
3560
  return;
3480
3561
  }
3481
3562
 
3482
- const needsRelay = new Set(['sync', 'read']);
3563
+ const needsRelay = new Set(['sync', 'read', 'inject']);
3483
3564
  if (needsRelay.has(sub)) {
3484
3565
  if (!await checkServer()) {
3485
3566
  log.info('Server not running, starting...');
@@ -3500,12 +3581,31 @@ async function cmdCookieJar(opts = []) {
3500
3581
  }
3501
3582
  return;
3502
3583
  }
3584
+ if (sub === 'inject') {
3585
+ if (!arg) {
3586
+ log.fail('Usage: glider cookie-jar inject <domain> [--store-id ID | --session-id SID | --tab TABID | --incognito]');
3587
+ process.exit(1);
3588
+ }
3589
+ const storeId = await resolveCookieStoreId(flagOpts);
3590
+ const setCookieFn = async (details) => {
3591
+ const r = await httpPost('/extension', { method: 'setCookie', params: details });
3592
+ if (r && r.error) throw new Error(r.error);
3593
+ return r?.cookie || r?.result?.cookie || r;
3594
+ };
3595
+ const r = await cj.injectDomain(arg, setCookieFn, { storeId });
3596
+ if (jsonOutput) emitJson(true, r);
3597
+ else log.ok(`injected ${r.count} cookie(s) for ${r.domain}${storeId ? ` storeId=${storeId}` : ' (default store)'}`);
3598
+ return;
3599
+ }
3503
3600
  if (sub === 'read') {
3504
3601
  if (!arg) {
3505
3602
  log.fail('Usage: glider cookie-jar read <domain>');
3506
3603
  process.exit(1);
3507
3604
  }
3508
- const line = await cj.readDomain(arg, fetchLive, (msg) => log.warn(msg));
3605
+ const line = await cj.readDomain(arg, async (d) => {
3606
+ const { header } = await fetchExtensionCookies(d);
3607
+ return header;
3608
+ }, (msg) => log.warn(msg));
3509
3609
  console.log(line);
3510
3610
  return;
3511
3611
  }
@@ -3547,10 +3647,10 @@ async function cmdCookieJar(opts = []) {
3547
3647
  console.log(`rebuilt ${r.path}: ${r.count} domain(s)`);
3548
3648
  return;
3549
3649
  }
3550
- log.fail(`unknown: ${sub}. try: sync|read|age|list|add|rm|rebuild`);
3650
+ log.fail(`unknown: ${sub}. try: sync|read|inject|age|list|add|rm|rebuild`);
3551
3651
  process.exit(1);
3552
3652
  } catch (e) {
3553
- if (e.code === 'SYNC_EMPTY' || e.code === 'READ_MISS') log.fail(e.message);
3653
+ if (e.code === 'SYNC_EMPTY' || e.code === 'READ_MISS' || e.code === 'INJECT_MISS' || e.code === 'INJECT_EMPTY') log.fail(e.message);
3554
3654
  else log.fail(e.message);
3555
3655
  process.exit(1);
3556
3656
  }
@@ -4236,6 +4336,9 @@ ${B5}EXTRACTION PATTERNS${NC} ${DIM}(bulletproof, domain-agnostic)${NC}
4236
4336
  ${B5}AUTOMATION${NC}
4237
4337
  ${BW}run${NC} <task.yaml> Execute YAML task file
4238
4338
  ${BW}loop${NC} <task.yaml> Loop until marker
4339
+ ${BW}headless run${NC} <subscriber.mjs> -- [args]
4340
+ Run a versioned subscriber in an isolated Chromium profile
4341
+ ${BW}headless contract${NC} Print the subscriber API contract
4239
4342
 
4240
4343
  ${B5}EXAMPLES${NC}
4241
4344
  ${DIM}$${NC} glider install ${DIM}# one-time setup${NC}
@@ -4277,6 +4380,7 @@ ${YELLOW}RALPH WIGGUM PATTERN:${NC}
4277
4380
  ${YELLOW}REQUIREMENTS:${NC}
4278
4381
  - Node.js 18+
4279
4382
  - Glider extension from Chrome Web Store connected in a Chromium browser
4383
+ - Headless subscribers use a local Chromium binary and do not require the extension
4280
4384
 
4281
4385
  ${YELLOW}DOMAIN EXTENSIONS:${NC}
4282
4386
  Add custom domain commands via $GLIDER/config/domains.json:
@@ -4346,7 +4450,7 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
4346
4450
  console.log(` ${GREEN}${'emulate'.padEnd(16)}${NC} ${DIM}tz | geo | viewport | offline | ua | color-scheme${NC}`);
4347
4451
  console.log(` ${GREEN}${'storage'.padEnd(16)}${NC} ${DIM}get | set | delete | keys | jar (localStorage)${NC}`);
4348
4452
  console.log(` ${GREEN}${'cookies'.padEnd(16)}${NC} ${DIM}(read: no flags) | --set NAME=VAL --host H | --delete NAME --host H${NC}`);
4349
- console.log(` ${GREEN}${'cookie-jar'.padEnd(16)}${NC} ${DIM}sync [domain] | read | age | list | add | rm | rebuild${NC}`);
4453
+ console.log(` ${GREEN}${'cookie-jar'.padEnd(16)}${NC} ${DIM}sync [domain] | inject <domain> | read | age | list | add | rm | rebuild${NC}`);
4350
4454
  console.log(` ${GREEN}${'history'.padEnd(16)}${NC} ${DIM}back | forward | reload${NC}`);
4351
4455
  console.log(` ${GREEN}${'dialog'.padEnd(16)}${NC} ${DIM}dialog auto accept|dismiss${NC}`);
4352
4456
  console.log(` ${GREEN}${'console'.padEnd(16)}${NC} ${DIM}tail | dump (partial: exits 2 until event streaming lands)${NC}`);
@@ -5644,24 +5748,47 @@ async function cmdCookieWrite(argv) {
5644
5748
  delete: { type: 'string' },
5645
5749
  host: { type: 'string' },
5646
5750
  url: { type: 'string' },
5751
+ 'store-id': { type: 'string' },
5752
+ storeId: { type: 'string' },
5753
+ 'session-id': { type: 'string' },
5754
+ session: { type: 'string' },
5755
+ tab: { type: 'string' },
5756
+ incognito: { type: 'boolean' },
5647
5757
  });
5648
5758
  assertExclusiveFlags(opts, ['set', 'delete']);
5649
5759
  assertExclusiveFlags(opts, ['host', 'url']);
5650
5760
  if ((!opts.host && !opts.url) || (!opts.set && !opts.delete)) {
5651
- log.fail('Usage: glider cookies --set NAME=VAL (--host H | --url U) | --delete NAME (--host H | --url U)');
5761
+ log.fail('Usage: glider cookies --set NAME=VAL (--host H | --url U) [--store-id|--session-id|--tab|--incognito]');
5762
+ log.fail(' glider cookies --delete NAME (--host H | --url U) [--store-id|--session-id|--tab|--incognito]');
5652
5763
  process.exit(1);
5653
5764
  }
5654
5765
  await _guardAndConnect('cookies-write');
5655
5766
  const cookieUrl = opts.url || (/^https?:\/\//i.test(opts.host) ? opts.host : `https://${opts.host}`);
5767
+ let storeId = null;
5768
+ try {
5769
+ storeId = await resolveCookieStoreId({
5770
+ storeId: opts['store-id'] || opts.storeId,
5771
+ sessionId: opts['session-id'] || opts.session,
5772
+ tabId: opts.tab,
5773
+ incognito: !!opts.incognito,
5774
+ });
5775
+ } catch (e) {
5776
+ log.fail(e.message);
5777
+ process.exit(1);
5778
+ }
5656
5779
  try {
5657
5780
  if (opts.set) {
5658
5781
  const [name, ...rest] = opts.set.split('='); const value = rest.join('=');
5659
5782
  if (!name || rest.length === 0) throw new Error('--set expects NAME=VALUE');
5660
- const r = await httpPost('/extension', { method: 'setCookie', params: { url: cookieUrl, name, value } });
5661
- if (jsonOutput) emitJson(true, r); else log.ok(`cookie set: ${name}@${new URL(cookieUrl).host}`);
5783
+ const params = { url: cookieUrl, name, value };
5784
+ if (storeId) params.storeId = storeId;
5785
+ const r = await httpPost('/extension', { method: 'setCookie', params });
5786
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie set: ${name}@${new URL(cookieUrl).host}${storeId ? ` storeId=${storeId}` : ''}`);
5662
5787
  } else if (opts.delete) {
5663
- const r = await httpPost('/extension', { method: 'removeCookie', params: { url: cookieUrl, name: opts.delete } });
5664
- if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${new URL(cookieUrl).host}`);
5788
+ const params = { url: cookieUrl, name: opts.delete };
5789
+ if (storeId) params.storeId = storeId;
5790
+ const r = await httpPost('/extension', { method: 'removeCookie', params });
5791
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${new URL(cookieUrl).host}${storeId ? ` storeId=${storeId}` : ''}`);
5665
5792
  }
5666
5793
  } catch (e) { log.fail(`cookie write failed: ${e.message}`); process.exit(1); }
5667
5794
  }
@@ -5708,7 +5835,7 @@ async function main() {
5708
5835
 
5709
5836
  const relayIndependent = new Set([
5710
5837
  'help', '--help', '-h', 'update', 'version', '-v', '--version',
5711
- 'config', 'domains', 'resolve', 'cookie-jar',
5838
+ 'config', 'domains', 'resolve', 'cookie-jar', 'headless',
5712
5839
  ]);
5713
5840
  if (relayConfigError && !relayIndependent.has(cmd)) {
5714
5841
  throw relayConfigError;
@@ -5726,7 +5853,7 @@ async function main() {
5726
5853
  'start', 'stop', 'restart', 'status', 'test', 'doctor', 'heal', 'connect',
5727
5854
  'install', 'uninstall', 'config',
5728
5855
  'help', '--help', '-h', 'update', 'version', '-v', '--version',
5729
- 'domains', 'resolve', 'cookie-jar',
5856
+ 'domains', 'resolve', 'cookie-jar', 'headless',
5730
5857
  ]);
5731
5858
  if (!noRelayPreflight.has(cmd)) {
5732
5859
  if (!await checkServer()) {
@@ -5942,6 +6069,9 @@ async function main() {
5942
6069
  case 'cookie-jar':
5943
6070
  await cmdCookieJar(args.slice(1));
5944
6071
  break;
6072
+ case 'headless':
6073
+ await require(path.join(LIB_DIR, 'headless-runtime.js')).cmdHeadless(args.slice(1));
6074
+ break;
5945
6075
  case 'spawn':
5946
6076
  await cmdSpawn(args.slice(1));
5947
6077
  break;
package/lib/cookie-jar.js CHANGED
@@ -18,6 +18,116 @@ function parseHeaderLine(raw) {
18
18
  return '';
19
19
  }
20
20
 
21
+ /** Split a Cookie header into [{name,value}, ...]. */
22
+ function parseHeaderPairs(raw) {
23
+ const line = parseHeaderLine(raw);
24
+ if (!line) return [];
25
+ const out = [];
26
+ for (const part of line.split(';')) {
27
+ const p = part.trim();
28
+ if (!p) continue;
29
+ const eq = p.indexOf('=');
30
+ if (eq <= 0) continue;
31
+ out.push({ name: p.slice(0, eq).trim(), value: p.slice(eq + 1) });
32
+ }
33
+ return out;
34
+ }
35
+
36
+ function jarCookiesPath(domain) {
37
+ return path.join(domainDir(domain), 'cookies.json');
38
+ }
39
+
40
+ function jarUrlForDomain(domain) {
41
+ if (/^https?:\/\//i.test(domain)) return domain.endsWith('/') ? domain : `${domain}/`;
42
+ return `https://${domain}/`;
43
+ }
44
+
45
+ /**
46
+ * Build chrome.cookies.set details list for inject.
47
+ * Prefers cookies.json (full attrs). Falls back to header.txt pairs.
48
+ */
49
+ function buildInjectDetails(domain, opts = {}) {
50
+ const storeId = opts.storeId;
51
+ const url = jarUrlForDomain(domain);
52
+ const fullPath = jarCookiesPath(domain);
53
+ if (fs.existsSync(fullPath)) {
54
+ let arr;
55
+ try {
56
+ arr = JSON.parse(fs.readFileSync(fullPath, 'utf8'));
57
+ } catch {
58
+ arr = null;
59
+ }
60
+ if (Array.isArray(arr) && arr.length) {
61
+ return arr.map((c) => {
62
+ const details = {
63
+ url: c.url || url,
64
+ name: c.name,
65
+ value: c.value ?? '',
66
+ };
67
+ for (const k of ['domain', 'path', 'secure', 'httpOnly', 'sameSite', 'expirationDate']) {
68
+ if (c[k] !== undefined && c[k] !== null) details[k] = c[k];
69
+ }
70
+ // chrome.cookies.set rejects sameSite "unspecified"
71
+ if (details.sameSite === 'unspecified') delete details.sameSite;
72
+ if (storeId != null && storeId !== '') details.storeId = String(storeId);
73
+ return details;
74
+ }).filter((d) => d.name);
75
+ }
76
+ }
77
+ const headerPath = path.join(domainDir(domain), 'header.txt');
78
+ if (!fs.existsSync(headerPath)) {
79
+ const err = new Error(`${domain}: no cookies.json or header.txt in jar`);
80
+ err.code = 'INJECT_MISS';
81
+ throw err;
82
+ }
83
+ const pairs = parseHeaderPairs(fs.readFileSync(headerPath, 'utf8'));
84
+ if (!pairs.length) {
85
+ const err = new Error(`${domain}: empty jar header`);
86
+ err.code = 'INJECT_EMPTY';
87
+ throw err;
88
+ }
89
+ return pairs.map(({ name, value }) => {
90
+ const details = {
91
+ url,
92
+ name,
93
+ value,
94
+ secure: true,
95
+ path: '/',
96
+ };
97
+ // common session cookies are HttpOnly in the live jar
98
+ if (name === 'auth_token' || name === 'ct0' || name === 'twid') details.httpOnly = name !== 'ct0';
99
+ if (name === 'ct0') details.httpOnly = false;
100
+ if (storeId != null && storeId !== '') details.storeId = String(storeId);
101
+ return details;
102
+ });
103
+ }
104
+
105
+ /**
106
+ * Persist full chrome.cookies.getAll rows beside header.txt.
107
+ * Enables lossless inject (HttpOnly / SameSite / domain / path).
108
+ */
109
+ function writeCookiesJson(domain, cookies) {
110
+ fs.mkdirSync(domainDir(domain), { recursive: true });
111
+ const list = Array.isArray(cookies) ? cookies : [];
112
+ fs.writeFileSync(jarCookiesPath(domain), `${JSON.stringify(list, null, 2)}\n`);
113
+ return list.length;
114
+ }
115
+
116
+ /**
117
+ * Inject jar into a cookie store via setCookieFn(details) => Promise.
118
+ * setCookieFn must call extension chrome.cookies.set.
119
+ */
120
+ async function injectDomain(domain, setCookieFn, opts = {}) {
121
+ const detailsList = buildInjectDetails(domain, opts);
122
+ const results = [];
123
+ for (const details of detailsList) {
124
+ // eslint-disable-next-line no-await-in-loop
125
+ const cookie = await setCookieFn(details);
126
+ results.push({ name: details.name, ok: !!cookie, storeId: details.storeId || null });
127
+ }
128
+ return { domain, count: results.length, storeId: opts.storeId || null, results };
129
+ }
130
+
21
131
  function domainDir(domain) {
22
132
  return path.join(cookiesDirRoot(), domain);
23
133
  }
@@ -123,11 +233,20 @@ function markStale(domain) {
123
233
  async function syncOne(domain, fetchLive) {
124
234
  fs.mkdirSync(domainDir(domain), { recursive: true });
125
235
  let hdr = '';
236
+ let cookies = null;
126
237
  if (fetchLive) {
127
238
  try {
128
- hdr = parseHeaderLine(await fetchLive(domain));
239
+ const live = await fetchLive(domain);
240
+ // fetchLive may return header string OR { header, cookies }
241
+ if (live && typeof live === 'object' && !Array.isArray(live)) {
242
+ hdr = parseHeaderLine(live.header || '');
243
+ cookies = Array.isArray(live.cookies) ? live.cookies : null;
244
+ } else {
245
+ hdr = parseHeaderLine(live);
246
+ }
129
247
  } catch {
130
248
  hdr = '';
249
+ cookies = null;
131
250
  }
132
251
  }
133
252
  if (!hdr) {
@@ -137,6 +256,7 @@ async function syncOne(domain, fetchLive) {
137
256
  throw err;
138
257
  }
139
258
  fs.writeFileSync(path.join(domainDir(domain), 'header.txt'), hdr);
259
+ if (cookies) writeCookiesJson(domain, cookies);
140
260
  const count = writeMeta(domain, hdr);
141
261
  return { domain, count };
142
262
  }
@@ -220,6 +340,11 @@ function rmDomain(domain) {
220
340
 
221
341
  module.exports = {
222
342
  parseHeaderLine,
343
+ parseHeaderPairs,
344
+ buildInjectDetails,
345
+ writeCookiesJson,
346
+ injectDomain,
347
+ jarUrlForDomain,
223
348
  rebuildDomains,
224
349
  syncOne,
225
350
  syncAll,
@@ -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.32",
3
+ "version": "0.4.34",
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",