@ai-ecoverse/sliccy-browser 0.1.37 → 0.1.40
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/package.json +2 -2
- package/src/browser.js +173 -36
- package/src/discover.js +352 -0
- package/src/guard.js +90 -0
- package/src/protected-origins.js +71 -0
- package/src/protected.js +115 -0
- package/src/version.js +1 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-ecoverse/sliccy-browser",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "sliccy:browser for jsh, over CDP",
|
|
3
|
+
"version": "0.1.40",
|
|
4
|
+
"description": "sliccy:browser for jsh, over CDP. Discovers Chrome via SLICC_CDP_URL, slicc browsers --json, DevToolsActivePort under slicc profiles, then 127.0.0.1:9222. Discovered endpoints refuse seven/vault/extension/error pages.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"repository": {
|
package/src/browser.js
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
1
|
import { appendFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { connect } from './connect.js';
|
|
4
|
+
import { resolveCdpEndpoint } from './discover.js';
|
|
4
5
|
import { buildBrowserFetchScript } from './fetch-script.js';
|
|
6
|
+
import {
|
|
7
|
+
dropProtectedCookies,
|
|
8
|
+
isProtectedHost,
|
|
9
|
+
isProtectedUrl,
|
|
10
|
+
REFUSAL,
|
|
11
|
+
refuseProtected,
|
|
12
|
+
} from './guard.js';
|
|
13
|
+
import { version } from './version.js';
|
|
14
|
+
|
|
15
|
+
export { REFUSAL, resolveCdpEndpoint, version };
|
|
5
16
|
|
|
6
17
|
const LOAD_TIMEOUT_MS = 15000;
|
|
7
18
|
const HELD_FRAMES = 100;
|
|
@@ -25,6 +36,7 @@ const RECORDER = `(() => {
|
|
|
25
36
|
})()`;
|
|
26
37
|
|
|
27
38
|
let opening;
|
|
39
|
+
let guarded = false;
|
|
28
40
|
const sessions = new Map();
|
|
29
41
|
const tabsBySession = new Map();
|
|
30
42
|
const sockets = new Map();
|
|
@@ -39,14 +51,52 @@ let idle;
|
|
|
39
51
|
|
|
40
52
|
function openClient() {
|
|
41
53
|
if (!opening) {
|
|
42
|
-
opening =
|
|
54
|
+
opening = openResolved().catch((error) => {
|
|
43
55
|
opening = undefined;
|
|
56
|
+
guarded = false;
|
|
44
57
|
throw error;
|
|
45
58
|
});
|
|
46
59
|
}
|
|
47
60
|
return opening;
|
|
48
61
|
}
|
|
49
62
|
|
|
63
|
+
async function openResolved() {
|
|
64
|
+
const explicit = process.env.SLICC_CDP_URL;
|
|
65
|
+
if (typeof explicit === 'string' && explicit.trim().length > 0) {
|
|
66
|
+
guarded = false;
|
|
67
|
+
return connect();
|
|
68
|
+
}
|
|
69
|
+
const { url } = await resolveCdpEndpoint();
|
|
70
|
+
guarded = true;
|
|
71
|
+
return connect({ url });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function liveInfo(tab) {
|
|
75
|
+
const targetId = targetIdOf(tab);
|
|
76
|
+
const client = await openClient();
|
|
77
|
+
const result = await client.send('Target.getTargets');
|
|
78
|
+
const infos = Array.isArray(result?.targetInfos) ? result.targetInfos : [];
|
|
79
|
+
return (
|
|
80
|
+
infos.find((info) => info && typeof info.targetId === 'string' && info.targetId === targetId) ??
|
|
81
|
+
null
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function urlOf(tab) {
|
|
86
|
+
const info = await liveInfo(tab);
|
|
87
|
+
if (info?.type !== 'page') return '';
|
|
88
|
+
return typeof info.url === 'string' ? info.url : '';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function withGuardedTab(tab, work) {
|
|
92
|
+
await openClient();
|
|
93
|
+
if (!guarded) return work();
|
|
94
|
+
refuseProtected(await urlOf(tab));
|
|
95
|
+
const result = await work();
|
|
96
|
+
refuseProtected(await urlOf(tab));
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
50
100
|
async function using(work) {
|
|
51
101
|
active += 1;
|
|
52
102
|
clearTimeout(idle);
|
|
@@ -69,6 +119,7 @@ function closeIdle() {
|
|
|
69
119
|
if (active > 0 || subscribers.size > 0 || !opening) return;
|
|
70
120
|
const closing = opening;
|
|
71
121
|
opening = undefined;
|
|
122
|
+
guarded = false;
|
|
72
123
|
sessions.clear();
|
|
73
124
|
tabsBySession.clear();
|
|
74
125
|
sockets.clear();
|
|
@@ -136,12 +187,17 @@ function dispatchFrame(message) {
|
|
|
136
187
|
if (targetId === undefined) return;
|
|
137
188
|
const key = socketKey(message.sessionId, params.requestId);
|
|
138
189
|
const url = sockets.get(key);
|
|
139
|
-
if (
|
|
190
|
+
if (typeof url === 'string') {
|
|
191
|
+
route(targetId, url, response.payloadData, () => true);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (guarded) return;
|
|
140
195
|
route(targetId, url, response.payloadData, (sub) => sub.urlMatch === undefined);
|
|
141
196
|
holdFrame(message.sessionId, targetId, key, response.payloadData);
|
|
142
197
|
}
|
|
143
198
|
|
|
144
199
|
function route(targetId, url, raw, which) {
|
|
200
|
+
if (guarded && (typeof url !== 'string' || isProtectedUrl(url))) return;
|
|
145
201
|
for (const sub of subscribers.values()) {
|
|
146
202
|
if (sub.targetId !== targetId || !which(sub) || !urlMatches(sub, url)) continue;
|
|
147
203
|
const body = parseFrame(raw, sub.filter?.parseAs);
|
|
@@ -195,6 +251,7 @@ async function learnUrl(client, message) {
|
|
|
195
251
|
sockets.set(key, url);
|
|
196
252
|
const frames = held.get(key) ?? [];
|
|
197
253
|
held.delete(key);
|
|
254
|
+
if (guarded && isProtectedUrl(url)) return;
|
|
198
255
|
const targetId = tabsBySession.get(sessionId);
|
|
199
256
|
for (const raw of frames) route(targetId, url, raw, (sub) => sub.urlMatch !== undefined);
|
|
200
257
|
}
|
|
@@ -303,16 +360,21 @@ async function findTabNow(query = {}) {
|
|
|
303
360
|
if (domain === undefined && urlMatch === undefined) {
|
|
304
361
|
throw new Error('browser.findTab: query requires `domain` or `urlMatch`');
|
|
305
362
|
}
|
|
363
|
+
await openClient();
|
|
364
|
+
if (guarded && domain !== undefined && isProtectedHost(domain)) throw new Error(REFUSAL);
|
|
306
365
|
const tabs = await listTabs();
|
|
307
366
|
const wanted = domain?.toLowerCase();
|
|
308
367
|
const re = urlMatch === undefined ? undefined : compilePattern(urlMatch, 'browser.findTab');
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
(tab)
|
|
312
|
-
|
|
313
|
-
(re === undefined || re.test(tab.url))
|
|
314
|
-
) ?? null
|
|
368
|
+
const matches = tabs.filter(
|
|
369
|
+
(tab) =>
|
|
370
|
+
(wanted === undefined || hostnameOf(tab.url)?.toLowerCase() === wanted) &&
|
|
371
|
+
(re === undefined || re.test(tab.url))
|
|
315
372
|
);
|
|
373
|
+
if (!guarded) return matches[0] ?? null;
|
|
374
|
+
const allowed = matches.find((tab) => !isProtectedUrl(tab.url));
|
|
375
|
+
if (allowed) return allowed;
|
|
376
|
+
if (matches.length > 0) throw new Error(REFUSAL);
|
|
377
|
+
return null;
|
|
316
378
|
}
|
|
317
379
|
|
|
318
380
|
export async function ensureTab(url, options) {
|
|
@@ -323,16 +385,20 @@ async function ensureTabNow(url, options = {}) {
|
|
|
323
385
|
if (typeof url !== 'string' || url.length === 0) {
|
|
324
386
|
throw new TypeError('browser.ensureTab: url must be a string');
|
|
325
387
|
}
|
|
388
|
+
await openClient();
|
|
389
|
+
if (guarded) refuseProtected(url);
|
|
326
390
|
const tabs = await listTabs();
|
|
327
391
|
const matchUrl = patternOf(options.matchUrl);
|
|
328
392
|
if (matchUrl !== undefined) {
|
|
329
393
|
const re = compilePattern(matchUrl, 'browser.ensureTab');
|
|
330
|
-
const hit = tabs.find((tab) => re.test(tab.url));
|
|
394
|
+
const hit = tabs.find((tab) => re.test(tab.url) && (!guarded || !isProtectedUrl(tab.url)));
|
|
331
395
|
if (hit) return hit;
|
|
332
396
|
} else {
|
|
333
397
|
const wanted = originOf(url);
|
|
334
398
|
if (wanted) {
|
|
335
|
-
const hit = tabs.find(
|
|
399
|
+
const hit = tabs.find(
|
|
400
|
+
(tab) => originOf(tab.url) === wanted && (!guarded || !isProtectedUrl(tab.url))
|
|
401
|
+
);
|
|
336
402
|
if (hit) return hit;
|
|
337
403
|
}
|
|
338
404
|
}
|
|
@@ -346,10 +412,18 @@ async function ensureTabNow(url, options = {}) {
|
|
|
346
412
|
throw new Error('Target.createTarget returned no targetId');
|
|
347
413
|
}
|
|
348
414
|
const { sessionId } = await sessionFor(targetId);
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
415
|
+
try {
|
|
416
|
+
if (url === 'about:blank') await waitForLoad(client, sessionId);
|
|
417
|
+
else await navigateAndWait(client, sessionId, url);
|
|
418
|
+
const live = (await listTabs()).find((tab) => tab.targetId === targetId);
|
|
419
|
+
if (guarded) refuseProtected(live?.url ?? '');
|
|
420
|
+
return live ?? { targetId, url, title: '' };
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (guarded) {
|
|
423
|
+
await client.send('Target.closeTarget', { targetId }).catch(() => undefined);
|
|
424
|
+
}
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
353
427
|
}
|
|
354
428
|
|
|
355
429
|
function evalSource(tab, source) {
|
|
@@ -367,21 +441,23 @@ function evaluate(tab, source, awaitPromise, decodeJson = true) {
|
|
|
367
441
|
}
|
|
368
442
|
|
|
369
443
|
async function evaluateNow(tab, source, awaitPromise, decodeJson) {
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
444
|
+
return withGuardedTab(tab, async () => {
|
|
445
|
+
const { client, sessionId } = await sessionFor(targetIdOf(tab));
|
|
446
|
+
const result = await client.send(
|
|
447
|
+
'Runtime.evaluate',
|
|
448
|
+
{
|
|
449
|
+
expression: serializeEvalSource(source),
|
|
450
|
+
returnByValue: true,
|
|
451
|
+
awaitPromise,
|
|
452
|
+
},
|
|
453
|
+
sessionId
|
|
454
|
+
);
|
|
455
|
+
if (result?.exceptionDetails) {
|
|
456
|
+
throw new Error(exceptionMessage(result.exceptionDetails));
|
|
457
|
+
}
|
|
458
|
+
const value = result?.result?.value;
|
|
459
|
+
return decodeJson ? unwrapEvalResult(value) : value;
|
|
460
|
+
});
|
|
385
461
|
}
|
|
386
462
|
|
|
387
463
|
export async function cookie(tab, name) {
|
|
@@ -390,11 +466,15 @@ export async function cookie(tab, name) {
|
|
|
390
466
|
}
|
|
391
467
|
|
|
392
468
|
async function cookieNow(tab, name) {
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
469
|
+
return withGuardedTab(tab, async () => {
|
|
470
|
+
const { client, sessionId } = await sessionFor(targetIdOf(tab));
|
|
471
|
+
const params = guarded ? { urls: [await urlOf(tab)] } : {};
|
|
472
|
+
const result = await client.send('Network.getCookies', params, sessionId);
|
|
473
|
+
const cookies = Array.isArray(result?.cookies) ? result.cookies : [];
|
|
474
|
+
const visible = guarded ? dropProtectedCookies(cookies) : cookies;
|
|
475
|
+
const hit = visible.find((item) => item && item.name === name);
|
|
476
|
+
return hit && typeof hit.value === 'string' ? hit.value : null;
|
|
477
|
+
});
|
|
398
478
|
}
|
|
399
479
|
|
|
400
480
|
export async function localStorage(tab, key) {
|
|
@@ -409,10 +489,64 @@ export async function localStorage(tab, key) {
|
|
|
409
489
|
return typeof raw === 'string' ? raw : String(raw);
|
|
410
490
|
}
|
|
411
491
|
|
|
492
|
+
function resolveFetchUrl(url, base) {
|
|
493
|
+
try {
|
|
494
|
+
return new URL(url, base).href;
|
|
495
|
+
} catch {
|
|
496
|
+
throw new TypeError(
|
|
497
|
+
`browser.fetch: could not resolve ${JSON.stringify(url)} against ${JSON.stringify(base)}`
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function baseUriOf(tab) {
|
|
503
|
+
const { client, sessionId } = await sessionFor(targetIdOf(tab));
|
|
504
|
+
const result = await client.send(
|
|
505
|
+
'Runtime.evaluate',
|
|
506
|
+
{ expression: 'document.baseURI', returnByValue: true },
|
|
507
|
+
sessionId
|
|
508
|
+
);
|
|
509
|
+
if (result?.exceptionDetails) {
|
|
510
|
+
throw new Error(exceptionMessage(result.exceptionDetails));
|
|
511
|
+
}
|
|
512
|
+
const value = result?.result?.value;
|
|
513
|
+
return typeof value === 'string' ? value : '';
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async function evaluateFetchScript(tab, script) {
|
|
517
|
+
const { client, sessionId } = await sessionFor(targetIdOf(tab));
|
|
518
|
+
const result = await client.send(
|
|
519
|
+
'Runtime.evaluate',
|
|
520
|
+
{
|
|
521
|
+
expression: serializeEvalSource(script),
|
|
522
|
+
returnByValue: true,
|
|
523
|
+
awaitPromise: true,
|
|
524
|
+
},
|
|
525
|
+
sessionId
|
|
526
|
+
);
|
|
527
|
+
if (result?.exceptionDetails) {
|
|
528
|
+
throw new Error(exceptionMessage(result.exceptionDetails));
|
|
529
|
+
}
|
|
530
|
+
return unwrapEvalResult(result?.result?.value);
|
|
531
|
+
}
|
|
532
|
+
|
|
412
533
|
export async function fetch(tab, url, opts = {}) {
|
|
413
534
|
if (typeof url !== 'string') throw new TypeError('browser.fetch: url must be a string');
|
|
414
|
-
|
|
415
|
-
|
|
535
|
+
return using(async () => {
|
|
536
|
+
await openClient();
|
|
537
|
+
if (!guarded) {
|
|
538
|
+
const script = await buildBrowserFetchScript(url, opts);
|
|
539
|
+
return evaluateFetchScript(tab, script);
|
|
540
|
+
}
|
|
541
|
+
return withGuardedTab(tab, async () => {
|
|
542
|
+
const baseURI = await baseUriOf(tab);
|
|
543
|
+
refuseProtected(baseURI);
|
|
544
|
+
const absolute = resolveFetchUrl(url, baseURI);
|
|
545
|
+
refuseProtected(absolute);
|
|
546
|
+
const script = await buildBrowserFetchScript(absolute, opts);
|
|
547
|
+
return evaluateFetchScript(tab, script);
|
|
548
|
+
});
|
|
549
|
+
});
|
|
416
550
|
}
|
|
417
551
|
|
|
418
552
|
function serializeEvalSource(source) {
|
|
@@ -642,6 +776,8 @@ export const websocket = {
|
|
|
642
776
|
},
|
|
643
777
|
};
|
|
644
778
|
async function subscribe(sink) {
|
|
779
|
+
await openClient();
|
|
780
|
+
if (guarded) refuseProtected(await urlOf(tab));
|
|
645
781
|
const urlMatchRe =
|
|
646
782
|
urlMatch === undefined ? undefined : compilePattern(urlMatch, 'browser.websocket');
|
|
647
783
|
const { sessionId } = await sessionFor(targetId);
|
|
@@ -673,6 +809,7 @@ export const websocket = {
|
|
|
673
809
|
};
|
|
674
810
|
|
|
675
811
|
const browser = {
|
|
812
|
+
version,
|
|
676
813
|
findTab,
|
|
677
814
|
ensureTab,
|
|
678
815
|
eval: evalSource,
|
package/src/discover.js
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
const CLI_TIMEOUT_MS = 1500;
|
|
6
|
+
const CLI_MAX_STDOUT = 1_000_000;
|
|
7
|
+
const PROBE_TIMEOUT_MS = 500;
|
|
8
|
+
const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
|
|
9
|
+
const FALLBACK_PORT = 9222;
|
|
10
|
+
|
|
11
|
+
function nonempty(value) {
|
|
12
|
+
if (typeof value !== 'string') return undefined;
|
|
13
|
+
const trimmed = value.trim();
|
|
14
|
+
if (trimmed.length === 0) return undefined;
|
|
15
|
+
return trimmed;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function isRecord(value) {
|
|
19
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function loopbackHost(host) {
|
|
23
|
+
const name = String(host ?? '')
|
|
24
|
+
.toLowerCase()
|
|
25
|
+
.replace(/^\[|\]$/gu, '');
|
|
26
|
+
return name === '127.0.0.1' || name === 'localhost' || name === '::1';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function acceptLoopbackWs(url, expectedPort) {
|
|
30
|
+
let parsed;
|
|
31
|
+
try {
|
|
32
|
+
parsed = new URL(url);
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
if (parsed.protocol !== 'ws:') return false;
|
|
37
|
+
if (!loopbackHost(parsed.hostname)) return false;
|
|
38
|
+
const port = parsed.port === '' ? 80 : Number(parsed.port);
|
|
39
|
+
return Number.isInteger(port) && port === expectedPort;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function joinParts(parts) {
|
|
43
|
+
return path.join(...parts);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function configDir(env, platform) {
|
|
47
|
+
const home = nonempty(env.HOME) ?? os.homedir();
|
|
48
|
+
if (platform === 'darwin') {
|
|
49
|
+
return joinParts([home, 'Library', 'Application Support']);
|
|
50
|
+
}
|
|
51
|
+
if (platform === 'win32') {
|
|
52
|
+
return nonempty(env.APPDATA) ?? joinParts([home, 'AppData', 'Roaming']);
|
|
53
|
+
}
|
|
54
|
+
const xdg = nonempty(env.XDG_CONFIG_HOME);
|
|
55
|
+
if (xdg && path.isAbsolute(xdg)) return xdg;
|
|
56
|
+
return joinParts([home, '.config']);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sixProfilesRoot(env, platform) {
|
|
60
|
+
const home = nonempty(env.HOME) ?? os.homedir();
|
|
61
|
+
if (platform === 'darwin') {
|
|
62
|
+
return joinParts([home, 'Library', 'Application Support', 'Slicc', 'profiles']);
|
|
63
|
+
}
|
|
64
|
+
if (platform === 'win32') {
|
|
65
|
+
const local = nonempty(env.LOCALAPPDATA) ?? joinParts([home, 'AppData', 'Local']);
|
|
66
|
+
return joinParts([local, 'Slicc', 'profiles']);
|
|
67
|
+
}
|
|
68
|
+
const xdg = nonempty(env.XDG_STATE_HOME);
|
|
69
|
+
if (xdg && path.isAbsolute(xdg)) return joinParts([xdg, 'slicc', 'profiles']);
|
|
70
|
+
return joinParts([home, '.local', 'state', 'slicc', 'profiles']);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function sliccProfileRoots(options = {}) {
|
|
74
|
+
const env = options.env ?? process.env;
|
|
75
|
+
const platform = options.platform ?? process.platform;
|
|
76
|
+
const config = configDir(env, platform);
|
|
77
|
+
return [
|
|
78
|
+
joinParts([config, 'slicc', 'seven-profiles']),
|
|
79
|
+
joinParts([config, 'slicc', 'profiles']),
|
|
80
|
+
sixProfilesRoot(env, platform),
|
|
81
|
+
];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function isSliccUserDataDir(dir) {
|
|
85
|
+
if (typeof dir !== 'string' || dir.length === 0) return false;
|
|
86
|
+
const normalized = dir.replaceAll('\\', '/');
|
|
87
|
+
return (
|
|
88
|
+
normalized.includes('/slicc/seven-profiles/') ||
|
|
89
|
+
normalized.includes('/slicc/profiles/') ||
|
|
90
|
+
normalized.includes('/Slicc/profiles/') ||
|
|
91
|
+
/\/slicc\/seven-profiles$/u.test(normalized) ||
|
|
92
|
+
/\/slicc\/profiles$/u.test(normalized) ||
|
|
93
|
+
/\/Slicc\/profiles$/u.test(normalized)
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function portFromCdp(cdp) {
|
|
98
|
+
if (typeof cdp !== 'string') return undefined;
|
|
99
|
+
try {
|
|
100
|
+
const parsed = new URL(cdp);
|
|
101
|
+
if (!loopbackHost(parsed.hostname)) return undefined;
|
|
102
|
+
const port =
|
|
103
|
+
parsed.port === '' ? (parsed.protocol === 'https:' ? 443 : 80) : Number(parsed.port);
|
|
104
|
+
return Number.isInteger(port) ? port : undefined;
|
|
105
|
+
} catch {
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function endpointCandidates(entries) {
|
|
111
|
+
if (!Array.isArray(entries)) return [];
|
|
112
|
+
const out = [];
|
|
113
|
+
for (const entry of entries) {
|
|
114
|
+
if (!isRecord(entry) || entry.kind !== 'endpoint' || !isRecord(entry.endpoint)) continue;
|
|
115
|
+
const { endpoint } = entry;
|
|
116
|
+
const ws = endpoint.webSocketDebuggerUrl;
|
|
117
|
+
const port = portFromCdp(endpoint.cdp);
|
|
118
|
+
if (typeof ws !== 'string' || port === undefined) continue;
|
|
119
|
+
if (!acceptLoopbackWs(ws, port)) continue;
|
|
120
|
+
const tier = Number.isInteger(entry.tier) ? entry.tier : 99;
|
|
121
|
+
out.push({
|
|
122
|
+
url: ws,
|
|
123
|
+
sevenOpen: endpoint.sevenOpen === true,
|
|
124
|
+
sliccProfile:
|
|
125
|
+
(typeof endpoint.profile === 'string' && endpoint.profile.length > 0) ||
|
|
126
|
+
isSliccUserDataDir(endpoint.userDataDir),
|
|
127
|
+
tier,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function pickCliEndpoint(entries) {
|
|
134
|
+
const candidates = endpointCandidates(entries);
|
|
135
|
+
if (candidates.length === 0) return undefined;
|
|
136
|
+
candidates.sort((left, right) => {
|
|
137
|
+
if (left.sevenOpen !== right.sevenOpen) return left.sevenOpen ? -1 : 1;
|
|
138
|
+
if (left.sliccProfile !== right.sliccProfile) return left.sliccProfile ? -1 : 1;
|
|
139
|
+
return left.tier - right.tier;
|
|
140
|
+
});
|
|
141
|
+
return candidates[0].url;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function loadSpawn() {
|
|
145
|
+
const mod = await import('node:child_process');
|
|
146
|
+
return mod.spawn;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function runSliccBrowsers(options) {
|
|
150
|
+
let spawnImpl = options.spawn;
|
|
151
|
+
if (spawnImpl === undefined) {
|
|
152
|
+
try {
|
|
153
|
+
spawnImpl = await (options.loadSpawn ?? loadSpawn)();
|
|
154
|
+
} catch (error) {
|
|
155
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
156
|
+
return { ok: false, reason: `child_process unavailable (${message})` };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const timeoutMs = options.cliTimeoutMs ?? CLI_TIMEOUT_MS;
|
|
160
|
+
const maxBytes = options.cliMaxStdout ?? CLI_MAX_STDOUT;
|
|
161
|
+
const env = options.env ?? process.env;
|
|
162
|
+
return new Promise((resolve) => {
|
|
163
|
+
let child;
|
|
164
|
+
try {
|
|
165
|
+
child = spawnImpl('slicc', ['browsers', '--json'], {
|
|
166
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
167
|
+
env,
|
|
168
|
+
shell: false,
|
|
169
|
+
windowsHide: true,
|
|
170
|
+
});
|
|
171
|
+
} catch (error) {
|
|
172
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
173
|
+
resolve({ ok: false, reason: `spawn failed (${message})` });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
let settled = false;
|
|
177
|
+
let stdout = Buffer.alloc(0);
|
|
178
|
+
let oversized = false;
|
|
179
|
+
const finish = (result) => {
|
|
180
|
+
if (settled) return;
|
|
181
|
+
settled = true;
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
resolve(result);
|
|
184
|
+
};
|
|
185
|
+
const timer = setTimeout(() => {
|
|
186
|
+
oversized = true;
|
|
187
|
+
child.kill('SIGKILL');
|
|
188
|
+
finish({ ok: false, reason: `timed out after ${timeoutMs}ms` });
|
|
189
|
+
}, timeoutMs);
|
|
190
|
+
child.on('error', (error) => {
|
|
191
|
+
if (error && error.code === 'ENOENT') {
|
|
192
|
+
finish({ ok: false, reason: 'slicc not on PATH' });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
196
|
+
finish({ ok: false, reason: `spawn error (${message})` });
|
|
197
|
+
});
|
|
198
|
+
child.stdout.on('data', (chunk) => {
|
|
199
|
+
if (settled || oversized) return;
|
|
200
|
+
stdout = Buffer.concat([stdout, chunk]);
|
|
201
|
+
if (stdout.length > maxBytes) {
|
|
202
|
+
oversized = true;
|
|
203
|
+
child.kill('SIGKILL');
|
|
204
|
+
finish({ ok: false, reason: 'stdout exceeded size cap' });
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
child.on('close', (code) => {
|
|
208
|
+
if (settled) return;
|
|
209
|
+
if (code !== 0) {
|
|
210
|
+
finish({ ok: false, reason: `exited ${code ?? 'null'}` });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
let value;
|
|
214
|
+
try {
|
|
215
|
+
value = JSON.parse(stdout.toString('utf8'));
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
218
|
+
finish({ ok: false, reason: `invalid JSON (${message})` });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (!isRecord(value) || value.schema !== 1 || !Array.isArray(value.entries)) {
|
|
222
|
+
finish({ ok: false, reason: 'schema 1 document missing or invalid' });
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const url = pickCliEndpoint(value.entries);
|
|
226
|
+
if (url === undefined) {
|
|
227
|
+
finish({ ok: false, reason: 'no usable loopback endpoint' });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
finish({ ok: true, url });
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function readActivePort(file) {
|
|
236
|
+
const text = await readFile(file, 'utf8');
|
|
237
|
+
const lines = text.split(/\r?\n/u);
|
|
238
|
+
const port = Number(lines[0]?.trim());
|
|
239
|
+
const wsPath = lines[1]?.trim();
|
|
240
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined;
|
|
241
|
+
if (typeof wsPath !== 'string' || !wsPath.startsWith('/')) return undefined;
|
|
242
|
+
return { port, wsPath };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function probeVersion(fetchImpl, port, timeoutMs) {
|
|
246
|
+
const controller = new AbortController();
|
|
247
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
248
|
+
try {
|
|
249
|
+
const response = await fetchImpl(`http://127.0.0.1:${port}/json/version`, {
|
|
250
|
+
signal: controller.signal,
|
|
251
|
+
redirect: 'manual',
|
|
252
|
+
headers: { accept: 'application/json' },
|
|
253
|
+
});
|
|
254
|
+
if (!response.ok) return undefined;
|
|
255
|
+
const body = await response.text();
|
|
256
|
+
let value;
|
|
257
|
+
try {
|
|
258
|
+
value = JSON.parse(body);
|
|
259
|
+
} catch {
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
const url = isRecord(value) ? value.webSocketDebuggerUrl : undefined;
|
|
263
|
+
if (typeof url !== 'string' || !acceptLoopbackWs(url, port)) return undefined;
|
|
264
|
+
return url;
|
|
265
|
+
} catch {
|
|
266
|
+
return undefined;
|
|
267
|
+
} finally {
|
|
268
|
+
clearTimeout(timer);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async function collectActivePorts(roots) {
|
|
273
|
+
const found = [];
|
|
274
|
+
for (const root of roots) {
|
|
275
|
+
let entries;
|
|
276
|
+
try {
|
|
277
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
278
|
+
} catch {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
for (const entry of entries) {
|
|
282
|
+
if (!entry.isDirectory()) continue;
|
|
283
|
+
if (!PROFILE_NAME.test(entry.name)) continue;
|
|
284
|
+
const file = path.join(root, entry.name, 'DevToolsActivePort');
|
|
285
|
+
try {
|
|
286
|
+
const active = await readActivePort(file);
|
|
287
|
+
if (active === undefined) continue;
|
|
288
|
+
const mtimeMs = (await stat(file)).mtimeMs;
|
|
289
|
+
found.push({ ...active, file, mtimeMs });
|
|
290
|
+
} catch {}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return found;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function fromDevToolsActivePort(options) {
|
|
297
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
298
|
+
const timeoutMs = options.probeTimeoutMs ?? PROBE_TIMEOUT_MS;
|
|
299
|
+
const roots = options.profileRoots ?? sliccProfileRoots(options);
|
|
300
|
+
const files = await collectActivePorts(roots);
|
|
301
|
+
files.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
|
302
|
+
for (const item of files) {
|
|
303
|
+
const url = await probeVersion(fetchImpl, item.port, timeoutMs);
|
|
304
|
+
if (url === undefined) continue;
|
|
305
|
+
if (new URL(url).pathname !== item.wsPath) continue;
|
|
306
|
+
return { ok: true, url };
|
|
307
|
+
}
|
|
308
|
+
if (files.length === 0) {
|
|
309
|
+
return { ok: false, reason: 'no DevToolsActivePort files under slicc profile dirs' };
|
|
310
|
+
}
|
|
311
|
+
return { ok: false, reason: 'no live DevToolsActivePort (stale or rejected websocket URL)' };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function fromFallback(options) {
|
|
315
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
316
|
+
const timeoutMs = options.probeTimeoutMs ?? PROBE_TIMEOUT_MS;
|
|
317
|
+
const url = await probeVersion(fetchImpl, FALLBACK_PORT, timeoutMs);
|
|
318
|
+
if (url !== undefined) return { ok: true, url };
|
|
319
|
+
return { ok: false, reason: 'no answer on /json/version' };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export async function resolveCdpEndpoint(options = {}) {
|
|
323
|
+
const env = options.env ?? process.env;
|
|
324
|
+
const tried = [];
|
|
325
|
+
const explicit = nonempty(env.SLICC_CDP_URL);
|
|
326
|
+
if (explicit !== undefined) {
|
|
327
|
+
return { url: explicit, tried: ['SLICC_CDP_URL: set'] };
|
|
328
|
+
}
|
|
329
|
+
tried.push('SLICC_CDP_URL: not set');
|
|
330
|
+
|
|
331
|
+
const cli = await runSliccBrowsers({ ...options, env });
|
|
332
|
+
if (cli.ok) {
|
|
333
|
+
tried.push('slicc browsers --json: chose a loopback endpoint');
|
|
334
|
+
return { url: cli.url, tried };
|
|
335
|
+
}
|
|
336
|
+
tried.push(`slicc browsers --json: ${cli.reason}`);
|
|
337
|
+
|
|
338
|
+
const active = await fromDevToolsActivePort({ ...options, env });
|
|
339
|
+
if (active.ok) {
|
|
340
|
+
tried.push('DevToolsActivePort: chose a live loopback port');
|
|
341
|
+
return { url: active.url, tried };
|
|
342
|
+
}
|
|
343
|
+
tried.push(`DevToolsActivePort: ${active.reason}`);
|
|
344
|
+
|
|
345
|
+
const fallback = await fromFallback(options);
|
|
346
|
+
if (fallback.ok) {
|
|
347
|
+
tried.push(`127.0.0.1:${FALLBACK_PORT}: answered`);
|
|
348
|
+
return { url: fallback.url, tried };
|
|
349
|
+
}
|
|
350
|
+
tried.push(`127.0.0.1:${FALLBACK_PORT}: ${fallback.reason}`);
|
|
351
|
+
throw new Error(`no debugger is connected\n${tried.map((line) => `- ${line}`).join('\n')}\n`);
|
|
352
|
+
}
|
package/src/guard.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { protectedOrigins } from './protected.js';
|
|
2
|
+
import { PROTECTED_ORIGINS } from './protected-origins.js';
|
|
3
|
+
|
|
4
|
+
export const REFUSAL = PROTECTED_ORIGINS.refusal;
|
|
5
|
+
|
|
6
|
+
const guard = protectedOrigins(PROTECTED_ORIGINS);
|
|
7
|
+
|
|
8
|
+
function under(host, domain) {
|
|
9
|
+
return host === domain || host.endsWith(`.${domain}`);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function inheritingAbout(text) {
|
|
13
|
+
if (typeof text !== 'string') return false;
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(text);
|
|
16
|
+
if (url.protocol !== 'about:') return false;
|
|
17
|
+
return PROTECTED_ORIGINS.inheriting.includes(`about:${url.pathname.toLowerCase()}`);
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function hostOf(text) {
|
|
24
|
+
const host = new URL(text).hostname.toLowerCase();
|
|
25
|
+
return host.endsWith('.') ? host.slice(0, -1) : host;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function asHttp(text) {
|
|
29
|
+
try {
|
|
30
|
+
const url = new URL(text);
|
|
31
|
+
if (url.protocol === 'ws:') url.protocol = 'http:';
|
|
32
|
+
else if (url.protocol === 'wss:') url.protocol = 'https:';
|
|
33
|
+
return url.href;
|
|
34
|
+
} catch {
|
|
35
|
+
return text;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isProtectedHost(host) {
|
|
40
|
+
if (typeof host !== 'string' || host.length === 0) return true;
|
|
41
|
+
const name = host.toLowerCase().replace(/\.$/u, '');
|
|
42
|
+
if (PROTECTED_ORIGINS.hosts.includes(name)) return true;
|
|
43
|
+
return PROTECTED_ORIGINS.domains.some((domain) => under(name, domain));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isProtectedUrl(text) {
|
|
47
|
+
if (typeof text !== 'string' || text.length === 0) return true;
|
|
48
|
+
if (inheritingAbout(text)) return true;
|
|
49
|
+
if (
|
|
50
|
+
typeof PROTECTED_ORIGINS.errorPage?.url === 'string' &&
|
|
51
|
+
text === PROTECTED_ORIGINS.errorPage.url
|
|
52
|
+
) {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
if (text.startsWith('chrome-error:')) return true;
|
|
56
|
+
const mapped = asHttp(text);
|
|
57
|
+
return guard.url(text) || (mapped !== text && guard.url(mapped));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function siteProtected(site) {
|
|
61
|
+
if (typeof site !== 'string' || site.length === 0) return true;
|
|
62
|
+
if (isProtectedUrl(site)) return true;
|
|
63
|
+
const host = hostOf(site);
|
|
64
|
+
return host.length > 0 && guard.cookieDomain(host);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function cookieProtected(cookie) {
|
|
68
|
+
if (!cookie || typeof cookie !== 'object') return true;
|
|
69
|
+
if (typeof cookie.domain === 'string' && guard.cookieDomain(cookie.domain)) return true;
|
|
70
|
+
if (typeof cookie.url === 'string') {
|
|
71
|
+
if (isProtectedUrl(cookie.url)) return true;
|
|
72
|
+
const host = hostOf(cookie.url);
|
|
73
|
+
if (host.length > 0 && guard.cookieDomain(host)) return true;
|
|
74
|
+
}
|
|
75
|
+
const key = cookie.partitionKey;
|
|
76
|
+
if (typeof key === 'string') return siteProtected(key);
|
|
77
|
+
if (key && typeof key === 'object' && typeof key.topLevelSite === 'string') {
|
|
78
|
+
return siteProtected(key.topLevelSite);
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function dropProtectedCookies(cookies) {
|
|
84
|
+
if (!Array.isArray(cookies)) return [];
|
|
85
|
+
return cookies.filter((cookie) => !cookieProtected(cookie));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function refuseProtected(text) {
|
|
89
|
+
if (isProtectedUrl(text)) throw new Error(REFUSAL);
|
|
90
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export const PROTECTED_ORIGINS = {
|
|
2
|
+
domains: ['sliccy.ai'],
|
|
3
|
+
hosts: ['vault.sliccy.ai'],
|
|
4
|
+
schemes: ['https', 'http'],
|
|
5
|
+
innerSchemes: ['blob', 'filesystem', 'view-source'],
|
|
6
|
+
anySchemes: ['devtools'],
|
|
7
|
+
protectedSchemes: [
|
|
8
|
+
'chrome',
|
|
9
|
+
'chrome-untrusted',
|
|
10
|
+
'chrome-search',
|
|
11
|
+
'chrome-native',
|
|
12
|
+
'chrome-distiller',
|
|
13
|
+
'chrome-experimental-site-token-provider',
|
|
14
|
+
'isolated-app',
|
|
15
|
+
'externalfile',
|
|
16
|
+
'content',
|
|
17
|
+
'chrome-extension',
|
|
18
|
+
'devtools',
|
|
19
|
+
'edge',
|
|
20
|
+
'brave',
|
|
21
|
+
'opera',
|
|
22
|
+
'vivaldi',
|
|
23
|
+
'arc',
|
|
24
|
+
'file',
|
|
25
|
+
],
|
|
26
|
+
schemeExceptions: [
|
|
27
|
+
'chrome://newtab',
|
|
28
|
+
'chrome://new-tab-page',
|
|
29
|
+
'chrome-untrusted://new-tab-page',
|
|
30
|
+
'edge://newtab',
|
|
31
|
+
'brave://newtab',
|
|
32
|
+
'opera://startpage',
|
|
33
|
+
],
|
|
34
|
+
aboutScheme: 'chrome',
|
|
35
|
+
targetTypes: ['browser_ui'],
|
|
36
|
+
inheriting: ['about:blank', 'about:srcdoc'],
|
|
37
|
+
errorPage: {
|
|
38
|
+
url: 'chrome-error://chromewebdata/',
|
|
39
|
+
target: 'previous',
|
|
40
|
+
redact: 'origin',
|
|
41
|
+
},
|
|
42
|
+
unparseable: 'protected',
|
|
43
|
+
unparseableRefusal: "slicc: refused: slicc can't parse this URL, so it could be a protected page",
|
|
44
|
+
extensionFrames: {
|
|
45
|
+
schemes: ['chrome-extension'],
|
|
46
|
+
whenShown: [
|
|
47
|
+
'Page.captureScreenshot',
|
|
48
|
+
'Input.dispatchKeyEvent',
|
|
49
|
+
'Input.dispatchMouseEvent',
|
|
50
|
+
'Input.dispatchTouchEvent',
|
|
51
|
+
'Input.dispatchDragEvent',
|
|
52
|
+
'Input.emulateTouchFromMouseEvent',
|
|
53
|
+
'Input.insertText',
|
|
54
|
+
'Input.imeSetComposition',
|
|
55
|
+
'Input.synthesizePinchGesture',
|
|
56
|
+
'Input.synthesizeScrollGesture',
|
|
57
|
+
'Input.synthesizeTapGesture',
|
|
58
|
+
],
|
|
59
|
+
whilePresent: [
|
|
60
|
+
'Page.captureSnapshot',
|
|
61
|
+
'Page.printToPDF',
|
|
62
|
+
'Page.startScreencast',
|
|
63
|
+
'HeadlessExperimental.beginFrame',
|
|
64
|
+
],
|
|
65
|
+
shownRefusal:
|
|
66
|
+
"slicc: refused: a browser extension's frame (chrome-extension://) is showing or focused in this tab, such as a password manager's autofill list; close it or reload the tab",
|
|
67
|
+
presentRefusal:
|
|
68
|
+
"slicc: refused: this tab holds a browser extension's frame (chrome-extension://), such as a password manager's autofill list, so it can't be captured whole or streamed; reload the tab to remove it; an active screencast is stopped or its frames are dropped until the frame is gone",
|
|
69
|
+
},
|
|
70
|
+
refusal: "slicc: refused: target is on seven's origin",
|
|
71
|
+
};
|
package/src/protected.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
const parse = (text) => {
|
|
2
|
+
if (typeof text !== 'string') return null;
|
|
3
|
+
try {
|
|
4
|
+
return new URL(text);
|
|
5
|
+
} catch {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const scheme = (u) => u.protocol.slice(0, -1);
|
|
11
|
+
|
|
12
|
+
const hostOf = (u) => {
|
|
13
|
+
const h = u.hostname.toLowerCase();
|
|
14
|
+
return h.endsWith('.') ? h.slice(0, -1) : h;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const originOf = (u) => {
|
|
18
|
+
if (!u?.host) return null;
|
|
19
|
+
return `${scheme(u)}://${hostOf(u)}${u.port ? `:${u.port}` : ''}`;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const under = (host, domain) => host === domain || host.endsWith(`.${domain}`);
|
|
23
|
+
|
|
24
|
+
export function protectedOrigins(rules, extraOrigins = []) {
|
|
25
|
+
const extra = extraOrigins.map((o) => originOf(parse(o))).filter(Boolean);
|
|
26
|
+
const extraHosts = extraOrigins
|
|
27
|
+
.map((o) => parse(o))
|
|
28
|
+
.filter((u) => u?.host)
|
|
29
|
+
.map(hostOf);
|
|
30
|
+
|
|
31
|
+
const unwrap = (u) => {
|
|
32
|
+
for (let i = 0; u && rules.innerSchemes.includes(scheme(u)) && i < 8; i += 1) {
|
|
33
|
+
u = parse(u.href.slice(u.protocol.length));
|
|
34
|
+
}
|
|
35
|
+
return u;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const alias = (u) => {
|
|
39
|
+
if (!u || scheme(u) !== 'about' || !rules.aboutScheme) return u;
|
|
40
|
+
if (rules.inheriting.includes(`about:${u.pathname.toLowerCase()}`)) return u;
|
|
41
|
+
return parse(`${rules.aboutScheme}://${u.pathname}${u.search}${u.hash}`) ?? u;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const exempt = (text) => text === '' || text === 'null' || text === '://';
|
|
45
|
+
const failed = (u) => !u || rules.innerSchemes.includes(scheme(u));
|
|
46
|
+
const unparseable = (text) => !exempt(text) && failed(unwrap(parse(text)));
|
|
47
|
+
|
|
48
|
+
const url = (text, { readOnly = false } = {}) => {
|
|
49
|
+
const u = alias(unwrap(parse(text)));
|
|
50
|
+
if (failed(u)) return rules.unparseable === 'protected' && !readOnly && !exempt(text);
|
|
51
|
+
const s = scheme(u);
|
|
52
|
+
if (rules.anySchemes.includes(s)) return true;
|
|
53
|
+
if ((rules.protectedSchemes ?? []).includes(s))
|
|
54
|
+
return !(rules.schemeExceptions ?? []).includes(`${s}://${hostOf(u)}`);
|
|
55
|
+
if (rules.schemes.includes(s) && rules.hosts.includes(hostOf(u))) return true;
|
|
56
|
+
if (rules.schemes.includes(s) && rules.domains.some((d) => under(hostOf(u), d))) return true;
|
|
57
|
+
const o = originOf(u);
|
|
58
|
+
return o !== null && extra.includes(o);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const inheriting = (text) => {
|
|
62
|
+
if (text === '') return true;
|
|
63
|
+
const u = parse(text);
|
|
64
|
+
return (
|
|
65
|
+
u !== null &&
|
|
66
|
+
scheme(u) === 'about' &&
|
|
67
|
+
rules.inheriting.includes(`about:${u.pathname.toLowerCase()}`)
|
|
68
|
+
);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const target = ({
|
|
72
|
+
url: text,
|
|
73
|
+
previous = false,
|
|
74
|
+
opener,
|
|
75
|
+
type,
|
|
76
|
+
documentURL,
|
|
77
|
+
unreachableURL,
|
|
78
|
+
navigating = false,
|
|
79
|
+
}) => {
|
|
80
|
+
if (type && (rules.targetTypes ?? []).includes(type)) return true;
|
|
81
|
+
if (
|
|
82
|
+
rules.errorPage &&
|
|
83
|
+
documentURL === rules.errorPage.url &&
|
|
84
|
+
unreachableURL === text &&
|
|
85
|
+
!navigating
|
|
86
|
+
)
|
|
87
|
+
return previous;
|
|
88
|
+
if (inheriting(text)) return previous || opener === 'protected' || opener === 'unknown';
|
|
89
|
+
return url(text);
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const cookieDomain = (domain) => {
|
|
93
|
+
let d = domain.toLowerCase();
|
|
94
|
+
if (d.startsWith('.')) d = d.slice(1);
|
|
95
|
+
if (d.endsWith('.')) d = d.slice(0, -1);
|
|
96
|
+
if (d === '') return false;
|
|
97
|
+
if (rules.domains.some((x) => under(d, x))) return true;
|
|
98
|
+
return [...rules.domains, ...rules.hosts, ...extraHosts].some((h) => under(h, d));
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const storageKey = (key) => {
|
|
102
|
+
const [first, ...rest] = key.split('^');
|
|
103
|
+
return [first, ...rest.filter((p) => p.startsWith('0')).map((p) => p.slice(1))].some((text) =>
|
|
104
|
+
url(text, { readOnly: true })
|
|
105
|
+
);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const extensionFrame = (text) => {
|
|
109
|
+
const u = parse(text);
|
|
110
|
+
if (!u || !(rules.extensionFrames?.schemes ?? []).includes(scheme(u))) return false;
|
|
111
|
+
return !extra.includes(originOf(u));
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return { url, target, cookieDomain, storageKey, unparseable, extensionFrame };
|
|
115
|
+
}
|
package/src/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const version = '0.1.40';
|