glidercli 0.4.32 → 0.4.33

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/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
  }
@@ -4346,7 +4446,7 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
4346
4446
  console.log(` ${GREEN}${'emulate'.padEnd(16)}${NC} ${DIM}tz | geo | viewport | offline | ua | color-scheme${NC}`);
4347
4447
  console.log(` ${GREEN}${'storage'.padEnd(16)}${NC} ${DIM}get | set | delete | keys | jar (localStorage)${NC}`);
4348
4448
  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}`);
4449
+ console.log(` ${GREEN}${'cookie-jar'.padEnd(16)}${NC} ${DIM}sync [domain] | inject <domain> | read | age | list | add | rm | rebuild${NC}`);
4350
4450
  console.log(` ${GREEN}${'history'.padEnd(16)}${NC} ${DIM}back | forward | reload${NC}`);
4351
4451
  console.log(` ${GREEN}${'dialog'.padEnd(16)}${NC} ${DIM}dialog auto accept|dismiss${NC}`);
4352
4452
  console.log(` ${GREEN}${'console'.padEnd(16)}${NC} ${DIM}tail | dump (partial: exits 2 until event streaming lands)${NC}`);
@@ -5644,24 +5744,47 @@ async function cmdCookieWrite(argv) {
5644
5744
  delete: { type: 'string' },
5645
5745
  host: { type: 'string' },
5646
5746
  url: { type: 'string' },
5747
+ 'store-id': { type: 'string' },
5748
+ storeId: { type: 'string' },
5749
+ 'session-id': { type: 'string' },
5750
+ session: { type: 'string' },
5751
+ tab: { type: 'string' },
5752
+ incognito: { type: 'boolean' },
5647
5753
  });
5648
5754
  assertExclusiveFlags(opts, ['set', 'delete']);
5649
5755
  assertExclusiveFlags(opts, ['host', 'url']);
5650
5756
  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)');
5757
+ log.fail('Usage: glider cookies --set NAME=VAL (--host H | --url U) [--store-id|--session-id|--tab|--incognito]');
5758
+ log.fail(' glider cookies --delete NAME (--host H | --url U) [--store-id|--session-id|--tab|--incognito]');
5652
5759
  process.exit(1);
5653
5760
  }
5654
5761
  await _guardAndConnect('cookies-write');
5655
5762
  const cookieUrl = opts.url || (/^https?:\/\//i.test(opts.host) ? opts.host : `https://${opts.host}`);
5763
+ let storeId = null;
5764
+ try {
5765
+ storeId = await resolveCookieStoreId({
5766
+ storeId: opts['store-id'] || opts.storeId,
5767
+ sessionId: opts['session-id'] || opts.session,
5768
+ tabId: opts.tab,
5769
+ incognito: !!opts.incognito,
5770
+ });
5771
+ } catch (e) {
5772
+ log.fail(e.message);
5773
+ process.exit(1);
5774
+ }
5656
5775
  try {
5657
5776
  if (opts.set) {
5658
5777
  const [name, ...rest] = opts.set.split('='); const value = rest.join('=');
5659
5778
  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}`);
5779
+ const params = { url: cookieUrl, name, value };
5780
+ if (storeId) params.storeId = storeId;
5781
+ const r = await httpPost('/extension', { method: 'setCookie', params });
5782
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie set: ${name}@${new URL(cookieUrl).host}${storeId ? ` storeId=${storeId}` : ''}`);
5662
5783
  } 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}`);
5784
+ const params = { url: cookieUrl, name: opts.delete };
5785
+ if (storeId) params.storeId = storeId;
5786
+ const r = await httpPost('/extension', { method: 'removeCookie', params });
5787
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${new URL(cookieUrl).host}${storeId ? ` storeId=${storeId}` : ''}`);
5665
5788
  }
5666
5789
  } catch (e) { log.fail(`cookie write failed: ${e.message}`); process.exit(1); }
5667
5790
  }
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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.4.32",
3
+ "version": "0.4.33",
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"