@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1outres/dsh-bot-connector-browser",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Gives each bot of DeepSeek Harness the Google Chrome on its VM's desktop as a browser it drives with Playwright MCP inside the VM (page snapshots, forms, screenshots), as a bot-core connector; a person sees the same Chrome in the Desktop panel.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,11 +42,11 @@
42
42
  "node": ">=22"
43
43
  },
44
44
  "peerDependencies": {
45
- "@1outres/dsh-bot-core": "^0.3.0",
45
+ "@1outres/dsh-bot-core": "^0.4.0",
46
46
  "@deepseek-ai/cordis": "~4.1.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@1outres/dsh-bot-core": "0.3.0",
49
+ "@1outres/dsh-bot-core": "0.4.0",
50
50
  "@deepseek-ai/cordis": "~4.1.0",
51
51
  "@playwright/mcp": "0.0.86"
52
52
  },
@@ -4,25 +4,30 @@
4
4
  * MCP there over DevTools, for every session of the bot. It requires the
5
5
  * desktop: the browser is the one on the screen a person watches.
6
6
  */
7
- import type { BotConnector } from "@1outres/dsh-bot-core"
7
+ import type { BotConnector, VaultKit } from "@1outres/dsh-bot-core"
8
8
  import { BROWSER_CONNECTOR_ID, DESKTOP_CONNECTOR_ID } from "../shared/connector"
9
9
  import { type GeneratedServer, offeredTools } from "./catalog"
10
10
  import { BrowserConnections } from "./connections"
11
11
  import type { McpClientDeps } from "./mcp/client"
12
- import type { McpServer } from "./mcp/server"
13
- import { createBrowserPreparation, type McpInstallation } from "./preparation"
14
- import { browserAttachment } from "./session"
12
+ import { type BrowserInstallation, createBrowserPreparation } from "./preparation"
13
+ import { type BrowserAttachment, browserAttachment } from "./session"
15
14
  import { browserTools } from "./tools"
15
+ import { vaultTools } from "./vault/tools"
16
16
 
17
17
  /** The least memory for Chrome's pages beside Playwright MCP's Node process. */
18
18
  export const BROWSER_MIN_MEMORY_MIB = 3072
19
19
 
20
20
  export interface BrowserConnectorDeps extends McpClientDeps {
21
21
  readonly generated: GeneratedServer
22
- readonly installation: McpInstallation
22
+ readonly installation: BrowserInstallation
23
+ readonly kit: VaultKit
24
+ /** A new one-time mark for a login's target (32 lower-case hex digits). */
25
+ mark(): string
23
26
  }
24
27
 
25
- export function createBrowserConnector(deps: BrowserConnectorDeps): BotConnector<McpServer> {
28
+ export function createBrowserConnector(
29
+ deps: BrowserConnectorDeps,
30
+ ): BotConnector<BrowserAttachment> {
26
31
  const connections = new BrowserConnections()
27
32
  return {
28
33
  id: BROWSER_CONNECTOR_ID,
@@ -43,6 +48,9 @@ export function createBrowserConnector(deps: BrowserConnectorDeps): BotConnector
43
48
  },
44
49
  },
45
50
  attachment: browserAttachment({ ...deps, connections }),
46
- tools: browserTools(offeredTools(deps.generated.tools), connections),
51
+ tools: [
52
+ ...browserTools(offeredTools(deps.generated.tools), connections),
53
+ ...vaultTools({ ...deps, connections }),
54
+ ],
47
55
  }
48
56
  }
@@ -2,15 +2,23 @@
2
2
  * Making the bot's environment ready for the browser, one idempotent path
3
3
  * (the desktop, which runs the Chrome it drives, is ready before: the
4
4
  * connector requires it): Playwright MCP installed from the pinned
5
- * npm-shrinkwrap.json when the installed one differs, the desktop's Chrome answering DevTools,
6
- * and the server listing exactly the generated tools.
5
+ * npm-shrinkwrap.json when the installed one differs, the login helpers when they differ, the
6
+ * desktop's Chrome answering DevTools, and the server listing exactly the generated tools.
7
7
  */
8
8
  import type { BotConnectorContext, BotConnectorPreparation } from "@1outres/dsh-bot-core"
9
9
  import { type GeneratedServer, toolDifferences } from "./catalog"
10
10
  import type { McpClientDeps } from "./mcp/client"
11
11
  import { startServer } from "./mcp/server"
12
12
  import { readVmUser, run } from "./vm/commands"
13
- import { CDP_ENDPOINT, MCP_DIR, MCP_SHRINKWRAP, stagingDir, type VmUser } from "./vm/layout"
13
+ import {
14
+ CDP_ENDPOINT,
15
+ HELPER_DIR,
16
+ helperStagingDir,
17
+ MCP_DIR,
18
+ MCP_SHRINKWRAP,
19
+ stagingDir,
20
+ type VmUser,
21
+ } from "./vm/layout"
14
22
 
15
23
  /** The package's vm/ files the preparation installs from. */
16
24
  export interface McpInstallation {
@@ -20,11 +28,24 @@ export interface McpInstallation {
20
28
  readonly script: Uint8Array
21
29
  }
22
30
 
31
+ /** The login helpers (vm/helper/*.mjs) and vm/install-helper.sh. */
32
+ export interface HelperInstallation {
33
+ readonly files: readonly { readonly name: string; readonly data: Uint8Array }[]
34
+ readonly script: Uint8Array
35
+ }
36
+
37
+ export interface BrowserInstallation {
38
+ readonly mcp: McpInstallation
39
+ readonly helper: HelperInstallation
40
+ }
41
+
23
42
  export interface BrowserPreparationDeps extends McpClientDeps {
24
43
  readonly generated: GeneratedServer
25
- readonly installation: McpInstallation
44
+ readonly installation: BrowserInstallation
26
45
  }
27
46
 
47
+ const HELPER_FILE = /^[a-z][a-z0-9-]*\.mjs$/
48
+
28
49
  const INSTALL_TIMEOUT_MS = 15 * 60_000
29
50
 
30
51
  /** What the desktop's Chrome says on DevTools' /json/version. @throws for anything but Chrome. */
@@ -51,9 +72,9 @@ export function createBrowserPreparation(deps: BrowserPreparationDeps): BotConne
51
72
  await run(environment, ["rm", "-rf", "--", stage], { signal })
52
73
  await run(environment, ["mkdir", "-p", "-m", "0700", "--", stage], { signal })
53
74
  const files: readonly [string, Uint8Array][] = [
54
- ["package.json", deps.installation.packageJson],
55
- ["npm-shrinkwrap.json", deps.installation.shrinkwrap],
56
- ["install-mcp.sh", deps.installation.script],
75
+ ["package.json", deps.installation.mcp.packageJson],
76
+ ["npm-shrinkwrap.json", deps.installation.mcp.shrinkwrap],
77
+ ["install-mcp.sh", deps.installation.mcp.script],
57
78
  ]
58
79
  for (const [name, data] of files) {
59
80
  await environment.writeFile(`${stage}/${name}`, data, { mode: 0o644, signal })
@@ -71,7 +92,41 @@ export function createBrowserPreparation(deps: BrowserPreparationDeps): BotConne
71
92
  accept: [0, 1],
72
93
  maxOutputBytes: 4 << 20,
73
94
  })
74
- return current.exitCode === 0 && current.stdout === decoder.decode(deps.installation.shrinkwrap)
95
+ return (
96
+ current.exitCode === 0 && current.stdout === decoder.decode(deps.installation.mcp.shrinkwrap)
97
+ )
98
+ }
99
+
100
+ const helperInstalled = async (context: BotConnectorContext) => {
101
+ for (const file of deps.installation.helper.files) {
102
+ const current = await run(context.environment, ["cat", "--", `${HELPER_DIR}/${file.name}`], {
103
+ signal: context.signal,
104
+ accept: [0, 1],
105
+ maxOutputBytes: 1 << 20,
106
+ })
107
+ if (current.exitCode !== 0 || current.stdout !== decoder.decode(file.data)) return false
108
+ }
109
+ return true
110
+ }
111
+
112
+ const installHelper = async (context: BotConnectorContext, user: VmUser) => {
113
+ const stage = helperStagingDir(user)
114
+ const { signal, environment } = context
115
+ await run(environment, ["rm", "-rf", "--", stage], { signal })
116
+ await run(environment, ["mkdir", "-p", "-m", "0700", "--", stage], { signal })
117
+ for (const file of deps.installation.helper.files) {
118
+ if (!HELPER_FILE.test(file.name))
119
+ throw new Error(`vm/helper/${file.name} is not a helper module`)
120
+ await environment.writeFile(`${stage}/${file.name}`, file.data, { mode: 0o644, signal })
121
+ }
122
+ await environment.writeFile(`${stage}/install-helper.sh`, deps.installation.helper.script, {
123
+ mode: 0o644,
124
+ signal,
125
+ })
126
+ await run(environment, ["sudo", "-n", "sh", `${stage}/install-helper.sh`, stage, HELPER_DIR], {
127
+ signal,
128
+ })
129
+ await run(environment, ["rm", "-rf", "--", stage], { signal })
75
130
  }
76
131
 
77
132
  const checkTools = async (context: BotConnectorContext, user: VmUser) => {
@@ -106,6 +161,11 @@ export function createBrowserPreparation(deps: BrowserPreparationDeps): BotConne
106
161
  progress(`installing Playwright MCP ${deps.generated.version}`)
107
162
  await install(context, user)
108
163
  }
164
+ progress("checking the login helpers")
165
+ if (!(await helperInstalled(context))) {
166
+ progress("installing the login helpers")
167
+ await installHelper(context, user)
168
+ }
109
169
  progress("checking the desktop's Chrome")
110
170
  const answer = await run(
111
171
  context.environment,
@@ -1,23 +1,31 @@
1
1
  /**
2
2
  * The browser connector's resident resource per bot: Playwright MCP started
3
- * in the bot's environment, attached to the desktop's Chrome. Chrome itself
4
- * is the desktop's user service, so its tabs and cookies outlive the server.
3
+ * in the bot's environment, attached to the desktop's Chrome, and the
4
+ * passkey offered there, if any. Chrome itself is the desktop's user
5
+ * service, so its tabs and cookies outlive the server.
5
6
  */
6
- import type { BotConnectorAttachmentSource } from "@1outres/dsh-bot-core"
7
+ import type { BotConnectorAttachmentSource, VaultKit } from "@1outres/dsh-bot-core"
7
8
  import type { GeneratedServer } from "./catalog"
8
9
  import type { BrowserConnections } from "./connections"
9
10
  import type { McpClientDeps } from "./mcp/client"
10
11
  import { type McpServer, startServer } from "./mcp/server"
12
+ import { type PasskeySlot, passkeySlot } from "./vault/passkeys"
11
13
  import { readVmUser } from "./vm/commands"
12
14
 
15
+ export interface BrowserAttachment {
16
+ readonly mcp: McpServer
17
+ readonly passkeys: PasskeySlot
18
+ }
19
+
13
20
  export interface BrowserSessionDeps extends McpClientDeps {
14
21
  readonly generated: GeneratedServer
15
22
  readonly connections: BrowserConnections
23
+ readonly kit: VaultKit
16
24
  }
17
25
 
18
26
  export function browserAttachment(
19
27
  deps: BrowserSessionDeps,
20
- ): BotConnectorAttachmentSource<McpServer> {
28
+ ): BotConnectorAttachmentSource<BrowserAttachment> {
21
29
  return {
22
30
  async open(context) {
23
31
  const user = await readVmUser(context.environment, context.signal)
@@ -29,10 +37,17 @@ export function browserAttachment(
29
37
  deps,
30
38
  )
31
39
  deps.connections.connected(context.bot.id)
40
+ const passkeys = passkeySlot({
41
+ environment: context.environment,
42
+ signal: context.signal,
43
+ kit: deps.kit,
44
+ deadline: deps.deadline,
45
+ })
32
46
  return {
33
- value: server,
47
+ value: { mcp: server, passkeys },
34
48
  ended: server.ended,
35
49
  async dispose() {
50
+ passkeys.release()
36
51
  server.close()
37
52
  },
38
53
  }
package/src/host/tools.ts CHANGED
@@ -15,9 +15,9 @@ import type { OfferedTool } from "./catalog"
15
15
  import type { BrowserConnections } from "./connections"
16
16
  import { McpCallError, McpUnavailableError } from "./mcp/client"
17
17
  import { McpProtocolError } from "./mcp/protocol"
18
- import type { McpServer } from "./mcp/server"
19
18
  import { resultOf } from "./result"
20
19
  import { toolSchema } from "./schema"
20
+ import type { BrowserAttachment } from "./session"
21
21
 
22
22
  /** Snapshots of large pages run long; bot-core cuts what is beyond. */
23
23
  export const MAX_RESULT_CHARS = 128_000
@@ -50,12 +50,25 @@ export function explain(error: unknown): Error {
50
50
  return error instanceof Error ? error : new Error(String(error))
51
51
  }
52
52
 
53
+ /** The result, after a note when it is the first since the connection was opened again. */
54
+ export function withReconnection(
55
+ result: BotConnectorResult,
56
+ connections: BrowserConnections,
57
+ botId: string,
58
+ ): BotConnectorResult {
59
+ if (!connections.takeReconnected(botId)) return result
60
+ return {
61
+ ...result,
62
+ text: [RECONNECTED, ...(result.text === undefined ? [] : [result.text])].join("\n\n"),
63
+ }
64
+ }
65
+
53
66
  export function browserTools(
54
67
  offered: readonly OfferedTool[],
55
68
  connections: BrowserConnections,
56
- ): readonly BotConnectorToolDefinition<McpServer>[] {
57
- return offered.map((entry): BotConnectorToolDefinition<McpServer> => {
58
- const tool: BotConnectorSchemaTool<McpServer> = {
69
+ ): readonly BotConnectorToolDefinition<BrowserAttachment>[] {
70
+ return offered.map((entry): BotConnectorToolDefinition<BrowserAttachment> => {
71
+ const tool: BotConnectorSchemaTool<BrowserAttachment> = {
59
72
  name: entry.name,
60
73
  description: entry.upstream.description,
61
74
  inputSchema: toolSchema(entry.upstream.inputSchema, entry.upstream.name),
@@ -68,7 +81,7 @@ export function browserTools(
68
81
  let result: BotConnectorResult
69
82
  try {
70
83
  result = await resultOf(
71
- await run.attachment.callTool(entry.upstream.name, args, {
84
+ await run.attachment.mcp.callTool(entry.upstream.name, args, {
72
85
  signal: run.signal,
73
86
  timeoutMs: CALL_TIMEOUT_MS,
74
87
  }),
@@ -77,11 +90,7 @@ export function browserTools(
77
90
  } catch (error) {
78
91
  throw explain(error)
79
92
  }
80
- if (!connections.takeReconnected(run.bot.id)) return result
81
- return {
82
- ...result,
83
- text: [RECONNECTED, ...(result.text === undefined ? [] : [result.text])].join("\n\n"),
84
- }
93
+ return withReconnection(result, connections, run.bot.id)
85
94
  },
86
95
  }
87
96
  return tool
@@ -0,0 +1,31 @@
1
+ /** What the model reads when a login helper stopped (it never says more than its code). */
2
+ import type { HelperFailure } from "./protocol"
3
+
4
+ const TEXTS: Readonly<Record<HelperFailure, string>> = {
5
+ devtools:
6
+ "the browser's DevTools could not be reached; check that the browser is ready and try again",
7
+ "not-found":
8
+ "the marked element is gone (the page changed); take a new browser_snapshot and use its ref",
9
+ ambiguous: "the element could not be told apart from another; take a new browser_snapshot",
10
+ "not-editable":
11
+ "the element is not a text field (an enabled input, textarea or editable element); pick the field's ref",
12
+ "not-password-field":
13
+ "a password goes only into a password field (type=password, or autocomplete current-password / new-password)",
14
+ "not-text": "the value is not text that can be typed",
15
+ "opaque-origin":
16
+ "the field is in a frame without a web origin (sandboxed, or not http/https); nothing was filled",
17
+ "origin-changed":
18
+ "the page went to another site before the value was entered; nothing was filled",
19
+ "focus-lost":
20
+ "the field lost the focus; take a new browser_snapshot to see what the field holds before trying again",
21
+ rejected: "the browser did not take the passkey",
22
+ protocol: "the browser's login helper failed",
23
+ failed: "the browser's login helper failed",
24
+ }
25
+
26
+ export class HelperFailureError extends Error {
27
+ constructor(readonly code: HelperFailure) {
28
+ super(TEXTS[code])
29
+ this.name = "HelperFailureError"
30
+ }
31
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * One run of a login helper in the bot's VM, spoken to over its standard
3
+ * input and output (vault/protocol.ts). A secret reaches it only as raw
4
+ * bytes on its standard input, written from one array that is wiped right
5
+ * after: never in its argv or environment, never as a JS string.
6
+ */
7
+ import type {
8
+ BotConnectorEnvironment,
9
+ BotEnvironmentProcess,
10
+ SecretBytes,
11
+ VaultKit,
12
+ } from "@1outres/dsh-bot-core"
13
+ import { HelperProtocolError, type HelperReply, parseReply } from "./protocol"
14
+
15
+ const MAX_LINE_BYTES = 4096
16
+ const NEWLINE = 0x0a
17
+
18
+ export class HelperEndedError extends Error {
19
+ constructor() {
20
+ super("the browser's login helper ended without an answer")
21
+ this.name = "HelperEndedError"
22
+ }
23
+ }
24
+
25
+ export interface HelperRun {
26
+ /** The next answer. @throws when the helper ended or answered something malformed. */
27
+ next(): Promise<HelperReply>
28
+ send(message: object): Promise<void>
29
+ /** A line made by `header(secret.length)`, then the secret's bytes; the secret is spent. */
30
+ sendSecret(header: (length: number) => object, secret: SecretBytes): Promise<void>
31
+ /** Close its input: a helper waiting for an order stops (nothing was filled). */
32
+ end(): Promise<void>
33
+ terminate(): void
34
+ readonly done: Promise<unknown>
35
+ }
36
+
37
+ async function* lines(stdout: AsyncIterable<Uint8Array>): AsyncGenerator<Uint8Array> {
38
+ let buffer = new Uint8Array(0)
39
+ for await (const chunk of stdout) {
40
+ const joined = new Uint8Array(buffer.byteLength + chunk.byteLength)
41
+ joined.set(buffer)
42
+ joined.set(chunk, buffer.byteLength)
43
+ buffer = joined
44
+ let index = buffer.indexOf(NEWLINE)
45
+ while (index >= 0) {
46
+ yield buffer.slice(0, index)
47
+ buffer = buffer.slice(index + 1)
48
+ index = buffer.indexOf(NEWLINE)
49
+ }
50
+ if (buffer.byteLength > MAX_LINE_BYTES) {
51
+ throw new HelperProtocolError(`a line longer than ${MAX_LINE_BYTES} bytes`)
52
+ }
53
+ }
54
+ }
55
+
56
+ export function helperRun(process: BotEnvironmentProcess, kit: VaultKit): HelperRun {
57
+ const encoder = new TextEncoder()
58
+ const decoder = new TextDecoder()
59
+ const reader = lines(process.stdout)
60
+ return {
61
+ done: process.done,
62
+ async next() {
63
+ const line = await reader.next()
64
+ if (line.done === true) throw new HelperEndedError()
65
+ let value: unknown
66
+ try {
67
+ value = JSON.parse(decoder.decode(line.value))
68
+ } catch {
69
+ throw new HelperProtocolError("a line that is not JSON")
70
+ }
71
+ return parseReply(value)
72
+ },
73
+ send: (message) => process.stdin.write(encoder.encode(`${JSON.stringify(message)}\n`)),
74
+ async sendSecret(header, secret) {
75
+ const line = encoder.encode(`${JSON.stringify(header(secret.length))}\n`)
76
+ await secret.use(async (bytes) => {
77
+ const frame = kit.concat([line, bytes])
78
+ try {
79
+ await process.stdin.write(frame)
80
+ } finally {
81
+ kit.wipe(frame)
82
+ }
83
+ })
84
+ },
85
+ end: () => process.stdin.end(),
86
+ terminate: () => process.terminate(),
87
+ }
88
+ }
89
+
90
+ export async function startHelper(
91
+ environment: BotConnectorEnvironment,
92
+ script: string,
93
+ signal: AbortSignal,
94
+ kit: VaultKit,
95
+ ): Promise<HelperRun> {
96
+ return helperRun(await environment.spawn({ argv: ["node", script], signal }), kit)
97
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The one-time marks Playwright MCP puts on what a login goes to, so that
3
+ * the helper finds it over DevTools by itself (the value never goes
4
+ * through Playwright MCP). A mark is 32 lower-case hex digits.
5
+ */
6
+ export const FILL_ATTRIBUTE = "data-dsh-fill"
7
+ export const PASSKEY_ATTRIBUTE = "data-dsh-passkey"
8
+
9
+ const MARK = /^[0-9a-f]{32}$/
10
+
11
+ export function checkMark(mark: string): string {
12
+ if (!MARK.test(mark)) throw new Error("a mark is 32 lower-case hex digits")
13
+ return mark
14
+ }
15
+
16
+ /** browser_evaluate's function for the element of a ref. */
17
+ export const markElement = (mark: string) =>
18
+ `(element) => { element.setAttribute("${FILL_ATTRIBUTE}", "${checkMark(mark)}"); return "marked" }`
19
+
20
+ /** browser_evaluate's function for the current tab's document. */
21
+ export const markTab = (mark: string) =>
22
+ `() => { document.documentElement.setAttribute("${PASSKEY_ATTRIBUTE}", "${checkMark(mark)}"); return "marked" }`
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The passkey offered in a bot's browser: at most one passkey helper per
3
+ * bot, part of the connector's resident resource (it outlives the tool's
4
+ * call), ended by the next offer, by the helper itself (used once, time up,
5
+ * the tab left the origin) or when the resource is disposed.
6
+ */
7
+ import type {
8
+ BotConnectorEnvironment,
9
+ SecretBytes,
10
+ VaultKit,
11
+ VaultPasskey,
12
+ } from "@1outres/dsh-bot-core"
13
+ import { CDP_HOST_PORT, PASSKEY_HELPER } from "../vm/layout"
14
+ import { HelperFailureError } from "./failures"
15
+ import { type HelperRun, startHelper } from "./helper"
16
+ import { HelperProtocolError, type PasskeyOrder, type PasskeyRequest } from "./protocol"
17
+
18
+ /** How long an offered passkey waits for the site. */
19
+ export const PASSKEY_SECONDS = 60
20
+ const STEP_TIMEOUT_MS = 30_000
21
+
22
+ export interface PasskeySlotDeps {
23
+ readonly environment: BotConnectorEnvironment
24
+ /** The resident resource's lifetime. */
25
+ readonly signal: AbortSignal
26
+ readonly kit: VaultKit
27
+ deadline(ms: number): AbortSignal
28
+ }
29
+
30
+ /** The tab the helper found; the passkey goes to it, or the offer is cancelled. */
31
+ export interface PasskeyTab {
32
+ readonly origin: string
33
+ /** Resolves once the site can use the passkey; the private key is spent either way. */
34
+ offer(passkey: VaultPasskey): Promise<void>
35
+ cancel(): void
36
+ }
37
+
38
+ export interface PasskeySlot {
39
+ /** End the passkey offered so far, then find the tab marked with `mark`. */
40
+ locate(mark: string): Promise<PasskeyTab>
41
+ release(): void
42
+ }
43
+
44
+ const base64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64")
45
+
46
+ export function passkeySlot(deps: PasskeySlotDeps): PasskeySlot {
47
+ let current: HelperRun | undefined
48
+
49
+ const release = () => {
50
+ current?.terminate()
51
+ current = undefined
52
+ }
53
+
54
+ const answer = async (run: HelperRun) => {
55
+ const timeout = deps.deadline(STEP_TIMEOUT_MS)
56
+ const timedOut = new Promise<never>((_, reject) => {
57
+ timeout.addEventListener("abort", () => reject(new HelperFailureError("failed")), {
58
+ once: true,
59
+ })
60
+ })
61
+ const reply = await Promise.race([run.next(), timedOut])
62
+ if (reply.kind === "error") throw new HelperFailureError(reply.code)
63
+ return reply
64
+ }
65
+
66
+ const drain = async (run: HelperRun) => {
67
+ try {
68
+ for (;;) await run.next()
69
+ } catch {
70
+ } finally {
71
+ if (current === run) current = undefined
72
+ }
73
+ }
74
+
75
+ const order = (origin: string, passkey: VaultPasskey, length: number): PasskeyOrder => ({
76
+ passkey: {
77
+ origin,
78
+ rpId: passkey.rpId,
79
+ credentialId: base64(passkey.credentialId),
80
+ ...(passkey.userHandle === undefined ? {} : { userHandle: base64(passkey.userHandle) }),
81
+ signCount: passkey.signCount,
82
+ seconds: PASSKEY_SECONDS,
83
+ length,
84
+ },
85
+ })
86
+
87
+ return {
88
+ release,
89
+ async locate(mark) {
90
+ release()
91
+ const run = await startHelper(deps.environment, PASSKEY_HELPER, deps.signal, deps.kit)
92
+ current = run
93
+ try {
94
+ const request: PasskeyRequest = { devtools: CDP_HOST_PORT, mark }
95
+ await run.send(request)
96
+ const located = await answer(run)
97
+ if (located.kind !== "located") throw new HelperProtocolError("out of order")
98
+ return {
99
+ origin: located.origin,
100
+ async offer(passkey) {
101
+ const key: SecretBytes = passkey.privateKey
102
+ try {
103
+ await run.sendSecret((length) => order(located.origin, passkey, length), key)
104
+ const ready = await answer(run)
105
+ if (ready.kind !== "ready") throw new HelperProtocolError("out of order")
106
+ void drain(run)
107
+ } catch (error) {
108
+ if (current === run) release()
109
+ throw error
110
+ } finally {
111
+ key.wipe()
112
+ }
113
+ },
114
+ cancel() {
115
+ if (current === run) release()
116
+ },
117
+ }
118
+ } catch (error) {
119
+ if (current === run) release()
120
+ throw error
121
+ }
122
+ },
123
+ }
124
+ }