@edlsh/browse-core 0.7.0 → 0.8.0
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 +8 -2
- package/dist/broker-client.d.ts +4 -2
- package/dist/broker-client.js +10 -5
- package/dist/broker-protocol.d.ts +3 -2
- package/dist/broker-protocol.js +11 -7
- package/dist/broker.js +12 -12
- package/dist/config.d.ts +101 -0
- package/dist/config.js +78 -0
- package/dist/contexts.d.ts +10 -0
- package/dist/contexts.js +27 -0
- package/dist/errors.d.ts +29 -0
- package/dist/errors.js +83 -0
- package/dist/host-model.d.ts +24 -0
- package/dist/host-model.js +35 -0
- package/dist/index.d.ts +10 -13
- package/dist/index.js +11 -15
- package/dist/jev.js +9 -3
- package/dist/page-operations.d.ts +11 -1
- package/dist/page-operations.js +62 -11
- package/dist/real-browser-ai.d.ts +1 -1
- package/dist/real-browser-ai.js +1 -1
- package/dist/real-browser-client.js +1 -1
- package/dist/real-browser-session.d.ts +1 -1
- package/dist/real-browser-session.js +24 -5
- package/dist/schema.d.ts +32 -0
- package/dist/schema.js +22 -6
- package/dist/session-runtime.d.ts +42 -0
- package/dist/session-runtime.js +144 -0
- package/dist/session.d.ts +27 -118
- package/dist/session.js +134 -350
- package/dist/settings.js +47 -6
- package/dist/tool-results.d.ts +28 -0
- package/dist/tool-results.js +40 -0
- package/extensions/http-auth/README.md +27 -0
- package/extensions/http-auth/background.js +85 -0
- package/extensions/http-auth/manifest.json +27 -0
- package/extensions/http-auth/native/README.md +31 -0
- package/extensions/http-auth/native/host.py +97 -0
- package/extensions/http-auth/native/install.py +62 -0
- package/extensions/http-auth/options.html +25 -0
- package/extensions/http-auth/options.js +36 -0
- package/extensions/http-auth/origin.js +16 -0
- package/package.json +13 -2
package/dist/settings.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
-
import { dirname } from "node:path";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
5
|
import { z } from "zod";
|
|
4
|
-
import { BrowseToolError } from "./
|
|
6
|
+
import { BrowseToolError } from "./errors.js";
|
|
5
7
|
/** Per-profile file, in the profile's agent dir, holding every /browse setting. */
|
|
6
8
|
export const SETTINGS_FILE = "browserbase-ai.json";
|
|
7
9
|
/** Picker row that clears the choice, so Stagehand runs each conversation's own model. */
|
|
@@ -35,8 +37,43 @@ export async function readSettings(path) {
|
|
|
35
37
|
throw new BrowseToolError("settings_config", `Could not read the browse settings from ${path}. Fix or delete the file, then run /browse to choose again.`);
|
|
36
38
|
}
|
|
37
39
|
}
|
|
40
|
+
const writes = new Map();
|
|
38
41
|
/** Saves one setting for every conversation in the profile; undefined clears it, and the file goes with the last one. */
|
|
39
42
|
export async function writeSetting(path, key, value) {
|
|
43
|
+
path = resolve(path);
|
|
44
|
+
const pending = (writes.get(path) ?? Promise.resolve()).catch(() => { }).then(async () => {
|
|
45
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
46
|
+
const lock = path + ".lock";
|
|
47
|
+
for (const deadline = Date.now() + 5000;;) {
|
|
48
|
+
try {
|
|
49
|
+
await mkdir(lock, { mode: 0o700 });
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (error.code !== "EEXIST")
|
|
54
|
+
throw error;
|
|
55
|
+
if (Date.now() >= deadline)
|
|
56
|
+
throw new BrowseToolError("settings_busy", "Another process is saving browse settings. Retry; if it exited, remove the stale lock directory " + lock);
|
|
57
|
+
await delay(20);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
await updateSetting(path, key, value);
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await rm(lock, { recursive: true });
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
writes.set(path, pending);
|
|
68
|
+
try {
|
|
69
|
+
await pending;
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
if (writes.get(path) === pending)
|
|
73
|
+
writes.delete(path);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function updateSetting(path, key, value) {
|
|
40
77
|
const settings = BrowseSettings.parse({ ...await readSettings(path), [key]: value });
|
|
41
78
|
if (value === undefined)
|
|
42
79
|
delete settings[key];
|
|
@@ -44,11 +81,15 @@ export async function writeSetting(path, key, value) {
|
|
|
44
81
|
await rm(path, { force: true });
|
|
45
82
|
return;
|
|
46
83
|
}
|
|
47
|
-
await mkdir(dirname(path), { recursive: true });
|
|
48
84
|
// Rename into place so another host process reading the settings never sees a partial file.
|
|
49
|
-
const partial = `${path}.${
|
|
50
|
-
|
|
51
|
-
|
|
85
|
+
const partial = `${path}.${randomUUID()}.tmp`;
|
|
86
|
+
try {
|
|
87
|
+
await writeFile(partial, `${JSON.stringify(settings, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
88
|
+
await rename(partial, path);
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
await rm(partial, { force: true });
|
|
92
|
+
}
|
|
52
93
|
}
|
|
53
94
|
export function roleChoice(settings, role) {
|
|
54
95
|
return settings[ROLE_KEYS[role]];
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { Json } from "./broker-protocol.ts";
|
|
3
|
+
import type { BrowserOutput } from "./session.ts";
|
|
4
|
+
export declare function redactMetadata(metadata: object, redact: (value: string) => string): Record<string, Json>;
|
|
5
|
+
/** One redacted oversized result per binding, in memory only. Never store screenshots or user-only control links. */
|
|
6
|
+
export declare class ToolResults {
|
|
7
|
+
private page?;
|
|
8
|
+
clear(): void;
|
|
9
|
+
encode(output: BrowserOutput, owner: string, redact: (text: string) => string): {
|
|
10
|
+
json: string;
|
|
11
|
+
metadata: Record<string, z.JSONType>;
|
|
12
|
+
image: Uint8Array<ArrayBufferLike> | undefined;
|
|
13
|
+
isError: boolean;
|
|
14
|
+
};
|
|
15
|
+
read(owner: string, id: string, offset: number): {
|
|
16
|
+
resultId: string;
|
|
17
|
+
offset: number;
|
|
18
|
+
chunk: string;
|
|
19
|
+
totalChars: number;
|
|
20
|
+
nextOffset?: number | undefined;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export declare function encodeFailure(cause: unknown, redact: (text: string) => string): {
|
|
24
|
+
json: string;
|
|
25
|
+
metadata: Record<string, z.JSONType>;
|
|
26
|
+
isError: true;
|
|
27
|
+
image: undefined;
|
|
28
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { BrowseToolError } from "./errors.js";
|
|
4
|
+
export function redactMetadata(metadata, redact) {
|
|
5
|
+
const clean = (v) => typeof v === "string" ? redact(v) : Array.isArray(v) ? v.map(clean)
|
|
6
|
+
: v !== null && typeof v === "object" ? Object.fromEntries(Object.entries(v).map(([k, value]) => [redact(k), clean(value)])) : v;
|
|
7
|
+
const json = JSON.stringify(metadata, (_k, v) => typeof v === "bigint" ? String(v) : v);
|
|
8
|
+
return Object.fromEntries(Object.entries(JSON.parse(json)).map(([k, v]) => [k, clean(v)]));
|
|
9
|
+
}
|
|
10
|
+
/** One redacted oversized result per binding, in memory only. Never store screenshots or user-only control links. */
|
|
11
|
+
export class ToolResults {
|
|
12
|
+
page;
|
|
13
|
+
clear() { this.page = undefined; }
|
|
14
|
+
encode(output, owner, redact) {
|
|
15
|
+
const { liveViewUrl: _private, image, isError, ...rest } = output;
|
|
16
|
+
let metadata = redactMetadata(rest, redact), json = JSON.stringify(metadata);
|
|
17
|
+
if (json.length > 60_000) {
|
|
18
|
+
const id = randomUUID(), preview = json.slice(0, 3000);
|
|
19
|
+
this.page = { owner, id, text: json };
|
|
20
|
+
metadata = Object.fromEntries(["action", "backend", "origin", "sessionId", "tabId", "code", "batch"].filter(k => k in metadata).map(k => [k, metadata[k]]));
|
|
21
|
+
Object.assign(metadata, { truncated: true, resultId: id, totalChars: json.length, nextOffset: preview.length, preview });
|
|
22
|
+
json = JSON.stringify(metadata);
|
|
23
|
+
}
|
|
24
|
+
return { json, metadata, image, isError: Boolean(isError) };
|
|
25
|
+
}
|
|
26
|
+
read(owner, id, offset) {
|
|
27
|
+
if (!this.page || this.page.owner !== owner || this.page.id !== id)
|
|
28
|
+
throw new BrowseToolError("result_expired", "This result is not retained by this conversation.");
|
|
29
|
+
const { text } = this.page, chunk = text.slice(offset, offset + 8000), end = offset + chunk.length;
|
|
30
|
+
return { resultId: id, offset, chunk, totalChars: text.length, ...(end < text.length ? { nextOffset: end } : {}) };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function encodeFailure(cause, redact) {
|
|
34
|
+
const code = cause instanceof BrowseToolError ? cause.code : cause instanceof z.ZodError ? "invalid_arguments"
|
|
35
|
+
: cause instanceof Error && cause.name === "AbortError" ? "cancelled" : "browser_error";
|
|
36
|
+
const raw = cause instanceof z.ZodError ? z.prettifyError(cause) : cause instanceof Error ? cause.message : "Browser operation failed.";
|
|
37
|
+
const metadata = redactMetadata({ code, message: raw, ...(cause instanceof BrowseToolError && cause.batch ? { batch: cause.batch } : {}) }, redact);
|
|
38
|
+
metadata.message = String(metadata.message).slice(0, 4000);
|
|
39
|
+
return { json: JSON.stringify(metadata), metadata, isError: true, image: undefined };
|
|
40
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Browse HTTP sign-in
|
|
2
|
+
|
|
3
|
+
Enable automatic HTTP Basic sign-in for one website in your everyday Chrome or Helium profile. The companion listens for a top-level navigation that receives an HTTP Basic challenge and asks a local helper for the credentials. Chrome handles the sign-in itself.
|
|
4
|
+
|
|
5
|
+
## Set up on macOS
|
|
6
|
+
|
|
7
|
+
1. Install the local helper and register it with the browser you use. From the repository root, run `python3 extensions/http-auth/native/install.py chrome`, substituting `helium` for Helium. You can specify both browser names.
|
|
8
|
+
2. Configure the helper's origin-to-provider mapping. The helper reads `~/.config/browse/http-auth.json` or the same path under `$XDG_CONFIG_HOME` starting at `browse/`. Make the file readable and writable only by your account (mode `0600`). Each exact origin maps to an argument array for a local executable that reads credentials from your configured secrets manager. The first argument must be an absolute executable path. The helper passes a JSON object with the `origin` on stdin. The provider returns a JSON object with `username` and `password` on stdout.
|
|
9
|
+
3. Open the browser's extensions manager, enable **Developer mode**, choose **Load unpacked**, and select this directory. Keep the directory in place while the extension is installed.
|
|
10
|
+
4. Open **Browse HTTP sign-in** from the extensions menu. Enter the full site origin, such as `https://example.com`, choose **Enable sign-in**, and approve the site's permission.
|
|
11
|
+
5. Open the protected page. If a native sign-in sheet was already open during setup, cancel it and reload the page to issue a fresh request.
|
|
12
|
+
|
|
13
|
+
The extension remembers the selected site across browser restarts. Use **Clear sign-in** to remove the site and its permission. Chrome can reuse a successful HTTP login in other tabs of the profile. Quit the browser completely to clear its in-memory authentication cache after revoking access.
|
|
14
|
+
|
|
15
|
+
## Scope
|
|
16
|
+
|
|
17
|
+
The scheme, host and port must match the configured origin. Use HTTPS for remote sites. HTTP is available for tests on `localhost` and `127.0.0.1`. Proxy authentication, frames and subresources keep the browser's normal behavior. If the helper is unavailable or the server rejects its credentials, the native prompt takes over. The extension submits credentials at most once per challenged request.
|
|
18
|
+
|
|
19
|
+
## Browser verification
|
|
20
|
+
|
|
21
|
+
On Linux with Chromium, Node.js 22 or newer and Python 3 installed, run:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
CHROME_PATH=/usr/bin/chromium node test/browser.mjs
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The fixture creates an isolated browser profile, installs the companion and its native messaging host there, and uses a generated credential. Two local HTTP servers verify that the chosen origin authenticates and a different port receives no credentials.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { siteOrigin, sitePermission } from "./origin.js";
|
|
2
|
+
|
|
3
|
+
const grants = chrome.storage.local;
|
|
4
|
+
const attempts = chrome.storage.session;
|
|
5
|
+
const navigation = { urls: ["http://*/*", "https://*/*"], types: ["main_frame"] };
|
|
6
|
+
|
|
7
|
+
chrome.action.onClicked.addListener(() => chrome.runtime.openOptionsPage());
|
|
8
|
+
|
|
9
|
+
async function answer(details) {
|
|
10
|
+
if (details.tabId < 0 || details.isProxy || details.scheme.toLowerCase() !== "basic") return {};
|
|
11
|
+
const url = new URL(details.url);
|
|
12
|
+
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
13
|
+
if (details.challenger.host.toLowerCase() !== url.hostname || details.challenger.port !== port) return {};
|
|
14
|
+
|
|
15
|
+
const attempt = "attempt:" + details.requestId;
|
|
16
|
+
const [{ origin }, prior] = await Promise.all([grants.get("origin"), attempts.get(attempt)]);
|
|
17
|
+
if (origin !== url.origin || prior[attempt]) return {};
|
|
18
|
+
await attempts.set({ [attempt]: true });
|
|
19
|
+
const result = await chrome.runtime.sendNativeMessage("sh.edl.browse_http_auth", { origin });
|
|
20
|
+
if (!result || typeof result.username !== "string" || !result.username || result.username.includes(":")
|
|
21
|
+
|| typeof result.password !== "string") return {};
|
|
22
|
+
// Revocation while the credential manager was unlocking takes effect on this challenge.
|
|
23
|
+
if ((await grants.get("origin")).origin !== origin) return {};
|
|
24
|
+
return { authCredentials: { username: result.username, password: result.password } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function answerChallenge(details, reply) {
|
|
28
|
+
answer(details).then(reply, () => reply({}));
|
|
29
|
+
}
|
|
30
|
+
function finished(details) {
|
|
31
|
+
void attempts.remove("attempt:" + details.requestId);
|
|
32
|
+
}
|
|
33
|
+
// Chrome ignores listeners registered before the first host grant. Rebind them when permissions change.
|
|
34
|
+
function listen() {
|
|
35
|
+
for (const [event, listener] of [
|
|
36
|
+
[chrome.webRequest.onAuthRequired, answerChallenge],
|
|
37
|
+
[chrome.webRequest.onCompleted, finished],
|
|
38
|
+
[chrome.webRequest.onErrorOccurred, finished],
|
|
39
|
+
]) event.removeListener(listener);
|
|
40
|
+
chrome.webRequest.onAuthRequired.addListener(answerChallenge, navigation, ["asyncBlocking"]);
|
|
41
|
+
chrome.webRequest.onCompleted.addListener(finished, navigation);
|
|
42
|
+
chrome.webRequest.onErrorOccurred.addListener(finished, navigation);
|
|
43
|
+
}
|
|
44
|
+
listen();
|
|
45
|
+
chrome.permissions.onAdded.addListener(listen);
|
|
46
|
+
|
|
47
|
+
// Keep only the permission for the currently configured site, including after a browser restart.
|
|
48
|
+
async function trimPermissions() {
|
|
49
|
+
const { origin } = await grants.get("origin");
|
|
50
|
+
const keep = origin && sitePermission(origin);
|
|
51
|
+
const { origins = [] } = await chrome.permissions.getAll();
|
|
52
|
+
const remove = origins.filter(origin => origin !== keep);
|
|
53
|
+
if (remove.length) await chrome.permissions.remove({ origins: remove });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let updating = Promise.resolve();
|
|
57
|
+
function serialize(operation) {
|
|
58
|
+
const next = updating.then(operation);
|
|
59
|
+
updating = next.catch(() => {});
|
|
60
|
+
return next;
|
|
61
|
+
}
|
|
62
|
+
chrome.runtime.onStartup.addListener(() => { void serialize(trimPermissions); });
|
|
63
|
+
chrome.permissions.onRemoved.addListener(() => {
|
|
64
|
+
void serialize(async () => {
|
|
65
|
+
const { origin } = await grants.get("origin");
|
|
66
|
+
if (origin && !await chrome.permissions.contains({ origins: [sitePermission(origin)] })) {
|
|
67
|
+
await grants.remove("origin");
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
chrome.runtime.onMessage.addListener((message, sender, reply) => {
|
|
73
|
+
if (sender.url !== chrome.runtime.getURL("options.html")) return;
|
|
74
|
+
serialize(async () => {
|
|
75
|
+
if (message.action === "clear") {
|
|
76
|
+
await grants.remove("origin");
|
|
77
|
+
} else if (message.action === "save") {
|
|
78
|
+
const origin = siteOrigin(message.origin);
|
|
79
|
+
if (!await chrome.permissions.contains({ origins: [sitePermission(origin)] })) throw new Error();
|
|
80
|
+
await grants.set({ origin });
|
|
81
|
+
} else throw new Error();
|
|
82
|
+
await trimPermissions();
|
|
83
|
+
}).then(() => reply(true), () => reply(false));
|
|
84
|
+
return true;
|
|
85
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"manifest_version": 3,
|
|
3
|
+
"name": "Browse HTTP sign-in",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"description": "Answer HTTP Basic sign-in requests for a site you choose.",
|
|
6
|
+
"permissions": [
|
|
7
|
+
"storage",
|
|
8
|
+
"webRequest",
|
|
9
|
+
"webRequestAuthProvider",
|
|
10
|
+
"nativeMessaging"
|
|
11
|
+
],
|
|
12
|
+
"optional_host_permissions": [
|
|
13
|
+
"https://*/*",
|
|
14
|
+
"http://localhost/*",
|
|
15
|
+
"http://127.0.0.1/*"
|
|
16
|
+
],
|
|
17
|
+
"background": {
|
|
18
|
+
"service_worker": "background.js",
|
|
19
|
+
"type": "module"
|
|
20
|
+
},
|
|
21
|
+
"action": {
|
|
22
|
+
"default_title": "Configure HTTP sign-in"
|
|
23
|
+
},
|
|
24
|
+
"options_page": "options.html",
|
|
25
|
+
"incognito": "not_allowed",
|
|
26
|
+
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsrpzYqqBt4iy8ZSiyJ9HJRp+Hn5DF8MLxZA1av+JRKaYfI1Br52EmFXHIVPOzZ/YfB1pu5s2Pz0fEux4lM9zqM5Y03yuU4nTQtd4eqYfNgp8pG462gFb6M85ZBPmWyzUz9txq4umDuHldC3VT/OVgfKgIIWbf29+J2m1rZMr0QZg0fXJ+ivQDL4lFESWrHjkZbx+8lV5dw0MXlHRLbRTqC/CgQ2IQ1Lg9ixI1xVH7poPxIc91t0vpWn3T7QhJfM8g1RF7ELPxjFQch3+MW4WcNnCVWYjhs7TJU1MMyblW0FsgyAtaScnfkqKJGpY3oRrmXzYrtndhbnOQv7Iuha+RQIDAQAB"
|
|
27
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Local HTTP sign-in host
|
|
2
|
+
|
|
3
|
+
Each configured origin has a local credential provider. When Chrome requests a username and password, the host looks up the exact origin and runs its provider. The provider can read the current Login from your configured secrets manager on each challenge.
|
|
4
|
+
|
|
5
|
+
## Set up
|
|
6
|
+
|
|
7
|
+
From this directory, register the host for the macOS browser you use. Python 3.8 or later must be available to the browser.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
python3 install.py chrome
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Use `helium` for Helium, or `chrome helium` for both. For a local managed browser on macOS or Linux, `python3 install.py managed` installs just the resolver executable. Each installation places the host at `~/.local/lib/browse-http-auth/host.py`. Rerunning the installer updates the executable and checks the browser registration.
|
|
14
|
+
|
|
15
|
+
Create `~/.config/browse/http-auth.json` with mode `0600`, owned by your account. The host honors an absolute `XDG_CONFIG_HOME` when set. Each key is a serialized HTTPS origin, including any non-default port. Local fixtures may use HTTP on `localhost` or `127.0.0.1`.
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"https://example.com": ["/absolute/path/to/read-storefront-login"]
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Use a trusted executable under your control. Its fixed arguments, if any, go in the same array. Keep account credentials in the secrets manager. Place only the executable and any non-secret arguments in this file. Desktop-launched browsers may have a different environment from an interactive terminal, so the provider must be able to access the configured secrets manager in that context.
|
|
24
|
+
|
|
25
|
+
The provider receives a JSON object containing `origin` on stdin. Its stdout must contain one JSON object with nonempty string fields `username` and `password`. The host consumes this output over a pipe. Refusal, invalid output or a 12-second timeout leaves the challenge unanswered. Ensure the provider writes diagnostics without private data.
|
|
26
|
+
|
|
27
|
+
## Client interfaces
|
|
28
|
+
|
|
29
|
+
The companion uses native messaging host `sh.edl.browse_http_auth`. Its registration allows the packaged extension's fixed ID. A managed client invokes the installed host with `--resolve` and uses pipes for stdin and stdout. Both interfaces accept `{"origin":"https://example.com"}`, return the provider's username and password on success, and return `{}` when no credential is available. The native messaging transport wraps each JSON message in a four-byte native-endian length prefix.
|
|
30
|
+
|
|
31
|
+
Run `python3 -m unittest test_host` here to verify both interfaces using an isolated temporary provider.
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read one origin, invoke the locally configured provider and answer on stdout."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import stat
|
|
8
|
+
import struct
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
CALLER = "chrome-extension://gegbngaiinihchnmbppmhgepfjjodifa/"
|
|
15
|
+
MAX_REQUEST = 4096
|
|
16
|
+
MAX_RESULT = 64 * 1024
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def resolve(request):
|
|
20
|
+
if not isinstance(request, dict) or set(request) != {"origin"}:
|
|
21
|
+
return {}
|
|
22
|
+
origin = request["origin"]
|
|
23
|
+
if not isinstance(origin, str) or not origin.isascii() or any(ord(c) < 33 or ord(c) == 127 for c in origin):
|
|
24
|
+
return {}
|
|
25
|
+
url = urlsplit(origin)
|
|
26
|
+
if url.scheme != "https" and not (url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1")):
|
|
27
|
+
return {}
|
|
28
|
+
if not url.hostname or url.username is not None or any(c in url.netloc for c in ("\\", "*", "%")):
|
|
29
|
+
return {}
|
|
30
|
+
# Compare serialized origins, including port. A path, query, fragment or userinfo cannot select a provider.
|
|
31
|
+
host = f"[{url.hostname}]" if ":" in url.hostname else url.hostname
|
|
32
|
+
port = url.port
|
|
33
|
+
authority = host if port in (None, 443 if url.scheme == "https" else 80) else f"{host}:{port}"
|
|
34
|
+
if origin != f"{url.scheme}://{authority}":
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
config_root = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
38
|
+
if not config_root.is_absolute():
|
|
39
|
+
return {}
|
|
40
|
+
config_path = config_root / "browse" / "http-auth.json"
|
|
41
|
+
with os.fdopen(os.open(config_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)) as config:
|
|
42
|
+
info = os.fstat(config.fileno())
|
|
43
|
+
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
|
|
44
|
+
return {}
|
|
45
|
+
providers = json.load(config)
|
|
46
|
+
if not isinstance(providers, dict):
|
|
47
|
+
return {}
|
|
48
|
+
command = providers.get(origin)
|
|
49
|
+
if (not isinstance(command, list) or not command or not all(isinstance(arg, str) and arg for arg in command)
|
|
50
|
+
or not os.path.isabs(command[0])):
|
|
51
|
+
return {}
|
|
52
|
+
|
|
53
|
+
proc = subprocess.run(command, input=json.dumps(request).encode(), stdout=subprocess.PIPE,
|
|
54
|
+
stderr=subprocess.DEVNULL, timeout=12, check=True)
|
|
55
|
+
if len(proc.stdout) > MAX_RESULT:
|
|
56
|
+
return {}
|
|
57
|
+
result = json.loads(proc.stdout)
|
|
58
|
+
if not isinstance(result, dict):
|
|
59
|
+
return {}
|
|
60
|
+
login = {key: result.get(key) for key in ("username", "password")}
|
|
61
|
+
if not all(isinstance(value, str) and value for value in login.values()):
|
|
62
|
+
return {}
|
|
63
|
+
return login
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def main():
|
|
67
|
+
cli = sys.argv[1:] == ["--resolve"]
|
|
68
|
+
if cli and sys.stdout.isatty():
|
|
69
|
+
return 1
|
|
70
|
+
if not cli and sys.argv[1:] != [CALLER]:
|
|
71
|
+
return 1
|
|
72
|
+
answer = {}
|
|
73
|
+
try:
|
|
74
|
+
stream = sys.stdin.buffer
|
|
75
|
+
if cli:
|
|
76
|
+
raw = stream.read(MAX_REQUEST + 1)
|
|
77
|
+
else:
|
|
78
|
+
size, = struct.unpack("=I", stream.read(4))
|
|
79
|
+
if not 0 < size <= MAX_REQUEST:
|
|
80
|
+
raise ValueError("invalid frame length")
|
|
81
|
+
raw = stream.read(size)
|
|
82
|
+
if len(raw) != size:
|
|
83
|
+
raise ValueError("incomplete frame")
|
|
84
|
+
if len(raw) <= MAX_REQUEST:
|
|
85
|
+
answer = resolve(json.loads(raw))
|
|
86
|
+
except (OSError, ValueError, RecursionError, subprocess.SubprocessError, struct.error):
|
|
87
|
+
# Providers, JSON parsers and I/O errors can all include private data in their diagnostics.
|
|
88
|
+
pass
|
|
89
|
+
output = json.dumps(answer, separators=(",", ":")).encode()
|
|
90
|
+
if not cli:
|
|
91
|
+
sys.stdout.buffer.write(struct.pack("=I", len(output)))
|
|
92
|
+
sys.stdout.buffer.write(output)
|
|
93
|
+
return 0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
if __name__ == "__main__":
|
|
97
|
+
sys.exit(main())
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Install the local resolver and its user-level native messaging registration."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import platform
|
|
9
|
+
import tempfile
|
|
10
|
+
|
|
11
|
+
from host import CALLER
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
NAME = "sh.edl.browse_http_auth"
|
|
15
|
+
BROWSERS = {"chrome": "Google/Chrome", "helium": "net.imput.helium"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def replace_file(path, data, mode):
|
|
19
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
20
|
+
if path.exists() and not path.is_symlink() and path.read_bytes() == data and path.stat().st_mode & 0o777 == mode:
|
|
21
|
+
return
|
|
22
|
+
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as new:
|
|
23
|
+
temporary = Path(new.name)
|
|
24
|
+
try:
|
|
25
|
+
os.fchmod(new.fileno(), mode)
|
|
26
|
+
new.write(data)
|
|
27
|
+
new.flush()
|
|
28
|
+
os.replace(temporary, path)
|
|
29
|
+
finally:
|
|
30
|
+
temporary.unlink(missing_ok=True)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def install(user_home, browsers):
|
|
34
|
+
executable = user_home / ".local/lib/browse-http-auth/host.py"
|
|
35
|
+
manifest = {
|
|
36
|
+
"name": NAME, "description": "Resolve credentials for the configured HTTP origin",
|
|
37
|
+
"path": str(executable), "type": "stdio", "allowed_origins": [CALLER],
|
|
38
|
+
}
|
|
39
|
+
files = [
|
|
40
|
+
user_home / "Library/Application Support" / BROWSERS[browser] / "NativeMessagingHosts" / f"{NAME}.json"
|
|
41
|
+
for browser in browsers if browser != "managed"
|
|
42
|
+
]
|
|
43
|
+
for path in files:
|
|
44
|
+
if path.is_symlink() or (path.exists() and json.loads(path.read_bytes()) != manifest):
|
|
45
|
+
raise ValueError(f"Existing registration differs: {path}")
|
|
46
|
+
replace_file(executable, Path(__file__).with_name("host.py").read_bytes(), 0o700)
|
|
47
|
+
for path in files:
|
|
48
|
+
replace_file(path, (json.dumps(manifest, indent=2) + "\n").encode(), 0o600)
|
|
49
|
+
return executable
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
54
|
+
parser.add_argument("target", nargs="+", choices=["managed", *BROWSERS],
|
|
55
|
+
help="managed installs the CLI only; chrome and helium also register the native messaging host")
|
|
56
|
+
args = parser.parse_args()
|
|
57
|
+
if platform.system() != "Darwin" and any(target != "managed" for target in args.target):
|
|
58
|
+
parser.error("Browser registration is supported on macOS.")
|
|
59
|
+
try:
|
|
60
|
+
print(install(Path.home(), args.target))
|
|
61
|
+
except (OSError, ValueError) as error:
|
|
62
|
+
parser.exit(1, f"Install failed. {error}\n")
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<meta charset="utf-8">
|
|
4
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5
|
+
<title>Browse HTTP sign-in</title>
|
|
6
|
+
<style>
|
|
7
|
+
:root { color-scheme: light dark; font: 16px/1.5 system-ui, sans-serif; }
|
|
8
|
+
body { max-width: 32rem; margin: 4rem auto; padding: 0 1.5rem; }
|
|
9
|
+
h1 { line-height: 1.2; }
|
|
10
|
+
label, input { display: block; }
|
|
11
|
+
label { margin: 1rem 0; }
|
|
12
|
+
input, button { font: inherit; padding: .45rem .75rem; }
|
|
13
|
+
input { width: 100%; box-sizing: border-box; }
|
|
14
|
+
button { margin-right: .4rem; }
|
|
15
|
+
</style>
|
|
16
|
+
<h1>HTTP sign-in</h1>
|
|
17
|
+
<p>Choose the site whose HTTP sign-in prompt you want answered automatically. Your configured credential helper supplies the username and password.</p>
|
|
18
|
+
<form id="settings">
|
|
19
|
+
<label>Site origin <input id="origin" type="url" placeholder="https://example.com" required></label>
|
|
20
|
+
<button type="submit">Enable sign-in</button>
|
|
21
|
+
<button type="button" id="clear">Clear sign-in</button>
|
|
22
|
+
</form>
|
|
23
|
+
<p id="status" role="status" aria-live="polite"></p>
|
|
24
|
+
<script type="module" src="options.js"></script>
|
|
25
|
+
</html>
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { siteOrigin, sitePermission } from "./origin.js";
|
|
2
|
+
|
|
3
|
+
const form = document.querySelector("form");
|
|
4
|
+
const origin = document.querySelector("#origin");
|
|
5
|
+
const status = document.querySelector("#status");
|
|
6
|
+
|
|
7
|
+
function show(login) {
|
|
8
|
+
if (login) origin.value = login.origin;
|
|
9
|
+
status.textContent = login ? "Sign-in enabled for " + login.origin : "Automatic sign-in is off.";
|
|
10
|
+
}
|
|
11
|
+
const saved = await chrome.storage.local.get("origin");
|
|
12
|
+
show(saved.origin ? saved : null);
|
|
13
|
+
|
|
14
|
+
form.addEventListener("submit", async event => {
|
|
15
|
+
event.preventDefault();
|
|
16
|
+
try {
|
|
17
|
+
const site = siteOrigin(origin.value);
|
|
18
|
+
const granted = await chrome.permissions.request({ origins: [sitePermission(site)] });
|
|
19
|
+
if (!granted) {
|
|
20
|
+
status.textContent = "Site permission was declined.";
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (!await chrome.runtime.sendMessage({ action: "save", origin: site })) throw new Error();
|
|
24
|
+
show({ origin: site });
|
|
25
|
+
} catch {
|
|
26
|
+
status.textContent = "Could not enable sign-in. Check the site origin and site permissions.";
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
document.querySelector("#clear").addEventListener("click", async () => {
|
|
30
|
+
if (await chrome.runtime.sendMessage({ action: "clear" })) {
|
|
31
|
+
form.reset();
|
|
32
|
+
show(null);
|
|
33
|
+
} else {
|
|
34
|
+
status.textContent = "Could not clear sign-in. Try again.";
|
|
35
|
+
}
|
|
36
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Chrome grants host permissions across ports. The credential itself is bound to a single origin.
|
|
2
|
+
export function siteOrigin(value) {
|
|
3
|
+
const url = new URL(value);
|
|
4
|
+
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
5
|
+
if ((url.protocol !== "https:" && !(url.protocol === "http:" && loopback))
|
|
6
|
+
|| url.username || url.password || url.href !== url.origin + "/"
|
|
7
|
+
|| url.hostname.includes("*")) {
|
|
8
|
+
throw new Error("Enter an HTTPS origin such as https://example.com.");
|
|
9
|
+
}
|
|
10
|
+
return url.origin;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function sitePermission(origin) {
|
|
14
|
+
const url = new URL(origin);
|
|
15
|
+
return url.protocol + "//" + url.hostname + "/*";
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@edlsh/browse-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Host-neutral browser core (Browserbase, local Chrome, remote CDP, Stagehand) shared by omp-browse, pi-browse, and hermes-browse",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"browser",
|
|
@@ -33,6 +33,15 @@
|
|
|
33
33
|
},
|
|
34
34
|
"files": [
|
|
35
35
|
"dist",
|
|
36
|
+
"extensions/http-auth/README.md",
|
|
37
|
+
"extensions/http-auth/background.js",
|
|
38
|
+
"extensions/http-auth/manifest.json",
|
|
39
|
+
"extensions/http-auth/options.html",
|
|
40
|
+
"extensions/http-auth/options.js",
|
|
41
|
+
"extensions/http-auth/origin.js",
|
|
42
|
+
"extensions/http-auth/native/README.md",
|
|
43
|
+
"extensions/http-auth/native/host.py",
|
|
44
|
+
"extensions/http-auth/native/install.py",
|
|
36
45
|
"README.md",
|
|
37
46
|
"LICENSE"
|
|
38
47
|
],
|
|
@@ -41,7 +50,9 @@
|
|
|
41
50
|
"typecheck": "tsc --noEmit",
|
|
42
51
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/node-sqlite.d.ts dist/",
|
|
43
52
|
"check:package": "node scripts/check-package.mjs",
|
|
44
|
-
"
|
|
53
|
+
"test:helper": "python3 -B -m unittest discover -s extensions/http-auth/native",
|
|
54
|
+
"test:input": "bun test/input.integration.ts",
|
|
55
|
+
"check": "bun run test && bun run test:helper && bun run typecheck && bun run build && bun run check:package",
|
|
45
56
|
"prepublishOnly": "bun run build",
|
|
46
57
|
"test:http-auth": "bun test/http-auth.integration.ts",
|
|
47
58
|
"test:local": "bun test/local-browser.integration.ts",
|