navego 0.0.0-stage → 1.7.5
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 +149 -2
- package/action-strategy.js +15 -0
- package/advice.js +153 -0
- package/agent-guide.js +201 -0
- package/bin/kemudi.js +60 -0
- package/bin/opera-chrome.cmd +15 -0
- package/bin/opera-local-dev.js +62 -0
- package/bin/opera-local.js +188 -0
- package/bing-serp.js +174 -0
- package/bridge-token.js +43 -0
- package/bridge-ws.js +718 -0
- package/bridge.js +322 -0
- package/browsers.js +144 -0
- package/burst.js +413 -0
- package/canvas.js +248 -0
- package/captcha-solver.js +73 -0
- package/caret-guard.js +68 -0
- package/cdp.js +95 -0
- package/cloud.js +139 -0
- package/decks.js +115 -0
- package/dev-shim.js +253 -0
- package/dialog.js +198 -0
- package/doctor.js +92 -0
- package/documents.js +408 -0
- package/driver.js +73 -0
- package/focus-guard.js +87 -0
- package/gates.js +299 -0
- package/input.js +237 -0
- package/install.js +201 -0
- package/leases.js +59 -0
- package/lib/endpoints.js +34 -0
- package/lib/socket-protocol.js +144 -0
- package/mcp-server.js +1001 -0
- package/menu-tree.js +298 -0
- package/oauth.js +212 -0
- package/observe.js +363 -0
- package/office/docx.js +159 -0
- package/office/palette.js +17 -0
- package/office/pptx.js +154 -0
- package/office/xlsx.js +201 -0
- package/office/xml.js +31 -0
- package/office/zip.js +111 -0
- package/package.json +94 -4
- package/page-expressions.js +780 -0
- package/pointer.js +213 -0
- package/postinstall.js +27 -0
- package/primitives-file.js +394 -0
- package/primitives.js +149 -0
- package/read-strategy.js +58 -0
- package/registry.js +88 -0
- package/reports.js +309 -0
- package/sessions.js +131 -0
- package/spreadsheets.js +93 -0
- package/statements.js +221 -0
- package/surface-profile.js +241 -0
- package/tidy.js +72 -0
- package/tools.js +494 -0
- package/transport.js +200 -0
- package/waits.js +178 -0
- package/wallet-client.js +95 -0
- package/window-focus.js +338 -0
- package/ws-server.js +263 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @last-edited: 2026-10-21 UTC+7.
|
|
3
|
+
// @title: opera-local-dev — the development front door for the local MCP server.
|
|
4
|
+
// @state: the watched files, the supervisor behind the pipe, and the reload it performs on a save.
|
|
5
|
+
// @dependencies: none.
|
|
6
|
+
// Same tools as opera-local.js, reached through the dev shim: edit a watched file, save, and the worker behind the pipe rebuilds itself within a second, without a toggle.
|
|
7
|
+
// Production spawns opera-local.js directly.
|
|
8
|
+
import { stdin, stdout, stderr, exit, execPath } from 'node:process';
|
|
9
|
+
import { spawn } from 'node:child_process';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import { dirname, join } from 'node:path';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { createSupervisor } from '../dev-shim.js';
|
|
14
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
15
|
+
const root = join(here, '..', '..');
|
|
16
|
+
const WATCHED = [
|
|
17
|
+
join(root, 'local'),
|
|
18
|
+
join(root, 'extension', 'lib', 'socket-protocol.js')
|
|
19
|
+
];
|
|
20
|
+
const log = (message) => stderr.write(`[opera-local-dev] ${String(message)}\n`);
|
|
21
|
+
const supervisor = createSupervisor({
|
|
22
|
+
// WHY THE CAST: the spawn is declared with stdio pipes, so stdin and stdout are the streams the supervisor reads; Node types them as nullable, the supervisor asks for a non-null pair, and the cast names that contract.
|
|
23
|
+
spawnWorker: () => spawn(execPath, [join(here, 'opera-local.js')], {
|
|
24
|
+
stdio: ['pipe', 'pipe', 'inherit'],
|
|
25
|
+
cwd: join(root, 'local')
|
|
26
|
+
}),
|
|
27
|
+
watchFiles: (onChange) => {
|
|
28
|
+
const watchers = [];
|
|
29
|
+
for (const target of WATCHED) {
|
|
30
|
+
const stats = fs.statSync(target, { throwIfNoEntry: false });
|
|
31
|
+
if (!stats)
|
|
32
|
+
continue;
|
|
33
|
+
watchers.push(fs.watch(target, { recursive: stats.isDirectory() }, (_event, name) => {
|
|
34
|
+
if (name && !/\.(mjs|js|json)$/.test(name))
|
|
35
|
+
return;
|
|
36
|
+
onChange();
|
|
37
|
+
}));
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
close: () => {
|
|
41
|
+
for (const watcher of watchers)
|
|
42
|
+
watcher.close();
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
input: stdin,
|
|
47
|
+
output: stdout,
|
|
48
|
+
log
|
|
49
|
+
});
|
|
50
|
+
async function shutdown(code) {
|
|
51
|
+
await supervisor.stop();
|
|
52
|
+
exit(code);
|
|
53
|
+
}
|
|
54
|
+
stdin.on('end', () => {
|
|
55
|
+
void shutdown(0);
|
|
56
|
+
});
|
|
57
|
+
process.on('SIGINT', () => {
|
|
58
|
+
void shutdown(0);
|
|
59
|
+
});
|
|
60
|
+
process.on('SIGTERM', () => {
|
|
61
|
+
void shutdown(0);
|
|
62
|
+
});
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @last-edited: 2026-10-13 UTC+7.
|
|
3
|
+
// @title: opera-local — the installed entry point: a local CDP driver behind an MCP stdio server.
|
|
4
|
+
// @state: binds the protocol to a real browser and to the environment it was given.
|
|
5
|
+
// @dependencies: ../mcp-server.js, ../driver.js, ../sessions.js, ../transport.js.
|
|
6
|
+
// WHY THIS FILE EXISTS
|
|
7
|
+
//
|
|
8
|
+
// The server speaks MCP and the driver speaks CDP; this is the only place the two are joined.
|
|
9
|
+
// It is separate so the protocol stays testable without a browser.
|
|
10
|
+
//
|
|
11
|
+
// WHY the session is made lazily.
|
|
12
|
+
// status has to answer on a machine where no browser is listening, which is exactly when someone needs to be told that.
|
|
13
|
+
// Connecting eagerly would turn a useful diagnosis into a crash.
|
|
14
|
+
//
|
|
15
|
+
// WHY the port comes from the environment.
|
|
16
|
+
// npx must work without a config file, so the two things a user may need to override, which port and which browser, are environment variables rather than arguments a client would have to know about.
|
|
17
|
+
import { dirname, join } from 'node:path';
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
20
|
+
import { openSession, installedBrowsers } from '../driver.js';
|
|
21
|
+
import { windowState, focusWindow } from '../window-focus.js';
|
|
22
|
+
import { dialogState, dialogType, dialogPress } from '../dialog.js';
|
|
23
|
+
import { createSessionStore } from '../sessions.js';
|
|
24
|
+
import { listPageWebSockets, openTab, closeTab } from '../transport.js';
|
|
25
|
+
import { bridgePort, bridgeReachable, closeBridgeTarget, listBridgeTargets, openBridgeTarget } from '../bridge.js';
|
|
26
|
+
import { guide } from '../agent-guide.js';
|
|
27
|
+
import { startStdio } from '../mcp-server.js';
|
|
28
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
29
|
+
const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'));
|
|
30
|
+
const PORT = Number(process.env.OPERA_LOCAL_PORT || 9333);
|
|
31
|
+
// WHY THE LINK IS ASKED PER CALL.
|
|
32
|
+
// One `BRIDGED` constant decided the pipe at startup and then decided it for good: an extension that was asleep at that moment lost the run to a debugging port, which opens a profile nobody is logged into.
|
|
33
|
+
// Asking each time costs one field read and means a worker that wakes up late is simply used.
|
|
34
|
+
async function bridged() {
|
|
35
|
+
return bridgeReachable();
|
|
36
|
+
}
|
|
37
|
+
const store = createSessionStore({ openSession, port: PORT, viaBridge: null });
|
|
38
|
+
const open = (options) => store.open(options);
|
|
39
|
+
const attach = () => store.attach();
|
|
40
|
+
async function resolveTab() {
|
|
41
|
+
if (await bridged())
|
|
42
|
+
return (await listBridgeTargets()).map((page) => String(page.id));
|
|
43
|
+
return (await listPageWebSockets(PORT)).map((page) => page.id);
|
|
44
|
+
}
|
|
45
|
+
const driver = {
|
|
46
|
+
async tabs() {
|
|
47
|
+
if (await bridged())
|
|
48
|
+
return listBridgeTargets();
|
|
49
|
+
return (await listPageWebSockets(PORT)).map(({ id, url, title }) => ({ id, url, title }));
|
|
50
|
+
},
|
|
51
|
+
async open(url) {
|
|
52
|
+
if (await bridged()) {
|
|
53
|
+
const tab = await openBridgeTarget(url);
|
|
54
|
+
return { url, id: tab.id, port: bridgePort() };
|
|
55
|
+
}
|
|
56
|
+
const tab = await openTab(PORT, url);
|
|
57
|
+
return { url, id: tab.id, port: PORT };
|
|
58
|
+
},
|
|
59
|
+
async close(tabId) {
|
|
60
|
+
return store.closeTab(tabId, async (id) => await bridged() ? closeBridgeTarget(id) : closeTab(PORT, id));
|
|
61
|
+
},
|
|
62
|
+
async ask(method, params) {
|
|
63
|
+
return (await attach()).ask(method, params);
|
|
64
|
+
},
|
|
65
|
+
async guide(topic) {
|
|
66
|
+
return guide(topic);
|
|
67
|
+
},
|
|
68
|
+
async menuTree(options) {
|
|
69
|
+
return (await attach()).menuTree(options);
|
|
70
|
+
},
|
|
71
|
+
async openMenu(options) {
|
|
72
|
+
return (await attach()).openMenu(options);
|
|
73
|
+
},
|
|
74
|
+
async read() {
|
|
75
|
+
return (await attach()).read();
|
|
76
|
+
},
|
|
77
|
+
async settle() {
|
|
78
|
+
return (await attach()).settle();
|
|
79
|
+
},
|
|
80
|
+
async find(query) {
|
|
81
|
+
return (await attach()).find(query);
|
|
82
|
+
},
|
|
83
|
+
async clickFraction(at) {
|
|
84
|
+
return (await attach()).clickFraction(at);
|
|
85
|
+
},
|
|
86
|
+
async click(x, y, handle) {
|
|
87
|
+
return (await attach()).click(x, y, handle);
|
|
88
|
+
},
|
|
89
|
+
async resolve(role, name) {
|
|
90
|
+
return (await attach()).resolve(role, name);
|
|
91
|
+
},
|
|
92
|
+
async hover(x, y) {
|
|
93
|
+
return (await attach()).hover(x, y);
|
|
94
|
+
},
|
|
95
|
+
async clickRow(role, name) {
|
|
96
|
+
return (await attach()).clickRow(role, name);
|
|
97
|
+
},
|
|
98
|
+
async key(name, modifiers) {
|
|
99
|
+
return (await attach()).key(name, modifiers);
|
|
100
|
+
},
|
|
101
|
+
async type(text) {
|
|
102
|
+
return (await attach()).type(text);
|
|
103
|
+
},
|
|
104
|
+
async keys(events) {
|
|
105
|
+
return (await attach()).keys(events);
|
|
106
|
+
},
|
|
107
|
+
async snapshot(limit) {
|
|
108
|
+
return (await attach()).snapshot(limit);
|
|
109
|
+
},
|
|
110
|
+
async caretLine() {
|
|
111
|
+
return (await attach()).caretLine();
|
|
112
|
+
},
|
|
113
|
+
async windowState() {
|
|
114
|
+
return windowState();
|
|
115
|
+
},
|
|
116
|
+
async focusWindow(match) {
|
|
117
|
+
return focusWindow(match);
|
|
118
|
+
},
|
|
119
|
+
async ensureFront(options) {
|
|
120
|
+
return (await attach()).ensureFront(options);
|
|
121
|
+
},
|
|
122
|
+
async captureSized(options) {
|
|
123
|
+
return (await attach()).captureSized(options);
|
|
124
|
+
},
|
|
125
|
+
async dialogState() {
|
|
126
|
+
return dialogState();
|
|
127
|
+
},
|
|
128
|
+
async dialogType(text) {
|
|
129
|
+
return dialogType(text);
|
|
130
|
+
},
|
|
131
|
+
async dialogPress(name) {
|
|
132
|
+
return dialogPress(name);
|
|
133
|
+
},
|
|
134
|
+
async waitForRow(options) {
|
|
135
|
+
return (await attach()).waitForRow(options);
|
|
136
|
+
},
|
|
137
|
+
async waitForText(text, options) {
|
|
138
|
+
return (await attach()).waitForText(text, options);
|
|
139
|
+
},
|
|
140
|
+
async waitForStill(options) {
|
|
141
|
+
return (await attach()).waitForStill(options);
|
|
142
|
+
},
|
|
143
|
+
async waitForUrl(options) {
|
|
144
|
+
return (await attach()).waitForUrl(options);
|
|
145
|
+
},
|
|
146
|
+
async upload(options) {
|
|
147
|
+
return (await attach()).upload(options);
|
|
148
|
+
},
|
|
149
|
+
async dropFile(options) {
|
|
150
|
+
return (await attach()).dropFile(options);
|
|
151
|
+
},
|
|
152
|
+
async interceptFileChooser(enabled) {
|
|
153
|
+
return (await attach()).interceptFileChooser(enabled);
|
|
154
|
+
},
|
|
155
|
+
async download(options) {
|
|
156
|
+
return (await attach()).download(options);
|
|
157
|
+
},
|
|
158
|
+
async pageState() {
|
|
159
|
+
return (await attach()).pageState();
|
|
160
|
+
},
|
|
161
|
+
async capture(options) {
|
|
162
|
+
return (await attach()).capture(options);
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
// WHY the bridge listens before the first tool call.
|
|
166
|
+
// A lazy server makes the first command pay the whole link wait, and leaves the extension polling a dead port until then.
|
|
167
|
+
// Listening here links the worker while the client is still shaking hands.
|
|
168
|
+
// A failure is swallowed on purpose: the port may belong to another session, and every tool call retries with a named error anyway.
|
|
169
|
+
await bridgeReachable().catch(() => false);
|
|
170
|
+
// WHY THE STARTUP PROBE MAY NOT KILL THE SERVER.
|
|
171
|
+
// Asking which pipe is right is asking whether a port is free, and the honest answer to "another driver owns it" is to say so.
|
|
172
|
+
// Dying here instead said it by refusing to start at all, which is what happened when the person toggled the server on while a previous instance was still holding the loopback port: the conflict was real and the only visible result was a dead MCP with a stack trace instead of a server that starts and names the conflict on the first tool call.
|
|
173
|
+
// WHY THE PORT IS A FUNCTION AND NOT A VALUE.
|
|
174
|
+
// The pipe is chosen per call, because a worker that was asleep at startup picks itself up thirty seconds later.
|
|
175
|
+
// A port read once at startup reports the debugging port long after the drive has moved to the bridge — which is a wrong answer about a port nothing is listening on.
|
|
176
|
+
// The hand-built wrapper carries the verbs this CLI road exposes; the server's Driver names the full primitive surface.
|
|
177
|
+
// The gap is pre-existing and outside a type-only stage, so the object is asserted here and the debt is named rather than hidden.
|
|
178
|
+
startStdio({
|
|
179
|
+
context: {
|
|
180
|
+
driver: driver,
|
|
181
|
+
open,
|
|
182
|
+
resolveTab,
|
|
183
|
+
sessionOptions: {},
|
|
184
|
+
port: async () => (await bridged()) ? bridgePort() : PORT,
|
|
185
|
+
version: pkg.version,
|
|
186
|
+
browsers: installedBrowsers()
|
|
187
|
+
}
|
|
188
|
+
});
|
package/bing-serp.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// @last-edited: 2026-11-13 UTC+7.
|
|
2
|
+
// @title: bing-serp - the Bing SERP as data: external results, in order, with their snippets.
|
|
3
|
+
// @state: the one SERP parser behind search, on both roads; the local package reads a generated copy of this file, written by scripts/pack/pack-mcp.mjs and never committed.
|
|
4
|
+
// @dependencies: none.
|
|
5
|
+
// WHY THIS FILE LIVES IN shared/.
|
|
6
|
+
// The hosted road (edge function, Deno) bundles this folder via static import, and the local road (stdio server, Node) carries a copy written at pack time: one file in this tree, two consumers at build time, no drift to guard.
|
|
7
|
+
const BING_HOST = /(^|\.)bing\.com$/i;
|
|
8
|
+
const MICROSOFT_FW_LINK = /(^|\.)go\.microsoft\.com$/i;
|
|
9
|
+
// A display URL, as Bing renders it inside a result card: bare host, host with a path, or "host.tld/path https://host.tld/path".
|
|
10
|
+
const DISPLAY_URL_LINE = /^[\w-]+(\.[\w-]+)+(:[0-9]+)?(\/[\w./-]*)?$/;
|
|
11
|
+
const DISPLAY_MIXED = /^[\w-]+(\.[\w-]+)+(:[0-9]+)?(\/[\w./-]*)?\s+https?:\/\//i;
|
|
12
|
+
const DISPLAYISH = /^https?:\/\//i;
|
|
13
|
+
function isDisplayText(text) {
|
|
14
|
+
return DISPLAY_URL_LINE.test(text) || DISPLAYISH.test(text) || DISPLAY_MIXED.test(text);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* @param href the link's href as Bing rendered it
|
|
18
|
+
* @returns the lower-cased hostname, or an empty string for unparsable input
|
|
19
|
+
*/
|
|
20
|
+
export function hostOf(href) {
|
|
21
|
+
try {
|
|
22
|
+
return new URL(href).hostname.toLowerCase();
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return '';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function isExternal(href) {
|
|
29
|
+
if (!/^https?:\/\//i.test(href))
|
|
30
|
+
return false;
|
|
31
|
+
const host = hostOf(href);
|
|
32
|
+
if (!host)
|
|
33
|
+
return false;
|
|
34
|
+
if (BING_HOST.test(host) || MICROSOFT_FW_LINK.test(host))
|
|
35
|
+
return false;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Bing wraps organic cards in a redirect: https://www.bing.com/ck/a?...&u=a1<base64url-target>.
|
|
40
|
+
* WHY THE UNWRAP IS RE-VALIDATED.
|
|
41
|
+
* A redirect wrapper promises nothing about its target; the target is attacker-controlled.
|
|
42
|
+
* Returning it without the same checks every other href goes through would let javascript: or file: leak out as "results".
|
|
43
|
+
* So the target passes through isExternal before it is ever returned, and anything that fails stays dropped, exactly like the wrapper itself.
|
|
44
|
+
* @param href the redirect URL as Bing rendered it
|
|
45
|
+
* @returns the decoded target, or null when there is nothing to unwrap
|
|
46
|
+
*/
|
|
47
|
+
function unwrapBingRedirect(href) {
|
|
48
|
+
const host = hostOf(href);
|
|
49
|
+
if (!host || !BING_HOST.test(host))
|
|
50
|
+
return null;
|
|
51
|
+
let url;
|
|
52
|
+
try {
|
|
53
|
+
url = new URL(href);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
if (!url.pathname.startsWith('/ck/'))
|
|
59
|
+
return null;
|
|
60
|
+
const packed = url.searchParams.get('u');
|
|
61
|
+
if (!packed)
|
|
62
|
+
return null;
|
|
63
|
+
const encoded = packed.replace(/^a1/i, '').replace(/-/g, '+').replace(/_/g, '/');
|
|
64
|
+
const padded = encoded.padEnd(encoded.length + ((4 - (encoded.length % 4)) % 4), '=');
|
|
65
|
+
let target;
|
|
66
|
+
try {
|
|
67
|
+
const binary = atob(padded);
|
|
68
|
+
target = new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
return isExternal(target) ? target : null;
|
|
74
|
+
}
|
|
75
|
+
export function parseBingSerp({ text = '', links = [] } = {}, { currentFirst = 1 } = {}) {
|
|
76
|
+
const byHref = new Map();
|
|
77
|
+
for (const link of links) {
|
|
78
|
+
const href = String(link?.href ?? '').trim();
|
|
79
|
+
const external = unwrapBingRedirect(href) ?? href;
|
|
80
|
+
if (!isExternal(external))
|
|
81
|
+
continue;
|
|
82
|
+
const anchorText = String(link?.text ?? '').replace(/\s+/g, ' ').trim();
|
|
83
|
+
const group = byHref.get(external) ?? { url: external, site: hostOf(external).replace(/^www\./, ''), texts: [] };
|
|
84
|
+
if (anchorText)
|
|
85
|
+
group.texts.push(anchorText);
|
|
86
|
+
byHref.set(external, group);
|
|
87
|
+
}
|
|
88
|
+
const results = [];
|
|
89
|
+
for (const group of byHref.values()) {
|
|
90
|
+
const nonDisplay = group.texts.filter((t) => !isDisplayText(t));
|
|
91
|
+
let title;
|
|
92
|
+
if (nonDisplay.length) {
|
|
93
|
+
title = (nonDisplay[nonDisplay.length - 1] ?? '').replace(/\s+/g, ' ').trim().slice(0, 300);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
title = (group.texts[group.texts.length - 1] ?? '');
|
|
97
|
+
const arrow = title.indexOf('›');
|
|
98
|
+
if (arrow >= 0)
|
|
99
|
+
title = title.slice(0, arrow);
|
|
100
|
+
title = title.replace(/https?:\/\/\S+/g, '')
|
|
101
|
+
.replace(/\s+/g, ' ')
|
|
102
|
+
.trim()
|
|
103
|
+
.slice(0, 300);
|
|
104
|
+
}
|
|
105
|
+
if (!title || !group.url)
|
|
106
|
+
continue;
|
|
107
|
+
results.push({ rank: 0, title, url: group.url, site: group.site, snippet: '' });
|
|
108
|
+
}
|
|
109
|
+
// WHY NEXT FIRST IS DERIVED FROM THE PAGE, NOT ASSUMED.
|
|
110
|
+
// Bing's page size changed between result sets before (30, then 10): the pagination links name the first result of each numbered page, so the next page is the smallest first= above the current one, whatever the page size is today.
|
|
111
|
+
let nextFirst = null;
|
|
112
|
+
for (const link of links) {
|
|
113
|
+
const href = String(link?.href ?? '');
|
|
114
|
+
const linkHost = hostOf(href);
|
|
115
|
+
if (!linkHost || !BING_HOST.test(linkHost))
|
|
116
|
+
continue;
|
|
117
|
+
const match = /[?&]first=(\d+)/.exec(href);
|
|
118
|
+
const first = match?.[1];
|
|
119
|
+
if (!first)
|
|
120
|
+
continue;
|
|
121
|
+
const candidate = Number(first);
|
|
122
|
+
if (!Number.isFinite(candidate) || candidate <= currentFirst)
|
|
123
|
+
continue;
|
|
124
|
+
if (nextFirst === null || candidate < nextFirst)
|
|
125
|
+
nextFirst = candidate;
|
|
126
|
+
}
|
|
127
|
+
// WHY THE SNIPPET WALK SKIPS LEADING BLANK LINES.
|
|
128
|
+
// Bing puts a blank line between the title and its description, and a line that is only spaces counts as blank once trimmed: a parser that stopped at the first blank would return an empty snippet for every result.
|
|
129
|
+
// WHY DUPLICATE TITLES CARRY A COUNT, NOT A DELETE.
|
|
130
|
+
// Two cards may render the same title; a Set with one entry per title would drop the boundary for the second card after the first card's walk, and the snippet would bleed across cards.
|
|
131
|
+
// A multiset keeps one boundary per remaining occurrence.
|
|
132
|
+
const lines = String(text).split(/\r?\n/).map((line) => line.trim());
|
|
133
|
+
const pending = new Map();
|
|
134
|
+
for (const result of results)
|
|
135
|
+
pending.set(result.title, (pending.get(result.title) ?? 0) + 1);
|
|
136
|
+
const hasPending = (line) => (pending.get(line) ?? 0) > 0;
|
|
137
|
+
let cursor = 0;
|
|
138
|
+
const findTitle = (from, title) => {
|
|
139
|
+
for (let i = from; i < lines.length; i += 1)
|
|
140
|
+
if (lines[i] === title)
|
|
141
|
+
return i;
|
|
142
|
+
for (let i = from; i < lines.length; i += 1)
|
|
143
|
+
if (lines[i]?.startsWith(title))
|
|
144
|
+
return i;
|
|
145
|
+
return -1;
|
|
146
|
+
};
|
|
147
|
+
for (const result of results) {
|
|
148
|
+
pending.set(result.title, (pending.get(result.title) ?? 1) - 1);
|
|
149
|
+
const at = findTitle(cursor, result.title);
|
|
150
|
+
if (at < 0)
|
|
151
|
+
continue;
|
|
152
|
+
let k = at + 1;
|
|
153
|
+
while (k < lines.length && !lines[k])
|
|
154
|
+
k += 1;
|
|
155
|
+
const buf = [];
|
|
156
|
+
while (k < lines.length) {
|
|
157
|
+
const line = lines[k];
|
|
158
|
+
if (!line)
|
|
159
|
+
break;
|
|
160
|
+
if (DISPLAY_URL_LINE.test(line) || line.includes('›'))
|
|
161
|
+
break;
|
|
162
|
+
if (hasPending(line))
|
|
163
|
+
break;
|
|
164
|
+
buf.push(line);
|
|
165
|
+
if (buf.join(' ').length >= 600)
|
|
166
|
+
break;
|
|
167
|
+
k += 1;
|
|
168
|
+
}
|
|
169
|
+
result.snippet = buf.join(' ').replace(/\s+/g, ' ').trim().slice(0, 700);
|
|
170
|
+
cursor = Math.max(cursor, k);
|
|
171
|
+
}
|
|
172
|
+
results.forEach((result, index) => { result.rank = index + 1; });
|
|
173
|
+
return { results, nextFirst };
|
|
174
|
+
}
|
package/bridge-token.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// @last-edited: 2026-11-17 UTC+7.
|
|
2
|
+
// @title: bridge-token — the per-machine secret the local driver presents to the loopback bridge.
|
|
3
|
+
// @state: exports resolveBridgeToken and header constants; bridge-ws reads it once per server to gate POST endpoints.
|
|
4
|
+
// @dependencies: node:crypto, node:fs, node:os, node:path.
|
|
5
|
+
// WHY IT EXISTS.
|
|
6
|
+
// The loopback bridge owns the browser, and any local web page could reach its /command endpoint with a plain POST before it was gated.
|
|
7
|
+
// A random secret per machine answers "indistinguishable to a page on this machine, trivially readable by the processes that legitimately drive the browser".
|
|
8
|
+
// The token is never sent in a browser request: pages cannot read the file it lives in.
|
|
9
|
+
import { randomBytes } from 'node:crypto';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
const TOKEN_FILE = path.join(os.homedir(), '.navego', 'bridge-token');
|
|
14
|
+
let cached = null;
|
|
15
|
+
export function resolveBridgeToken() {
|
|
16
|
+
if (cached)
|
|
17
|
+
return cached;
|
|
18
|
+
if (process.env.OPERA_BRIDGE_TOKEN) {
|
|
19
|
+
cached = process.env.OPERA_BRIDGE_TOKEN;
|
|
20
|
+
return cached;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const stored = fs.readFileSync(TOKEN_FILE, 'utf8').trim();
|
|
24
|
+
if (stored) {
|
|
25
|
+
cached = stored;
|
|
26
|
+
return cached;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
}
|
|
31
|
+
const token = randomBytes(32).toString('hex');
|
|
32
|
+
try {
|
|
33
|
+
fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true, mode: 0o700 });
|
|
34
|
+
fs.writeFileSync(TOKEN_FILE, token, { mode: 0o600 });
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
}
|
|
38
|
+
cached = token;
|
|
39
|
+
return cached;
|
|
40
|
+
}
|
|
41
|
+
export function header() {
|
|
42
|
+
return { 'x-opera-bridge-token': resolveBridgeToken() };
|
|
43
|
+
}
|