@1outres/dsh-bot-connector-browser 0.3.0 → 0.4.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.
@@ -0,0 +1,143 @@
1
+ /**
2
+ * What the browser's login helpers in the bot's VM (vm/helper/) and the
3
+ * Host say to each other over the helper's standard input and output
4
+ * (docs/specs/bot-vaults.md §8). Every line is JSON; the only secret is
5
+ * the raw bytes that follow a line announcing their `length`. A helper
6
+ * answers with closed codes only, never with text of its own.
7
+ */
8
+
9
+ /** Why a helper stopped; each has a fixed explanation for the model. */
10
+ export type HelperFailure =
11
+ | "devtools"
12
+ | "not-found"
13
+ | "ambiguous"
14
+ | "not-editable"
15
+ | "not-password-field"
16
+ | "not-text"
17
+ | "opaque-origin"
18
+ | "origin-changed"
19
+ | "focus-lost"
20
+ | "rejected"
21
+ | "protocol"
22
+ | "failed"
23
+
24
+ /** Why an offered passkey went away. */
25
+ export type PasskeyEnd = "used" | "expired" | "navigated" | "closed" | "released"
26
+
27
+ export type HelperReply =
28
+ | { readonly kind: "located"; readonly origin: string; readonly element?: string }
29
+ | { readonly kind: "filled"; readonly submitted: boolean }
30
+ | { readonly kind: "ready" }
31
+ | { readonly kind: "ended"; readonly reason: PasskeyEnd }
32
+ | { readonly kind: "cancelled" }
33
+ | { readonly kind: "error"; readonly code: HelperFailure }
34
+
35
+ /** The first line to the fill helper. */
36
+ export interface FillRequest {
37
+ readonly devtools: string
38
+ readonly mark: string
39
+ readonly field: "username" | "password" | "otp"
40
+ }
41
+
42
+ /** The line before the value's bytes. */
43
+ export interface FillOrder {
44
+ readonly fill: { readonly origin: string; readonly submit: boolean; readonly length: number }
45
+ }
46
+
47
+ /** The first line to the passkey helper. */
48
+ export interface PasskeyRequest {
49
+ readonly devtools: string
50
+ readonly mark: string
51
+ }
52
+
53
+ /** The line before the private key's bytes (PKCS#8 DER). */
54
+ export interface PasskeyOrder {
55
+ readonly passkey: {
56
+ readonly origin: string
57
+ readonly rpId: string
58
+ readonly credentialId: string
59
+ readonly userHandle?: string
60
+ readonly signCount: number
61
+ readonly seconds: number
62
+ readonly length: number
63
+ }
64
+ }
65
+
66
+ const FAILURES: readonly HelperFailure[] = [
67
+ "devtools",
68
+ "not-found",
69
+ "ambiguous",
70
+ "not-editable",
71
+ "not-password-field",
72
+ "not-text",
73
+ "opaque-origin",
74
+ "origin-changed",
75
+ "focus-lost",
76
+ "rejected",
77
+ "protocol",
78
+ "failed",
79
+ ]
80
+ const ENDS: readonly PasskeyEnd[] = ["used", "expired", "navigated", "closed", "released"]
81
+ const ORIGIN = /^https?:\/\/[^/\s]{1,260}$/
82
+ const ELEMENT = /^(?:input:[a-z]{1,16}|textarea|contenteditable)$/
83
+
84
+ export class HelperProtocolError extends Error {
85
+ constructor(what: string) {
86
+ super(`the browser's login helper answered ${what}`)
87
+ this.name = "HelperProtocolError"
88
+ }
89
+ }
90
+
91
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
92
+ typeof value === "object" && value !== null && !Array.isArray(value)
93
+
94
+ const oneKey = (value: Record<string, unknown>) => {
95
+ const keys = Object.keys(value)
96
+ if (keys.length !== 1) throw new HelperProtocolError("a line that is not one answer")
97
+ return keys[0] as string
98
+ }
99
+
100
+ /** One line of a helper, checked (the VM is the bot's: untrusted). */
101
+ export function parseReply(value: unknown): HelperReply {
102
+ if (!isRecord(value)) throw new HelperProtocolError("a line that is not an object")
103
+ const key = oneKey(value)
104
+ const body = value[key]
105
+ switch (key) {
106
+ case "located": {
107
+ if (!isRecord(body) || typeof body.origin !== "string" || !ORIGIN.test(body.origin)) {
108
+ throw new HelperProtocolError("a location without a web origin")
109
+ }
110
+ if (
111
+ body.element !== undefined &&
112
+ (typeof body.element !== "string" || !ELEMENT.test(body.element))
113
+ ) {
114
+ throw new HelperProtocolError("an unknown kind of element")
115
+ }
116
+ return {
117
+ kind: "located",
118
+ origin: body.origin,
119
+ ...(body.element === undefined ? {} : { element: body.element }),
120
+ }
121
+ }
122
+ case "filled":
123
+ if (!isRecord(body) || typeof body.submitted !== "boolean") {
124
+ throw new HelperProtocolError("a malformed fill")
125
+ }
126
+ return { kind: "filled", submitted: body.submitted }
127
+ case "ready":
128
+ return { kind: "ready" }
129
+ case "ended":
130
+ if (!(ENDS as readonly unknown[]).includes(body))
131
+ throw new HelperProtocolError("an unknown end")
132
+ return { kind: "ended", reason: body as PasskeyEnd }
133
+ case "cancelled":
134
+ return { kind: "cancelled" }
135
+ case "error":
136
+ return {
137
+ kind: "error",
138
+ code: (FAILURES as readonly unknown[]).includes(body) ? (body as HelperFailure) : "failed",
139
+ }
140
+ default:
141
+ throw new HelperProtocolError("an unknown line")
142
+ }
143
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * The browser's login tools (docs/specs/bot-vaults.md §8): fill one field of
3
+ * a login of the bot into the element of a ref, and offer a login's passkey
4
+ * to the current tab. Playwright MCP only marks the target; the helper in
5
+ * the VM finds it over DevTools, checks the frame's origin as the browser
6
+ * reports it, and gets the value on its standard input. No value, page
7
+ * text or snapshot is returned.
8
+ */
9
+ import type {
10
+ BotConnectorRun,
11
+ BotConnectorTool,
12
+ BotConnectorToolDefinition,
13
+ BotCredential,
14
+ BotVaultAccess,
15
+ ConnectorPreview,
16
+ SecretBytes,
17
+ VaultKit,
18
+ } from "@1outres/dsh-bot-core"
19
+ import type { BrowserConnections } from "../connections"
20
+ import type { BrowserAttachment } from "../session"
21
+ import { explain, withReconnection } from "../tools"
22
+ import { CDP_HOST_PORT, FILL_HELPER } from "../vm/layout"
23
+ import { HelperFailureError } from "./failures"
24
+ import { type HelperRun, startHelper } from "./helper"
25
+ import { markElement, markTab } from "./marks"
26
+ import { PASSKEY_SECONDS } from "./passkeys"
27
+ import { type FillOrder, type FillRequest, HelperProtocolError, type HelperReply } from "./protocol"
28
+
29
+ export const FILL_FIELDS = ["username", "password", "otp"] as const
30
+ type FillField = (typeof FILL_FIELDS)[number]
31
+
32
+ /** Finding the field, fetching the value and typing it. */
33
+ const FILL_TIMEOUT_MS = 60_000
34
+ const EXCLUSIVE_PAGE = "page"
35
+
36
+ export interface VaultToolDeps {
37
+ readonly connections: BrowserConnections
38
+ readonly kit: VaultKit
39
+ /** A new one-time mark (32 lower-case hex digits). */
40
+ mark(): string
41
+ deadline(ms: number): AbortSignal
42
+ }
43
+
44
+ type Run = BotConnectorRun<BrowserAttachment>
45
+ type Parameters = NonNullable<BotConnectorTool["parameters"]>
46
+
47
+ /** A tool typed from its parameters (bot-core's connectorTools, which is a value this package cannot import). */
48
+ const tool = <const S extends Parameters>(
49
+ definition: BotConnectorTool<S, BrowserAttachment>,
50
+ ): BotConnectorToolDefinition<BrowserAttachment> =>
51
+ definition as BotConnectorToolDefinition<BrowserAttachment>
52
+
53
+ function vaultOf(run: Run): BotVaultAccess {
54
+ if (run.vault === undefined) throw new Error("this run has no access to the bot's logins")
55
+ return run.vault
56
+ }
57
+
58
+ const preview = (title: string, fields: ConnectorPreview["fields"]): ConnectorPreview => ({
59
+ title,
60
+ fields,
61
+ })
62
+
63
+ async function mark(run: Run, args: { readonly function: string; readonly target?: string }) {
64
+ let result: Awaited<ReturnType<BrowserAttachment["mcp"]["callTool"]>>
65
+ try {
66
+ result = await run.attachment.mcp.callTool(
67
+ "browser_evaluate",
68
+ args.target === undefined
69
+ ? { function: args.function }
70
+ : { element: "the field to fill", target: args.target, function: args.function },
71
+ { signal: run.signal, timeoutMs: 30_000 },
72
+ )
73
+ } catch (error) {
74
+ throw explain(error)
75
+ }
76
+ if (result.isError) {
77
+ const text = result.content.flatMap((block) => (block.type === "text" ? [block.text] : []))
78
+ throw new Error(
79
+ `Playwright MCP: ${text.join("\n").slice(0, 2_000) || "the target was not found"}`,
80
+ )
81
+ }
82
+ }
83
+
84
+ async function expect<K extends HelperReply["kind"]>(
85
+ helper: HelperRun,
86
+ kind: K,
87
+ ): Promise<Extract<HelperReply, { kind: K }>> {
88
+ const reply = await helper.next()
89
+ if (reply.kind === "error") throw new HelperFailureError(reply.code)
90
+ if (reply.kind !== kind) throw new HelperProtocolError("out of order")
91
+ return reply as Extract<HelperReply, { kind: K }>
92
+ }
93
+
94
+ function requireKind(credential: BotCredential, kind: BotCredential["kinds"][number]) {
95
+ if (credential.kinds.includes(kind)) return
96
+ throw new Error(
97
+ kind === "passkey"
98
+ ? `"${credential.label}" has no passkey this bot may use (its password manager may not hand out passkeys); sign in with browser_fill_credential instead`
99
+ : `"${credential.label}" has no ${kind} this bot may use`,
100
+ )
101
+ }
102
+
103
+ async function fill(
104
+ deps: VaultToolDeps,
105
+ run: Run,
106
+ args: { credential: string; field: FillField; ref: string; submit?: boolean | undefined },
107
+ ): Promise<string> {
108
+ const vault = vaultOf(run)
109
+ const credential = await vault.describe(args.credential)
110
+ requireKind(credential, args.field)
111
+ const markValue = deps.mark()
112
+ await mark(run, { target: args.ref, function: markElement(markValue) })
113
+ const signal = AbortSignal.any([run.signal, deps.deadline(FILL_TIMEOUT_MS)])
114
+ const helper = await startHelper(run.environment, FILL_HELPER, signal, deps.kit)
115
+ let secret: SecretBytes | undefined
116
+ try {
117
+ const request: FillRequest = { devtools: CDP_HOST_PORT, mark: markValue, field: args.field }
118
+ await helper.send(request)
119
+ const { origin } = await expect(helper, "located")
120
+ try {
121
+ secret = await vault.reveal(args.credential, args.field, { kind: "browser", origin })
122
+ } catch (error) {
123
+ await helper.end()
124
+ await expect(helper, "cancelled")
125
+ const reason = error instanceof Error ? error.message : "refused"
126
+ throw new Error(
127
+ `the ${args.field} of "${credential.label}" may not be filled in ${origin}: ${reason}`,
128
+ )
129
+ }
130
+ const submit = args.submit === true
131
+ await helper.sendSecret((length): FillOrder => ({ fill: { origin, submit, length } }), secret)
132
+ const filled = await expect(helper, "filled")
133
+ return `Filled the ${args.field} of "${credential.label}" in ${origin}${filled.submitted ? " and pressed Enter" : ""}. The value is not shown to you; take a browser_snapshot to see the page.`
134
+ } finally {
135
+ secret?.wipe()
136
+ helper.terminate()
137
+ }
138
+ }
139
+
140
+ export function vaultTools(
141
+ deps: VaultToolDeps,
142
+ ): readonly BotConnectorToolDefinition<BrowserAttachment>[] {
143
+ return [
144
+ tool({
145
+ name: "fill_credential",
146
+ description:
147
+ "Type one field (username, password or otp, a current one-time code) of one of your logins into a field of the page, by its ref from browser_snapshot, without you seeing the value. The field's frame must be one of the login's sites; a password goes only into a password field. Set submit to press Enter afterwards. List your logins with credentials_list first.",
148
+ parameters: {
149
+ credential: { type: "string", required: true, description: "The login's handle (cred-…)." },
150
+ field: {
151
+ type: "string",
152
+ enum: FILL_FIELDS,
153
+ required: true,
154
+ description: "Which field of the login.",
155
+ },
156
+ ref: {
157
+ type: "string",
158
+ required: true,
159
+ description: "The ref of the page's field from browser_snapshot.",
160
+ },
161
+ submit: { type: "boolean", description: "Press Enter in the field afterwards." },
162
+ },
163
+ permission: "allow",
164
+ exclusive: EXCLUSIVE_PAGE,
165
+ vault: true,
166
+ preview: (args) =>
167
+ preview("Fill a login of the bot in its browser?", [
168
+ { label: "login", value: args.credential },
169
+ { label: "field", value: args.field },
170
+ { label: "element", value: args.ref },
171
+ ...(args.submit === true ? [{ label: "then", value: "press Enter" }] : []),
172
+ ]),
173
+ async execute(args, run) {
174
+ const text = await fill(deps, run, args)
175
+ return withReconnection({ text }, deps.connections, run.bot.id)
176
+ },
177
+ }),
178
+ tool({
179
+ name: "use_passkey",
180
+ description: `Offer the passkey of one of your logins to the current tab for ${PASSKEY_SECONDS} seconds, without you seeing it: right after this, press the site's sign-in with a passkey. It is used once at most and only while the tab stays on the same site. List your logins with credentials_list first.`,
181
+ parameters: {
182
+ credential: { type: "string", required: true, description: "The login's handle (cred-…)." },
183
+ },
184
+ permission: "allow",
185
+ exclusive: EXCLUSIVE_PAGE,
186
+ vault: true,
187
+ preview: (args) =>
188
+ preview("Offer a passkey of the bot in its browser?", [
189
+ { label: "login", value: args.credential },
190
+ ]),
191
+ async execute(args, run) {
192
+ const text = await offerPasskey(deps, run, args)
193
+ return withReconnection({ text }, deps.connections, run.bot.id)
194
+ },
195
+ }),
196
+ ]
197
+ }
198
+
199
+ async function offerPasskey(deps: VaultToolDeps, run: Run, args: { credential: string }) {
200
+ const vault = vaultOf(run)
201
+ const credential = await vault.describe(args.credential)
202
+ requireKind(credential, "passkey")
203
+ const markValue = deps.mark()
204
+ await mark(run, { function: markTab(markValue) })
205
+ const tab = await run.attachment.passkeys.locate(markValue)
206
+ let passkey: Awaited<ReturnType<BotVaultAccess["passkey"]>>
207
+ try {
208
+ passkey = await vault.passkey(args.credential, { kind: "browser", origin: tab.origin })
209
+ } catch (error) {
210
+ tab.cancel()
211
+ const reason = error instanceof Error ? error.message : "refused"
212
+ throw new Error(
213
+ `the passkey of "${credential.label}" may not be used in ${tab.origin}: ${reason}`,
214
+ )
215
+ }
216
+ await tab.offer(passkey)
217
+ return `The passkey of "${credential.label}" is offered to ${tab.origin} for ${PASSKEY_SECONDS} seconds. Now press the site's sign-in with a passkey (browser_click), then take a browser_snapshot. It goes away once used, when the tab leaves the site, or at your next browser_use_passkey.`
218
+ }
@@ -5,8 +5,13 @@
5
5
  export const MCP_DIR = "/opt/dsh-browser/mcp"
6
6
  export const MCP_SHRINKWRAP = `${MCP_DIR}/npm-shrinkwrap.json`
7
7
  export const MCP_CLI = `${MCP_DIR}/node_modules/@playwright/mcp/cli.js`
8
+ /** The helpers that fill logins and offer passkeys over DevTools (vm/helper/), owned by root. */
9
+ export const HELPER_DIR = "/opt/dsh-browser/helper"
10
+ export const FILL_HELPER = `${HELPER_DIR}/dsh-browser-fill.mjs`
11
+ export const PASSKEY_HELPER = `${HELPER_DIR}/dsh-browser-passkey.mjs`
8
12
  /** The desktop connector's Chrome answers DevTools here, on loopback only (its vm/bin/chrome-run). */
9
- export const CDP_ENDPOINT = "http://127.0.0.1:9222"
13
+ export const CDP_HOST_PORT = "127.0.0.1:9222"
14
+ export const CDP_ENDPOINT = `http://${CDP_HOST_PORT}`
10
15
  /** Most bytes of screenshots and snapshots the server keeps on disk before it drops the oldest. */
11
16
  export const OUTPUT_MAX_BYTES = 256 << 20
12
17
 
@@ -20,3 +25,4 @@ export interface VmUser {
20
25
  /** Where the server writes the files its results link to (screenshots, snapshots, PDFs), readable by the bot. */
21
26
  export const outputDir = (user: VmUser) => `${user.home}/.cache/dsh-browser/output`
22
27
  export const stagingDir = (user: VmUser) => `${user.home}/.cache/dsh-browser/staging`
28
+ export const helperStagingDir = (user: VmUser) => `${user.home}/.cache/dsh-browser/helper-staging`
package/src/index.ts CHANGED
@@ -4,12 +4,13 @@
4
4
  * composition root: it reads the package's vm/ files and gives the Host
5
5
  * modules the clock.
6
6
  */
7
- import { readFile } from "node:fs/promises"
7
+ import { randomBytes } from "node:crypto"
8
+ import { readdir, readFile } from "node:fs/promises"
8
9
  import type { Bot } from "@1outres/dsh-bot-core"
9
10
  import type { Context } from "@deepseek-ai/cordis"
10
11
  import { GENERATED_SERVER } from "./host/catalog"
11
12
  import { createBrowserConnector } from "./host/connector"
12
- import type { McpInstallation } from "./host/preparation"
13
+ import type { BrowserInstallation } from "./host/preparation"
13
14
 
14
15
  export { GENERATED_SERVER } from "./host/catalog"
15
16
  export { createBrowserConnector } from "./host/connector"
@@ -31,13 +32,24 @@ function botOf(ctx: Context): Bot {
31
32
 
32
33
  const VM = new URL("../vm/", import.meta.url)
33
34
 
34
- /** The vm/ files the preparation installs Playwright MCP from. */
35
- export async function readMcpInstallation(directory: URL = VM): Promise<McpInstallation> {
35
+ /** The vm/ files the preparation installs Playwright MCP and the login helpers from. */
36
+ export async function readBrowserInstallation(directory: URL = VM): Promise<BrowserInstallation> {
36
37
  const read = async (path: string) => new Uint8Array(await readFile(new URL(path, directory)))
38
+ const helpers = (await readdir(new URL("helper/", directory)))
39
+ .filter((name) => name.endsWith(".mjs"))
40
+ .sort()
37
41
  return {
38
- packageJson: await read("mcp/package.json"),
39
- shrinkwrap: await read("mcp/npm-shrinkwrap.json"),
40
- script: await read("install-mcp.sh"),
42
+ mcp: {
43
+ packageJson: await read("mcp/package.json"),
44
+ shrinkwrap: await read("mcp/npm-shrinkwrap.json"),
45
+ script: await read("install-mcp.sh"),
46
+ },
47
+ helper: {
48
+ files: await Promise.all(
49
+ helpers.map(async (name) => ({ name, data: await read(`helper/${name}`) })),
50
+ ),
51
+ script: await read("install-helper.sh"),
52
+ },
41
53
  }
42
54
  }
43
55
 
@@ -45,7 +57,9 @@ export async function apply(ctx: Context): Promise<void> {
45
57
  const bot = botOf(ctx)
46
58
  const connector = createBrowserConnector({
47
59
  generated: GENERATED_SERVER,
48
- installation: await readMcpInstallation(),
60
+ installation: await readBrowserInstallation(),
61
+ kit: bot.vaultKit(),
62
+ mark: () => randomBytes(16).toString("hex"),
49
63
  deadline: (ms) => AbortSignal.timeout(ms),
50
64
  })
51
65
  ctx.effect(() => bot.registerConnector(connector), "browser: connector")
@@ -0,0 +1,74 @@
1
+ // Byte-level encodings of a secret for a DevTools message: never a JS string.
2
+
3
+ const BASE64 = new TextEncoder().encode(
4
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
5
+ )
6
+ const HEX = new TextEncoder().encode("0123456789abcdef")
7
+ const SHORT = new Map([
8
+ [8, 0x62],
9
+ [9, 0x74],
10
+ [10, 0x6e],
11
+ [12, 0x66],
12
+ [13, 0x72],
13
+ [34, 0x22],
14
+ [92, 0x5c],
15
+ ])
16
+
17
+ /** Standard base64 with padding. */
18
+ export function base64Bytes(bytes) {
19
+ const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4)
20
+ let at = 0
21
+ for (let i = 0; i < bytes.length; i += 3) {
22
+ const rest = bytes.length - i
23
+ const n =
24
+ (bytes[i] << 16) | ((rest > 1 ? bytes[i + 1] : 0) << 8) | (rest > 2 ? bytes[i + 2] : 0)
25
+ out[at++] = BASE64[(n >> 18) & 63]
26
+ out[at++] = BASE64[(n >> 12) & 63]
27
+ out[at++] = rest > 1 ? BASE64[(n >> 6) & 63] : 0x3d
28
+ out[at++] = rest > 2 ? BASE64[n & 63] : 0x3d
29
+ }
30
+ return out
31
+ }
32
+
33
+ /** The body of a JSON string (without quotes) holding the UTF-8 bytes. */
34
+ export function jsonStringBytes(bytes) {
35
+ let length = 0
36
+ for (const byte of bytes) length += SHORT.has(byte) ? 2 : byte < 0x20 ? 6 : 1
37
+ const out = new Uint8Array(length)
38
+ let at = 0
39
+ for (const byte of bytes) {
40
+ const short = SHORT.get(byte)
41
+ if (short !== undefined) {
42
+ out[at++] = 0x5c
43
+ out[at++] = short
44
+ } else if (byte < 0x20) {
45
+ out.set([0x5c, 0x75, 0x30, 0x30, HEX[byte >> 4], HEX[byte & 15]], at)
46
+ at += 6
47
+ } else {
48
+ out[at++] = byte
49
+ }
50
+ }
51
+ return out
52
+ }
53
+
54
+ /** Whether the bytes are well-formed UTF-8 (Input.insertText takes text). */
55
+ export function isUtf8(bytes) {
56
+ let i = 0
57
+ while (i < bytes.length) {
58
+ const byte = bytes[i]
59
+ const size =
60
+ byte < 0x80
61
+ ? 1
62
+ : byte >= 0xc2 && byte < 0xe0
63
+ ? 2
64
+ : byte >= 0xe0 && byte < 0xf0
65
+ ? 3
66
+ : byte >= 0xf0 && byte < 0xf5
67
+ ? 4
68
+ : 0
69
+ if (size === 0 || i + size > bytes.length) return false
70
+ for (let k = 1; k < size; k++) if ((bytes[i + k] & 0xc0) !== 0x80) return false
71
+ i += size
72
+ }
73
+ return true
74
+ }