@ai-ecoverse/sliccy-browser 0.1.45 → 0.1.46
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 +64 -5
- package/src/dialogs.js +364 -0
- package/src/socket.js +241 -0
- package/src/version.js +1 -1
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. Discovers Chrome via SLICC_CDP_URL, slicc browsers --json, DevToolsActivePort under slicc profiles (live /json/version must match the file's websocket path), then 127.0.0.1:9222. Discovered endpoints refuse seven/vault/extension/error pages; pre-attach websocket frames are dropped with a one-time warning.",
|
|
3
|
+
"version": "0.1.46",
|
|
4
|
+
"description": "sliccy:browser for jsh, over CDP. Discovers Chrome via SLICC_CDP_URL, slicc browsers --json, DevToolsActivePort under slicc profiles (live /json/version must match the file's websocket path), then 127.0.0.1:9222. Discovered endpoints refuse seven/vault/extension/error pages; pre-attach websocket frames are dropped with a one-time warning. Holds a dialog session on each tab it attaches to, so a page's alert, confirm or prompt is answered instead of freezing the tab.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"repository": {
|
package/src/browser.js
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import { appendFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { connect } from './connect.js';
|
|
4
|
+
import {
|
|
5
|
+
blocked,
|
|
6
|
+
clearHandler,
|
|
7
|
+
dialogs as dialogRecords,
|
|
8
|
+
refusal as dialogRefusal,
|
|
9
|
+
hold,
|
|
10
|
+
report,
|
|
11
|
+
setHandler,
|
|
12
|
+
} from './dialogs.js';
|
|
4
13
|
import { resolveCdpEndpoint } from './discover.js';
|
|
5
14
|
import { buildBrowserFetchScript } from './fetch-script.js';
|
|
6
15
|
import {
|
|
@@ -39,6 +48,7 @@ const RECORDER = `(() => {
|
|
|
39
48
|
|
|
40
49
|
let opening;
|
|
41
50
|
let guarded = false;
|
|
51
|
+
let endpoint;
|
|
42
52
|
const sessions = new Map();
|
|
43
53
|
const tabsBySession = new Map();
|
|
44
54
|
const sockets = new Map();
|
|
@@ -66,10 +76,12 @@ async function openResolved() {
|
|
|
66
76
|
const explicit = process.env.SLICC_CDP_URL;
|
|
67
77
|
if (typeof explicit === 'string' && explicit.trim().length > 0) {
|
|
68
78
|
guarded = false;
|
|
79
|
+
endpoint = explicit.trim();
|
|
69
80
|
return connect();
|
|
70
81
|
}
|
|
71
82
|
const { url } = await resolveCdpEndpoint();
|
|
72
83
|
guarded = true;
|
|
84
|
+
endpoint = url;
|
|
73
85
|
return connect({ url });
|
|
74
86
|
}
|
|
75
87
|
|
|
@@ -92,13 +104,24 @@ async function urlOf(tab) {
|
|
|
92
104
|
|
|
93
105
|
async function withGuardedTab(tab, work) {
|
|
94
106
|
await openClient();
|
|
95
|
-
if (!guarded) return work
|
|
107
|
+
if (!guarded) return targeting(tab, work);
|
|
96
108
|
refuseProtected(await urlOf(tab));
|
|
97
|
-
const result = await work
|
|
109
|
+
const result = await targeting(tab, work);
|
|
98
110
|
refuseProtected(await urlOf(tab));
|
|
99
111
|
return result;
|
|
100
112
|
}
|
|
101
113
|
|
|
114
|
+
async function targeting(tab, work) {
|
|
115
|
+
const targetId = targetIdOf(tab);
|
|
116
|
+
report(targetId);
|
|
117
|
+
if (await blocked(targetId, () => urlOf(tab))) throw new Error(dialogRefusal(targetId));
|
|
118
|
+
try {
|
|
119
|
+
return await work();
|
|
120
|
+
} finally {
|
|
121
|
+
report(targetId);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
102
125
|
async function using(work) {
|
|
103
126
|
active += 1;
|
|
104
127
|
clearTimeout(idle);
|
|
@@ -146,7 +169,10 @@ function ignoreMethod(prefix) {
|
|
|
146
169
|
async function sessionFor(targetId) {
|
|
147
170
|
const client = await openClient();
|
|
148
171
|
const cached = sessions.get(targetId);
|
|
149
|
-
if (cached)
|
|
172
|
+
if (cached) {
|
|
173
|
+
await hold(endpoint, targetId);
|
|
174
|
+
return { client, sessionId: cached };
|
|
175
|
+
}
|
|
150
176
|
listen(client);
|
|
151
177
|
const sessionId = await client.attach(targetId);
|
|
152
178
|
tabsBySession.set(sessionId, targetId);
|
|
@@ -157,6 +183,7 @@ async function sessionFor(targetId) {
|
|
|
157
183
|
networkless.set(sessionId, error.message);
|
|
158
184
|
});
|
|
159
185
|
sessions.set(targetId, sessionId);
|
|
186
|
+
await hold(endpoint, targetId);
|
|
160
187
|
return { client, sessionId };
|
|
161
188
|
}
|
|
162
189
|
|
|
@@ -551,7 +578,7 @@ export async function fetch(tab, url, opts = {}) {
|
|
|
551
578
|
await openClient();
|
|
552
579
|
if (!guarded) {
|
|
553
580
|
const script = await buildBrowserFetchScript(url, opts);
|
|
554
|
-
return evaluateFetchScript(tab, script);
|
|
581
|
+
return targeting(tab, () => evaluateFetchScript(tab, script));
|
|
555
582
|
}
|
|
556
583
|
return withGuardedTab(tab, async () => {
|
|
557
584
|
const baseURI = await baseUriOf(tab);
|
|
@@ -773,6 +800,36 @@ function deliver(sub, payload) {
|
|
|
773
800
|
}
|
|
774
801
|
}
|
|
775
802
|
|
|
803
|
+
export async function onDialog(tab, handler) {
|
|
804
|
+
const targetId = targetIdOf(tab);
|
|
805
|
+
if (handler !== null && typeof handler !== 'function') {
|
|
806
|
+
throw new TypeError('browser.onDialog: handler must be a function or null');
|
|
807
|
+
}
|
|
808
|
+
if (handler === null) {
|
|
809
|
+
clearHandler(targetId);
|
|
810
|
+
return null;
|
|
811
|
+
}
|
|
812
|
+
return using(() =>
|
|
813
|
+
withGuardedTab(tab, async () => {
|
|
814
|
+
await sessionFor(targetId);
|
|
815
|
+
if (!(await hold(endpoint, targetId))) {
|
|
816
|
+
throw new Error(`browser.onDialog: could not watch the dialogs of tab ${targetId}`);
|
|
817
|
+
}
|
|
818
|
+
setHandler(targetId, handler);
|
|
819
|
+
return {
|
|
820
|
+
targetId,
|
|
821
|
+
async close() {
|
|
822
|
+
return clearHandler(targetId, handler);
|
|
823
|
+
},
|
|
824
|
+
};
|
|
825
|
+
})
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
export function dialogs(tab) {
|
|
830
|
+
return dialogRecords(tab === undefined ? undefined : targetIdOf(tab));
|
|
831
|
+
}
|
|
832
|
+
|
|
776
833
|
export const websocket = {
|
|
777
834
|
on(tab, opts = {}) {
|
|
778
835
|
const targetId = targetIdOf(tab);
|
|
@@ -790,7 +847,7 @@ export const websocket = {
|
|
|
790
847
|
},
|
|
791
848
|
async forward(sink) {
|
|
792
849
|
validateSink(sink);
|
|
793
|
-
return using(() => subscribe(sink));
|
|
850
|
+
return using(() => targeting(tab, () => subscribe(sink)));
|
|
794
851
|
},
|
|
795
852
|
};
|
|
796
853
|
async function subscribe(sink) {
|
|
@@ -838,6 +895,8 @@ const browser = {
|
|
|
838
895
|
localStorage,
|
|
839
896
|
fetch,
|
|
840
897
|
websocket,
|
|
898
|
+
onDialog,
|
|
899
|
+
dialogs,
|
|
841
900
|
};
|
|
842
901
|
|
|
843
902
|
export default browser;
|
package/src/dialogs.js
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { connect } from './connect.js';
|
|
2
|
+
import { isProtectedUrl } from './guard.js';
|
|
3
|
+
import { socketClass } from './socket.js';
|
|
4
|
+
|
|
5
|
+
const ENABLE_TIMEOUT_MS = 10000;
|
|
6
|
+
const CHECK_TIMEOUT_MS = 5000;
|
|
7
|
+
const KEPT = 50;
|
|
8
|
+
|
|
9
|
+
let link;
|
|
10
|
+
let lastUrl;
|
|
11
|
+
const holds = new Map();
|
|
12
|
+
const handlers = new Map();
|
|
13
|
+
const records = new Map();
|
|
14
|
+
const unreported = new Map();
|
|
15
|
+
const frozen = new Map();
|
|
16
|
+
|
|
17
|
+
export function ordinaryUrl(text) {
|
|
18
|
+
if (typeof text !== 'string' || isProtectedUrl(text) || !URL.canParse(text)) return false;
|
|
19
|
+
const url = new URL(text);
|
|
20
|
+
return (url.protocol === 'http:' || url.protocol === 'https:') && url.hostname.length > 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function text(value) {
|
|
24
|
+
return typeof value === 'string' ? value : '';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function openLink(url) {
|
|
28
|
+
if (link?.url === url) return link.ready;
|
|
29
|
+
closeLink();
|
|
30
|
+
if (lastUrl !== url) {
|
|
31
|
+
lastUrl = url;
|
|
32
|
+
handlers.clear();
|
|
33
|
+
records.clear();
|
|
34
|
+
unreported.clear();
|
|
35
|
+
frozen.clear();
|
|
36
|
+
}
|
|
37
|
+
const current = { url, sessions: new Map() };
|
|
38
|
+
const Socket = socketClass((socket) => {
|
|
39
|
+
current.socket = socket;
|
|
40
|
+
socket.addEventListener('close', () => dropLink(current));
|
|
41
|
+
socket.addEventListener('error', () => dropLink(current));
|
|
42
|
+
});
|
|
43
|
+
current.ready = connect({ url, WebSocket: Socket }).then((client) => {
|
|
44
|
+
current.client = client;
|
|
45
|
+
listen(current, client);
|
|
46
|
+
if (link !== current) client.close();
|
|
47
|
+
return client;
|
|
48
|
+
});
|
|
49
|
+
current.ready.catch(() => dropLink(current));
|
|
50
|
+
link = current;
|
|
51
|
+
return current.ready;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function dropLink(current) {
|
|
55
|
+
if (link !== current) return;
|
|
56
|
+
link = undefined;
|
|
57
|
+
for (const [targetId, hold] of holds) {
|
|
58
|
+
if (hold.link !== current) continue;
|
|
59
|
+
holds.delete(targetId);
|
|
60
|
+
release(hold);
|
|
61
|
+
}
|
|
62
|
+
current.client?.close();
|
|
63
|
+
current.socket?.close();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function closeLink() {
|
|
67
|
+
if (link) dropLink(link);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function listen(current, client) {
|
|
71
|
+
const on = (method, work) =>
|
|
72
|
+
client.on(method, (message) => {
|
|
73
|
+
if (link !== current) return;
|
|
74
|
+
const hold = current.sessions.get(message?.sessionId);
|
|
75
|
+
if (hold && holds.get(hold.targetId) === hold) work(hold, message.params ?? {});
|
|
76
|
+
});
|
|
77
|
+
on('Page.javascriptDialogOpening', (hold, params) => void opened(hold, params));
|
|
78
|
+
on('Page.javascriptDialogClosed', (hold) => forget(hold));
|
|
79
|
+
on('Page.frameNavigated', (hold, params) => navigated(hold, params.frame));
|
|
80
|
+
on('Page.frameStartedNavigating', (hold) => moved(hold));
|
|
81
|
+
on('Inspector.detached', (hold) => drop(hold));
|
|
82
|
+
client.on('Target.detachedFromTarget', (message) => {
|
|
83
|
+
if (link !== current) return;
|
|
84
|
+
const hold = current.sessions.get(message?.params?.sessionId);
|
|
85
|
+
if (hold) drop(hold);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function forget(hold) {
|
|
90
|
+
hold.epoch += 1;
|
|
91
|
+
hold.dialog = undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function moved(hold) {
|
|
95
|
+
hold.moves += 1;
|
|
96
|
+
forget(hold);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function navigated(hold, frame) {
|
|
100
|
+
moved(hold);
|
|
101
|
+
if (frame?.id !== hold.targetId || frame.parentId !== undefined) return;
|
|
102
|
+
if (!ordinaryUrl(`${text(frame.url)}${text(frame.urlFragment)}`)) drop(hold);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function release(hold) {
|
|
106
|
+
forget(hold);
|
|
107
|
+
hold.link.sessions.delete(hold.sessionId);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function drop(hold) {
|
|
111
|
+
if (holds.get(hold.targetId) === hold) holds.delete(hold.targetId);
|
|
112
|
+
release(hold);
|
|
113
|
+
if (hold.sessionId && hold.link.client && link === hold.link) {
|
|
114
|
+
hold.link.client
|
|
115
|
+
.send('Target.detachFromTarget', { sessionId: hold.sessionId }, undefined, CHECK_TIMEOUT_MS)
|
|
116
|
+
.catch(() => undefined);
|
|
117
|
+
}
|
|
118
|
+
if (link === hold.link && ![...holds.values()].some((other) => other.link === link)) closeLink();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function hold(url, targetId) {
|
|
122
|
+
const existing = holds.get(targetId);
|
|
123
|
+
if (existing && existing.link === link && link?.url === url) return existing.ready;
|
|
124
|
+
let client;
|
|
125
|
+
try {
|
|
126
|
+
client = await openLink(url);
|
|
127
|
+
} catch {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
const again = holds.get(targetId);
|
|
131
|
+
if (again && again.link === link) return again.ready;
|
|
132
|
+
const entry = { targetId, link, epoch: 0, moves: 0, dialog: undefined };
|
|
133
|
+
holds.set(targetId, entry);
|
|
134
|
+
entry.ready = (async () => {
|
|
135
|
+
const sessionId = await client.attach(targetId);
|
|
136
|
+
entry.sessionId = sessionId;
|
|
137
|
+
entry.link.sessions.set(sessionId, entry);
|
|
138
|
+
await client.send('Page.enable', {}, sessionId, ENABLE_TIMEOUT_MS);
|
|
139
|
+
if (holds.get(targetId) !== entry) return false;
|
|
140
|
+
frozen.delete(targetId);
|
|
141
|
+
return true;
|
|
142
|
+
})().catch(() => {
|
|
143
|
+
drop(entry);
|
|
144
|
+
return false;
|
|
145
|
+
});
|
|
146
|
+
return entry.ready;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function setHandler(targetId, handler) {
|
|
150
|
+
handlers.set(targetId, handler);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function clearHandler(targetId, handler) {
|
|
154
|
+
if (handler !== undefined && handlers.get(targetId) !== handler) return false;
|
|
155
|
+
return handlers.delete(targetId);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function opened(hold, params) {
|
|
159
|
+
moved(hold);
|
|
160
|
+
const dialog = {
|
|
161
|
+
epoch: hold.epoch,
|
|
162
|
+
frameId: text(params.frameId),
|
|
163
|
+
url: text(params.url),
|
|
164
|
+
type: text(params.type),
|
|
165
|
+
message: text(params.message),
|
|
166
|
+
defaultPrompt: text(params.defaultPrompt),
|
|
167
|
+
state: 'pending',
|
|
168
|
+
done: Promise.withResolvers(),
|
|
169
|
+
};
|
|
170
|
+
hold.dialog = dialog;
|
|
171
|
+
return settle(hold, dialog);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function current(hold, dialog) {
|
|
175
|
+
return holds.get(hold.targetId) === hold && hold.dialog === dialog && hold.epoch === dialog.epoch;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function owned(hold, dialog) {
|
|
179
|
+
if (!current(hold, dialog)) return 'stale';
|
|
180
|
+
if (dialog.frameId !== hold.targetId || !ordinaryUrl(dialog.url)) return 'foreign';
|
|
181
|
+
const client = hold.link.client;
|
|
182
|
+
const info = await client
|
|
183
|
+
.send('Target.getTargetInfo', { targetId: hold.targetId }, undefined, CHECK_TIMEOUT_MS)
|
|
184
|
+
.catch(() => undefined);
|
|
185
|
+
const target = info?.targetInfo;
|
|
186
|
+
if (target?.targetId !== hold.targetId || target.type !== 'page') return 'protected';
|
|
187
|
+
if (!ordinaryUrl(target.url) || target.url !== dialog.url) return 'protected';
|
|
188
|
+
if (!current(hold, dialog)) return 'stale';
|
|
189
|
+
const history = await client
|
|
190
|
+
.send('Page.getNavigationHistory', {}, hold.sessionId, CHECK_TIMEOUT_MS)
|
|
191
|
+
.catch(() => undefined);
|
|
192
|
+
const entries = Array.isArray(history?.entries) ? history.entries : [];
|
|
193
|
+
const entry = Number.isInteger(history?.currentIndex) ? entries[history.currentIndex] : undefined;
|
|
194
|
+
if (!ordinaryUrl(entry?.url) || entry.url !== dialog.url) return 'protected';
|
|
195
|
+
return current(hold, dialog) ? 'owned' : 'stale';
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function blank(dialog) {
|
|
199
|
+
dialog.url = '';
|
|
200
|
+
dialog.type = '';
|
|
201
|
+
dialog.message = '';
|
|
202
|
+
dialog.defaultPrompt = '';
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function refuse(hold, dialog, outcome) {
|
|
206
|
+
blank(dialog);
|
|
207
|
+
dialog.done.resolve(false);
|
|
208
|
+
if (outcome === 'stale' || !current(hold, dialog)) return false;
|
|
209
|
+
dialog.state = 'refused';
|
|
210
|
+
remember(hold.targetId, { targetId: hold.targetId, refused: true, at: Date.now() });
|
|
211
|
+
note(hold.targetId, refusal(hold.targetId));
|
|
212
|
+
if (outcome !== 'protected') return false;
|
|
213
|
+
const info = await hold.link.client
|
|
214
|
+
.send('Target.getTargetInfo', { targetId: hold.targetId }, undefined, CHECK_TIMEOUT_MS)
|
|
215
|
+
.catch(() => undefined);
|
|
216
|
+
frozen.set(hold.targetId, text(info?.targetInfo?.url));
|
|
217
|
+
drop(hold);
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function refusal(targetId) {
|
|
222
|
+
return `browser: tab ${targetId} is showing a dialog this script may not answer, because its page isn't a verified ordinary page. The page waits until the dialog is answered in the browser, or the tab is reloaded or closed.`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function fallback(type) {
|
|
226
|
+
return { accept: type === 'alert' || type === 'beforeunload', by: 'default' };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function choose(hold, dialog) {
|
|
230
|
+
const handler = handlers.get(hold.targetId);
|
|
231
|
+
if (typeof handler !== 'function') return fallback(dialog.type);
|
|
232
|
+
let choice;
|
|
233
|
+
const chosen = Promise.withResolvers();
|
|
234
|
+
const view = Object.freeze({
|
|
235
|
+
targetId: hold.targetId,
|
|
236
|
+
type: dialog.type,
|
|
237
|
+
message: dialog.message,
|
|
238
|
+
defaultPrompt: dialog.defaultPrompt,
|
|
239
|
+
url: dialog.url,
|
|
240
|
+
accept(promptText) {
|
|
241
|
+
if (promptText !== undefined && typeof promptText !== 'string') {
|
|
242
|
+
throw new TypeError('browser.onDialog: promptText must be a string');
|
|
243
|
+
}
|
|
244
|
+
choice ??= { accept: true, promptText, by: 'handler' };
|
|
245
|
+
chosen.resolve();
|
|
246
|
+
return dialog.done.promise;
|
|
247
|
+
},
|
|
248
|
+
dismiss() {
|
|
249
|
+
choice ??= { accept: false, by: 'handler' };
|
|
250
|
+
chosen.resolve();
|
|
251
|
+
return dialog.done.promise;
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
const ran = Promise.resolve()
|
|
255
|
+
.then(() => handler(view))
|
|
256
|
+
.catch((error) => {
|
|
257
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
258
|
+
console.warn(`browser.onDialog: the handler for tab ${hold.targetId} failed: ${message}`);
|
|
259
|
+
});
|
|
260
|
+
await Promise.race([chosen.promise, ran]);
|
|
261
|
+
return choice ?? fallback(dialog.type);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function settle(hold, dialog) {
|
|
265
|
+
const before = await owned(hold, dialog);
|
|
266
|
+
if (before !== 'owned') return refuse(hold, dialog, before);
|
|
267
|
+
const choice = await choose(hold, dialog);
|
|
268
|
+
const after = await owned(hold, dialog);
|
|
269
|
+
if (after !== 'owned') return refuse(hold, dialog, after);
|
|
270
|
+
const params = { accept: choice.accept };
|
|
271
|
+
if (choice.accept && typeof choice.promptText === 'string') params.promptText = choice.promptText;
|
|
272
|
+
const moves = hold.moves;
|
|
273
|
+
try {
|
|
274
|
+
await hold.link.client.send(
|
|
275
|
+
'Page.handleJavaScriptDialog',
|
|
276
|
+
params,
|
|
277
|
+
hold.sessionId,
|
|
278
|
+
CHECK_TIMEOUT_MS
|
|
279
|
+
);
|
|
280
|
+
} catch {
|
|
281
|
+
if (current(hold, dialog)) forget(hold);
|
|
282
|
+
dialog.done.resolve(false);
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
if (hold.moves !== moves) {
|
|
286
|
+
blank(dialog);
|
|
287
|
+
remember(hold.targetId, {
|
|
288
|
+
targetId: hold.targetId,
|
|
289
|
+
accepted: choice.accept,
|
|
290
|
+
by: choice.by,
|
|
291
|
+
unsure: true,
|
|
292
|
+
at: Date.now(),
|
|
293
|
+
});
|
|
294
|
+
note(hold.targetId, unsure(hold.targetId, choice.accept));
|
|
295
|
+
dialog.done.resolve(true);
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
const record = {
|
|
299
|
+
targetId: hold.targetId,
|
|
300
|
+
type: dialog.type,
|
|
301
|
+
message: dialog.message,
|
|
302
|
+
url: dialog.url,
|
|
303
|
+
accepted: choice.accept,
|
|
304
|
+
by: choice.by,
|
|
305
|
+
at: Date.now(),
|
|
306
|
+
};
|
|
307
|
+
if (dialog.type === 'prompt') record.defaultPrompt = dialog.defaultPrompt;
|
|
308
|
+
if (params.promptText !== undefined) record.promptText = params.promptText;
|
|
309
|
+
remember(hold.targetId, record);
|
|
310
|
+
if (choice.by === 'default') {
|
|
311
|
+
note(
|
|
312
|
+
hold.targetId,
|
|
313
|
+
`browser: tab ${hold.targetId} showed ${article(dialog.type)} ${dialog.type} dialog nobody answered, so it was ${choice.accept ? 'accepted' : 'dismissed'}: ${JSON.stringify(dialog.message)}`
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
if (current(hold, dialog)) {
|
|
317
|
+
dialog.state = 'answered';
|
|
318
|
+
hold.dialog = undefined;
|
|
319
|
+
}
|
|
320
|
+
dialog.done.resolve(true);
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function unsure(targetId, accepted) {
|
|
325
|
+
return `browser: tab ${targetId} navigated or opened another dialog while a dialog was being ${accepted ? 'accepted' : 'dismissed'}, so which dialog the answer reached isn't known.`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function article(type) {
|
|
329
|
+
return /^[aeiou]/u.test(type) ? 'an' : 'a';
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function remember(targetId, record) {
|
|
333
|
+
const list = records.get(targetId) ?? [];
|
|
334
|
+
list.push(Object.freeze(record));
|
|
335
|
+
if (list.length > KEPT) list.shift();
|
|
336
|
+
records.set(targetId, list);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function note(targetId, line) {
|
|
340
|
+
const list = unreported.get(targetId) ?? [];
|
|
341
|
+
list.push(line);
|
|
342
|
+
if (list.length > KEPT) list.shift();
|
|
343
|
+
unreported.set(targetId, list);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function report(targetId) {
|
|
347
|
+
const lines = unreported.get(targetId);
|
|
348
|
+
if (!lines) return;
|
|
349
|
+
unreported.delete(targetId);
|
|
350
|
+
for (const line of lines) console.warn(line);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export async function blocked(targetId, urlOf) {
|
|
354
|
+
if (holds.get(targetId)?.dialog?.state === 'refused') return true;
|
|
355
|
+
if (!frozen.has(targetId)) return false;
|
|
356
|
+
if ((await urlOf()) === frozen.get(targetId)) return true;
|
|
357
|
+
frozen.delete(targetId);
|
|
358
|
+
return false;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export function dialogs(targetId) {
|
|
362
|
+
if (targetId === undefined) return [...records.values()].flat();
|
|
363
|
+
return [...(records.get(targetId) ?? [])];
|
|
364
|
+
}
|
package/src/socket.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
2
|
+
const HEAD_LIMIT = 65536;
|
|
3
|
+
|
|
4
|
+
export function socketClass(track) {
|
|
5
|
+
return class Socket extends UnrefSocket {
|
|
6
|
+
constructor(url) {
|
|
7
|
+
super(url);
|
|
8
|
+
track(this);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
class UnrefSocket {
|
|
14
|
+
#listeners = new Map();
|
|
15
|
+
#socket;
|
|
16
|
+
#open = false;
|
|
17
|
+
#closed = false;
|
|
18
|
+
#head = Buffer.alloc(0);
|
|
19
|
+
#frames = Buffer.alloc(0);
|
|
20
|
+
#parts = [];
|
|
21
|
+
#key;
|
|
22
|
+
|
|
23
|
+
constructor(url) {
|
|
24
|
+
this.url = String(url);
|
|
25
|
+
this.#start().catch((error) => this.#failed(error));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
addEventListener(type, listener) {
|
|
29
|
+
let set = this.#listeners.get(type);
|
|
30
|
+
if (!set) {
|
|
31
|
+
set = new Set();
|
|
32
|
+
this.#listeners.set(type, set);
|
|
33
|
+
}
|
|
34
|
+
set.add(listener);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
send(text) {
|
|
38
|
+
if (!this.#open || this.#closed) throw new Error('WebSocket is not open');
|
|
39
|
+
this.#write(1, Buffer.from(String(text), 'utf8'));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
close() {
|
|
43
|
+
if (this.#closed) return;
|
|
44
|
+
if (this.#open) {
|
|
45
|
+
const payload = Buffer.alloc(2);
|
|
46
|
+
payload.writeUInt16BE(1000, 0);
|
|
47
|
+
try {
|
|
48
|
+
this.#write(8, payload);
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
this.#finish(1000, '');
|
|
52
|
+
this.#socket?.end();
|
|
53
|
+
this.#socket?.destroy();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async #start() {
|
|
57
|
+
const target = new URL(this.url);
|
|
58
|
+
const secure = target.protocol === 'wss:';
|
|
59
|
+
if (!secure && target.protocol !== 'ws:')
|
|
60
|
+
throw new Error(`unsupported scheme ${target.protocol}`);
|
|
61
|
+
const host = target.hostname.replace(/^\[(.*)\]$/u, '$1');
|
|
62
|
+
const port = Number(target.port) || (secure ? 443 : 80);
|
|
63
|
+
const [net, crypto, tls] = await Promise.all([
|
|
64
|
+
import('node:net'),
|
|
65
|
+
import('node:crypto'),
|
|
66
|
+
secure ? import('node:tls') : undefined,
|
|
67
|
+
]);
|
|
68
|
+
if (this.#closed) return;
|
|
69
|
+
this.#key = crypto.randomBytes(16).toString('base64');
|
|
70
|
+
const accept = crypto.createHash('sha1').update(`${this.#key}${GUID}`).digest('base64');
|
|
71
|
+
let socket;
|
|
72
|
+
if (secure) {
|
|
73
|
+
socket = tls.connect({
|
|
74
|
+
host,
|
|
75
|
+
port,
|
|
76
|
+
servername: net.isIP(host) ? undefined : host,
|
|
77
|
+
ALPNProtocols: ['http/1.1'],
|
|
78
|
+
});
|
|
79
|
+
} else {
|
|
80
|
+
socket = net.connect({ host, port });
|
|
81
|
+
}
|
|
82
|
+
this.#socket = socket;
|
|
83
|
+
socket.unref();
|
|
84
|
+
socket.on(secure ? 'secureConnect' : 'connect', () => {
|
|
85
|
+
socket.unref();
|
|
86
|
+
socket.write(
|
|
87
|
+
`GET ${target.pathname}${target.search} HTTP/1.1\r\nHost: ${target.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${this.#key}\r\nSec-WebSocket-Version: 13\r\n\r\n`
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
socket.on('data', (chunk) => {
|
|
91
|
+
try {
|
|
92
|
+
if (this.#open) this.#read(chunk);
|
|
93
|
+
else this.#handshake(chunk, accept);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
this.#failed(error);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
socket.on('error', (error) => this.#failed(error));
|
|
99
|
+
socket.on('close', () => {
|
|
100
|
+
if (this.#open) this.#finish(1006, '');
|
|
101
|
+
else this.#failed(new Error('connection closed during the handshake'));
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
#handshake(chunk, accept) {
|
|
106
|
+
this.#head = Buffer.concat([this.#head, chunk]);
|
|
107
|
+
const end = this.#head.indexOf('\r\n\r\n');
|
|
108
|
+
if (end < 0) {
|
|
109
|
+
if (this.#head.length > HEAD_LIMIT) throw new Error('handshake response too large');
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const lines = this.#head.subarray(0, end).toString('latin1').split('\r\n');
|
|
113
|
+
const rest = this.#head.subarray(end + 4);
|
|
114
|
+
this.#head = Buffer.alloc(0);
|
|
115
|
+
if (!/^HTTP\/1\.1 101\b/u.test(lines[0])) {
|
|
116
|
+
throw new Error(`unexpected handshake response: ${lines[0]}`);
|
|
117
|
+
}
|
|
118
|
+
const headers = new Map();
|
|
119
|
+
for (const line of lines.slice(1)) {
|
|
120
|
+
const at = line.indexOf(':');
|
|
121
|
+
if (at > 0) headers.set(line.slice(0, at).trim().toLowerCase(), line.slice(at + 1).trim());
|
|
122
|
+
}
|
|
123
|
+
if (headers.get('sec-websocket-accept') !== accept) {
|
|
124
|
+
throw new Error('handshake response has the wrong Sec-WebSocket-Accept');
|
|
125
|
+
}
|
|
126
|
+
this.#open = true;
|
|
127
|
+
this.#emit('open', {});
|
|
128
|
+
if (rest.length > 0) this.#read(rest);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
#read(chunk) {
|
|
132
|
+
this.#frames = Buffer.concat([this.#frames, chunk]);
|
|
133
|
+
for (;;) {
|
|
134
|
+
const frame = this.#frame();
|
|
135
|
+
if (!frame) return;
|
|
136
|
+
this.#handle(frame);
|
|
137
|
+
if (this.#closed) return;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
#frame() {
|
|
142
|
+
const buffer = this.#frames;
|
|
143
|
+
if (buffer.length < 2) return undefined;
|
|
144
|
+
const second = buffer[1];
|
|
145
|
+
let length = second & 0x7f;
|
|
146
|
+
let offset = 2;
|
|
147
|
+
if (length === 126) {
|
|
148
|
+
if (buffer.length < 4) return undefined;
|
|
149
|
+
length = buffer.readUInt16BE(2);
|
|
150
|
+
offset = 4;
|
|
151
|
+
} else if (length === 127) {
|
|
152
|
+
if (buffer.length < 10) return undefined;
|
|
153
|
+
length = Number(buffer.readBigUInt64BE(2));
|
|
154
|
+
offset = 10;
|
|
155
|
+
}
|
|
156
|
+
const masked = (second & 0x80) !== 0;
|
|
157
|
+
const total = offset + (masked ? 4 : 0) + length;
|
|
158
|
+
if (buffer.length < total) return undefined;
|
|
159
|
+
const payload = Buffer.from(buffer.subarray(total - length, total));
|
|
160
|
+
if (masked) {
|
|
161
|
+
const key = buffer.subarray(offset, offset + 4);
|
|
162
|
+
for (let i = 0; i < payload.length; i += 1) payload[i] ^= key[i % 4];
|
|
163
|
+
}
|
|
164
|
+
this.#frames = buffer.subarray(total);
|
|
165
|
+
return { fin: (buffer[0] & 0x80) !== 0, opcode: buffer[0] & 0x0f, payload };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
#handle({ fin, opcode, payload }) {
|
|
169
|
+
if (opcode === 8) {
|
|
170
|
+
const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
|
|
171
|
+
const reason = payload.length > 2 ? payload.subarray(2).toString('utf8') : '';
|
|
172
|
+
try {
|
|
173
|
+
this.#write(8, payload.subarray(0, 2));
|
|
174
|
+
} catch {}
|
|
175
|
+
this.#finish(code, reason);
|
|
176
|
+
this.#socket?.end();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (opcode === 9) {
|
|
180
|
+
this.#write(10, payload);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (opcode === 10) return;
|
|
184
|
+
if (opcode === 1 || opcode === 2) this.#parts = [{ opcode, payload }];
|
|
185
|
+
else if (opcode === 0 && this.#parts.length > 0) this.#parts.push({ opcode, payload });
|
|
186
|
+
else return;
|
|
187
|
+
if (!fin) return;
|
|
188
|
+
const [{ opcode: kind }] = this.#parts;
|
|
189
|
+
const data = Buffer.concat(this.#parts.map((part) => part.payload));
|
|
190
|
+
this.#parts = [];
|
|
191
|
+
if (kind === 1) this.#emit('message', { data: data.toString('utf8') });
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
#write(opcode, payload) {
|
|
195
|
+
const mask = Buffer.alloc(4);
|
|
196
|
+
for (let i = 0; i < 4; i += 1) mask[i] = Math.floor(Math.random() * 256);
|
|
197
|
+
let head;
|
|
198
|
+
if (payload.length < 126) {
|
|
199
|
+
head = Buffer.from([0x80 | opcode, 0x80 | payload.length]);
|
|
200
|
+
} else if (payload.length < 65536) {
|
|
201
|
+
head = Buffer.alloc(4);
|
|
202
|
+
head[0] = 0x80 | opcode;
|
|
203
|
+
head[1] = 0x80 | 126;
|
|
204
|
+
head.writeUInt16BE(payload.length, 2);
|
|
205
|
+
} else {
|
|
206
|
+
head = Buffer.alloc(10);
|
|
207
|
+
head[0] = 0x80 | opcode;
|
|
208
|
+
head[1] = 0x80 | 127;
|
|
209
|
+
head.writeBigUInt64BE(BigInt(payload.length), 2);
|
|
210
|
+
}
|
|
211
|
+
const body = Buffer.from(payload);
|
|
212
|
+
for (let i = 0; i < body.length; i += 1) body[i] ^= mask[i % 4];
|
|
213
|
+
this.#socket.write(Buffer.concat([head, mask, body]));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
#failed(error) {
|
|
217
|
+
if (this.#closed) return;
|
|
218
|
+
if (this.#open) {
|
|
219
|
+
this.#finish(1006, '');
|
|
220
|
+
} else {
|
|
221
|
+
this.#closed = true;
|
|
222
|
+
this.#emit('error', { error });
|
|
223
|
+
}
|
|
224
|
+
this.#socket?.destroy();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
#finish(code, reason) {
|
|
228
|
+
if (this.#closed) return;
|
|
229
|
+
this.#closed = true;
|
|
230
|
+
this.#open = false;
|
|
231
|
+
this.#emit('close', { code, reason });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
#emit(type, event) {
|
|
235
|
+
for (const listener of [...(this.#listeners.get(type) ?? [])]) {
|
|
236
|
+
try {
|
|
237
|
+
listener(event);
|
|
238
|
+
} catch {}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const version = '0.1.
|
|
1
|
+
export const version = '0.1.46';
|