@abide/bridge 0.5.2 → 0.6.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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @abide/bridge
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f35c47f: A link can ask for MCP tools of the visitor's own servers. The bridge finds them in the visitor's Claude Code configuration (user scope) or in the `--mcp-config` they passed, reads them again every turn, and gives a turn only the servers of the tools it was granted (44.15, 44.58). It reports to the site which asked-for tools it cannot give (44.61). The Allow dialog names any tool whose server the visitor lacks (44.65), and offers Always Allow: kept per site and per holder of the code, so a code minted for someone else is still asked about (44.62). `abide-bridge forget [<site>]` makes a site ask again (44.66). `abide-bridge install` now registers on Linux (a desktop entry, asking with `zenity` or `kdialog`) and Windows (registry classes) as well as macOS (44.43, 44.64). Reinstall once to get the new link handler: an older one refuses a link carrying MCP tool names.
8
+
3
9
  ## 0.5.2
4
10
 
5
11
  ### Patch Changes
@@ -5,16 +5,22 @@
5
5
  // follows `--` is passed to Claude Code as you wrote it, and is how you give a site what reaches this
6
6
  // machine — `-- --tools WebSearch,WebFetch` for the built-in tools it asks for.
7
7
  //
8
- // `abide-bridge install` takes the same options and builds and registers, on macOS, the app that opens the
9
- // pairing link a site shows beside its command, so a click pairs instead of a terminal — every link it
10
- // opens runs with the `--env` and the `--` options given here (44.44); `abide-bridge uninstall` takes it
11
- // away.
8
+ // `abide-bridge install` takes the same options and builds and registers, on macOS, Linux or Windows,
9
+ // what opens the pairing link a site shows beside its command, so a click pairs instead of a terminal —
10
+ // every link it opens runs with the `--env` and the `--` options given here (44.44); `abide-bridge
11
+ // uninstall` takes it away. `abide-bridge forget [<site>]` stops always allowing a site, or every site.
12
12
 
13
+ import { allowedIn, forget } from '../src/allowedSites.ts'
13
14
  import { bridge } from '../src/bridge.ts'
14
- import { install, installDirectory, uninstall } from '../src/install.ts'
15
+ import {
16
+ handlerDirectory,
17
+ install,
18
+ installDirectory,
19
+ uninstall,
20
+ } from '../src/install.ts'
15
21
 
16
22
  const USAGE =
17
- 'usage: abide-bridge <site> <code> [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge install [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge uninstall'
23
+ 'usage: abide-bridge <site> <code> [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge install [--claude <path>] [--env NAME=VALUE]... [-- <claude options>]\n abide-bridge uninstall\n abide-bridge forget [<site>]'
18
24
 
19
25
  const all = process.argv.slice(2)
20
26
  const split = all.indexOf('--')
@@ -40,7 +46,10 @@ const [site, code] = positional
40
46
  if (
41
47
  malformed ||
42
48
  site === undefined ||
43
- (site !== 'uninstall' && site !== 'install' && code === undefined)
49
+ (site !== 'uninstall' &&
50
+ site !== 'install' &&
51
+ site !== 'forget' &&
52
+ code === undefined)
44
53
  ) {
45
54
  console.error(USAGE)
46
55
  process.exit(2)
@@ -50,6 +59,16 @@ try {
50
59
  if (site === 'uninstall') {
51
60
  await uninstall()
52
61
  console.error(`Removed ${installDirectory()}.`)
62
+ } else if (site === 'forget') {
63
+ const forgotten = await forget(
64
+ allowedIn(handlerDirectory(installDirectory())),
65
+ code,
66
+ )
67
+ console.error(
68
+ forgotten === 0
69
+ ? `No site was always allowed${code === undefined ? '' : ` as ${code}`}.`
70
+ : `Forgot ${forgotten === 1 ? 'one site' : `${forgotten} sites`}. The next link from ${forgotten === 1 ? 'it' : 'them'} asks you again.`,
71
+ )
53
72
  } else {
54
73
  // Absolute, because an installed handler runs from no directory of the visitor's and on no shell's PATH.
55
74
  const found = Bun.which(claude ?? 'claude')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abide/bridge",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "Connects the Claude Code on your machine to the assistant on an abide site",
6
6
  "license": "MIT",
@@ -0,0 +1,83 @@
1
+ // THE SITES A VISITOR ALWAYS ALLOWS (44.62), kept beside the handler install wrote so uninstall takes
2
+ // them too. ONE PER SITE AND HOLDER: a link pairs unasked only where its code was minted for the same
3
+ // holder `/__abide/bridge` named when the visitor chose to always allow it — a code an attacker minted
4
+ // is minted for the attacker, and is asked about.
5
+ import { siteOf } from './pairingLink.ts'
6
+
7
+ /** A site paired unasked, for one holder, while a link asks for none but `tools`. */
8
+ export type AllowedSite = { site: string; holder: string; tools: string[] }
9
+
10
+ /** The file the sites `directory`'s handler always allows are kept in. */
11
+ export function allowedIn(directory: string): string {
12
+ return `${directory}/allowed.json`
13
+ }
14
+
15
+ /** The sites kept in `file`, or none where it is not there. */
16
+ export async function allowedSites(file: string): Promise<AllowedSite[]> {
17
+ const kept = Bun.file(file)
18
+ return (await kept.exists()) ? ((await kept.json()) as AllowedSite[]) : []
19
+ }
20
+
21
+ /** Whether `sites` let a link for `site`, minted for `holder` and asking for `tools`, pair unasked. 44.62. */
22
+ export function allowsUnasked(
23
+ sites: readonly AllowedSite[],
24
+ site: string,
25
+ holder: string,
26
+ tools: readonly string[],
27
+ ): boolean {
28
+ for (const allowed of sites)
29
+ if (allowed.site === site && allowed.holder === holder) {
30
+ for (const tool of tools)
31
+ if (!allowed.tools.includes(tool)) return false
32
+ return true
33
+ }
34
+ return false
35
+ }
36
+
37
+ /** Keeps `site` always allowed for `holder`, with `tools` beside the ones allowed before. */
38
+ export async function allowAlways(
39
+ file: string,
40
+ site: string,
41
+ holder: string,
42
+ tools: readonly string[],
43
+ ): Promise<void> {
44
+ const sites = await allowedSites(file)
45
+ let entry = sites.find(
46
+ (allowed) => allowed.site === site && allowed.holder === holder,
47
+ )
48
+ if (entry === undefined) {
49
+ entry = { site, holder, tools: [] }
50
+ sites.push(entry)
51
+ }
52
+ for (const tool of tools)
53
+ if (!entry.tools.includes(tool)) entry.tools.push(tool)
54
+ await Bun.write(file, JSON.stringify(sites, null, 4))
55
+ }
56
+
57
+ /**
58
+ * Forgets `site` — written as a link names it, or bare, `example.com/app` — or every site where none is
59
+ * named, and answers how many were forgotten. 44.63.
60
+ */
61
+ export async function forget(file: string, site?: string): Promise<number> {
62
+ const sites = await allowedSites(file)
63
+ const kept: AllowedSite[] = []
64
+ // Compared without the scheme, so a bare name matches the `https:` or loopback `http:` site kept.
65
+ const named =
66
+ site === undefined
67
+ ? undefined
68
+ : withoutScheme(
69
+ siteOf(
70
+ new URL(site.includes('://') ? site : `https://${site}`),
71
+ ),
72
+ )
73
+ for (const allowed of sites)
74
+ if (named !== undefined && withoutScheme(allowed.site) !== named)
75
+ kept.push(allowed)
76
+ if (kept.length !== sites.length)
77
+ await Bun.write(file, JSON.stringify(kept, null, 4))
78
+ return sites.length - kept.length
79
+ }
80
+
81
+ function withoutScheme(site: string): string {
82
+ return site.slice(site.indexOf('://') + 3)
83
+ }
package/src/bridge.ts CHANGED
@@ -7,12 +7,13 @@
7
7
  // inside the page's own request, as the person at the page. No credential of theirs reaches this
8
8
  // machine, and none of this machine's reaches the site.
9
9
 
10
- import { getCACertificates } from 'node:tls' // bun's fetch reads this machine's trust store only under `--use-system-ca`, a flag `bun x` and the link handler's launch cannot pass
11
-
12
- import type { AssistantEvent } from '@abide/abide/server'
10
+ import type { ProviderEvent } from '@abide/abide/server'
13
11
 
14
12
  import { claudeTurn, type TurnRequest } from './claudeTurn.ts'
13
+ import { grantFor, withheldNotices } from './grant.ts'
14
+ import { siteOf } from './pairingLink.ts'
15
15
  import { readLines } from './readLines.ts'
16
+ import { siteTls } from './siteTls.ts'
16
17
 
17
18
  // abide's `BRIDGE_ADDRESS`, spelled out because the bridge carries no abide at run time — a test
18
19
  // holds the two equal.
@@ -33,7 +34,7 @@ export const HEARTBEAT_MILLISECONDS = 15_000
33
34
  export const SILENCE_MILLISECONDS = 3 * HEARTBEAT_MILLISECONDS
34
35
 
35
36
  type SiteFrame =
36
- | { type: 'paired'; token: string }
37
+ | { type: 'paired'; token: string; tools?: string[] }
37
38
  | ({ type: 'turn' } & TurnRequest)
38
39
  | {
39
40
  type: 'reply'
@@ -45,7 +46,7 @@ type SiteFrame =
45
46
  | { type: 'bye' }
46
47
 
47
48
  type Report =
48
- | { type: 'event'; turn: string; event: AssistantEvent }
49
+ | { type: 'event'; turn: string; event: ProviderEvent }
49
50
  | {
50
51
  type: 'mcp'
51
52
  turn: string
@@ -55,6 +56,7 @@ type Report =
55
56
  }
56
57
  | { type: 'end'; turn: string }
57
58
  | { type: 'fail'; turn: string; message: string }
59
+ | { type: 'missing'; tools: string[] }
58
60
 
59
61
  /** A relayed MCP request the site has yet to reply to. */
60
62
  type Waiting = {
@@ -89,18 +91,8 @@ export async function bridge(options: {
89
91
  replyMilliseconds?: number
90
92
  silenceMilliseconds?: number
91
93
  }): Promise<void> {
92
- const site = options.site.replace(/\/+$/, '')
93
- // 44.47 — bun's own roots and this machine's, so a site whose certificate an organization's
94
- // authority signed is reached as the browser reaches it. a `ca` replaces bun's roots rather than
95
- // adding to them, so both are passed.
96
- const tls = {
97
- ca: [
98
- ...new Set([
99
- ...getCACertificates('bundled'),
100
- ...getCACertificates('system'),
101
- ]),
102
- ],
103
- }
94
+ const site = siteOf(new URL(options.site))
95
+ const tls = siteTls()
104
96
  // WHAT IS SAID IS READ AS A NOTIFICATION, where a link opened the bridge (`opened.ts`): one short
105
97
  // sentence naming the site by its host. The detail goes to Claude Code, in the failure it is answered.
106
98
  const host = new URL(site).host
@@ -175,13 +167,16 @@ export async function bridge(options: {
175
167
  // 44.46 — a turn the site missed part of has no answer left to give, and is ended: what it
176
168
  // still waits on is answered as `run` ends it, and the reason is what it reports it failed with.
177
169
  for (const item of batch)
178
- turns
179
- .get(item.turn)
180
- ?.abort(
181
- new MissedTurn(
182
- `The site missed part of this turn, so it was ended: ${failure}`,
183
- ),
184
- )
170
+ // A lost `missing` is said again by the next look, rather than taken as said.
171
+ if (item.type === 'missing') reported = undefined
172
+ else
173
+ turns
174
+ .get(item.turn)
175
+ ?.abort(
176
+ new MissedTurn(
177
+ `The site missed part of this turn, so it was ended: ${failure}`,
178
+ ),
179
+ )
185
180
  }
186
181
  // One post at a time, in order: a turn's `end` never overtakes its last event.
187
182
  const report = (item: Report): void => {
@@ -201,6 +196,24 @@ export async function bridge(options: {
201
196
  say(line)
202
197
  }
203
198
 
199
+ // 44.61 — WHAT THE PAIRING ASKED FOR AND THIS MACHINE CANNOT GIVE, reported once it pairs and again
200
+ // before a turn where it changed: a server the visitor adds meanwhile is found at the next turn.
201
+ let pairingAsked: string[] = []
202
+ let reported: string | undefined
203
+ const reportMissing = async (): Promise<void> => {
204
+ const { grant } = await grantFor(
205
+ pairingAsked,
206
+ options.claudeArgs ?? [],
207
+ sayOnce,
208
+ )
209
+ const missing = [...grant.ungranted, ...grant.unserved]
210
+ const key = missing.join(',')
211
+ if (key === reported) return
212
+ reported = key
213
+ for (const notice of withheldNotices(grant)) sayOnce(notice)
214
+ report({ type: 'missing', tools: missing })
215
+ }
216
+
204
217
  const turns = new Map<string, AbortController>()
205
218
  // 44.30 — A SIGNAL ENDS THE RUNS WITH THE BRIDGE: exiting on one skips every `finally`, so a run
206
219
  // still going would outlive it, orphaned.
@@ -275,6 +288,7 @@ export async function bridge(options: {
275
288
  const run = async (turn: TurnRequest): Promise<void> => {
276
289
  const controller = new AbortController()
277
290
  turns.set(turn.id, controller)
291
+ await reportMissing()
278
292
  // A cancel or a signal aborts with no reason of its own, and ends the turn as asked.
279
293
  const missed = (): string | undefined =>
280
294
  controller.signal.reason instanceof MissedTurn
@@ -363,9 +377,11 @@ export async function bridge(options: {
363
377
  ) as SiteFrame
364
378
  if (frame.type === 'paired') {
365
379
  token = frame.token
380
+ pairingAsked = frame.tools ?? []
366
381
  say(
367
382
  `Connected to ${host}. Close the page to disconnect.`,
368
383
  )
384
+ void reportMissing()
369
385
  } else if (frame.type === 'turn') void run(frame)
370
386
  else if (frame.type === 'reply')
371
387
  answer(frame.id, frame.reply)
package/src/claudeTurn.ts CHANGED
@@ -4,19 +4,24 @@
4
4
  //
5
5
  // THE SITE ASKS, THE VISITOR GRANTS (44.15, 44.16, 44.29). Every option is Claude Code's own, by name:
6
6
  // a site's is laid on as its flag where it only shapes the answer, and its `tools` are a request the
7
- // visitor's own `--tools` narrows. What reaches this machine — a user's settings, a project's
8
- // CLAUDE.md, the files around it, its shell, the web from its network — is the visitor's to give, on
9
- // the bridge's command line, and nothing the site sends can.
7
+ // visitor's own `--tools` narrows (`grant.ts`). What reaches this machine — a user's settings, a
8
+ // project's CLAUDE.md, the files around it, its shell, the web from its network, its MCP servers — is
9
+ // the visitor's to give, on the bridge's command line, and nothing the site sends can.
10
10
 
11
11
  import { mkdtemp, rm } from 'node:fs/promises' // bun has no temporary directory or recursive remove of its own
12
12
  import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
13
13
 
14
- import type { AssistantEvent, ClaudeCodeConfig } from '@abide/abide/server'
14
+ import type { ClaudeCodeConfig, ProviderEvent } from '@abide/abide/server'
15
15
 
16
+ import {
17
+ type Grant,
18
+ grantFor,
19
+ SERVER_NAME,
20
+ takeFlag,
21
+ withheldNotices,
22
+ } from './grant.ts'
16
23
  import { readLines } from './readLines.ts'
17
24
 
18
- // What Claude Code names the one MCP server it is handed, and so the prefix on each tool it calls.
19
- const SERVER_NAME = 'app'
20
25
  // Every tool of that server, as `--allowedTools` names them.
21
26
  const SERVER_TOOLS = `mcp__${SERVER_NAME}`
22
27
  const TOOL_PREFIX = `${SERVER_TOOLS}__`
@@ -105,68 +110,35 @@ function siteFlags(config: Omit<ClaudeCodeConfig, 'tools'>): string[] {
105
110
  return flags
106
111
  }
107
112
 
108
- /**
109
- * The values the visitor gave a flag by any of its `spellings` — `--flag a b`, `--flag a,b` or
110
- * `--flag=a` — taken out of `args`, or `undefined` where they never gave it.
111
- */
112
- function takeFlag(args: string[], spellings: string[]): string[] | undefined {
113
- let values: string[] | undefined
114
- for (let index = 0; index < args.length;) {
115
- const arg = args[index] as string
116
- const [flag, inline] = arg.split(/=(.*)/s) as [string, string?]
117
- if (!spellings.includes(flag)) {
118
- index++
119
- continue
120
- }
121
- values ??= []
122
- if (inline !== undefined) {
123
- values.push(inline)
124
- args.splice(index, 1)
125
- } else {
126
- let end = index + 1
127
- while (end < args.length && !(args[end] as string).startsWith('-'))
128
- end++
129
- values.push(...args.slice(index + 1, end))
130
- args.splice(index, end - index)
131
- }
132
- }
133
- return values
134
- }
135
-
136
113
  /**
137
114
  * Every flag but the protocol's: the site's, then the visitor's — so theirs wins where both set one —
138
- * then the built-in tools both named (44.29), and no setting source where the visitor named none.
139
- * Beside them, the tools the site asked for that the visitor did not give.
115
+ * then the tools the site asked for and the visitor granted (44.29), and no setting source where the
116
+ * visitor named none.
117
+ * Beside them, what the site was given of this machine (`grantOf`).
140
118
  */
141
- function launchFlags(
119
+ async function launchFlags(
142
120
  config: ClaudeCodeConfig,
143
121
  visitor: string[],
144
- ): { flags: string[]; ungranted: string[] } {
122
+ ): Promise<{ flags: string[]; grant: Grant }> {
145
123
  const { tools: asked, ...options } = config
146
- const args = [...visitor]
147
- const granted = new Set<string>()
148
- for (const value of takeFlag(args, ['--tools']) ?? [])
149
- for (const tool of value.split(/[\s,]+/)) granted.add(tool)
124
+ // 44.15 — the visitor's servers reach a turn only as the tools it was given are of them.
125
+ const { grant, args } = await grantFor(asked ?? [], visitor)
150
126
  const allowed = takeFlag(args, ['--allowedTools', '--allowed-tools'])
151
127
  const sources = takeFlag(args, ['--setting-sources']) ?? []
152
- const tools: string[] = []
153
- const ungranted: string[] = []
154
- for (const tool of asked ?? [])
155
- (granted.has(tool) ? tools : ungranted).push(tool)
156
128
  const flags = [
157
129
  ...siteFlags(options),
158
130
  ...args,
159
131
  '--tools',
160
- tools.join(','),
161
- // The site's own tools are always approved; a built-in one is approved as granted, unless
162
- // the visitor said which calls of it are.
132
+ grant.builtIn.join(','),
133
+ // The site's own tools are always approved; one of this machine's is approved as granted,
134
+ // unless the visitor said which calls of it are.
163
135
  '--allowedTools',
164
136
  SERVER_TOOLS,
165
- ...(allowed ?? tools),
137
+ ...(allowed ?? [...grant.builtIn, ...grant.mcp]),
166
138
  '--setting-sources',
167
139
  sources.join(','),
168
140
  ]
169
- return { flags, ungranted }
141
+ return { flags, grant }
170
142
  }
171
143
 
172
144
  function textOf(content: McpContent[] | string | undefined): string {
@@ -177,7 +149,7 @@ function textOf(content: McpContent[] | string | undefined): string {
177
149
  return text
178
150
  }
179
151
 
180
- function done(stop: string, usage: Usage | undefined): AssistantEvent {
152
+ function done(stop: string, usage: Usage | undefined): ProviderEvent {
181
153
  return {
182
154
  type: 'done',
183
155
  stop,
@@ -203,21 +175,19 @@ export async function claudeTurn(
203
175
  claudeArgs: string[]
204
176
  mcpUrl: string
205
177
  signal: AbortSignal
206
- report: (event: AssistantEvent) => void
178
+ report: (event: ProviderEvent) => void
207
179
  say: (line: string) => void
208
180
  },
209
181
  ): Promise<void> {
210
- const { flags, ungranted } = launchFlags(turn.config, options.claudeArgs)
211
- if (ungranted.length > 0)
212
- options.say(
213
- `The site asked for ${ungranted.join(', ')}, which this bridge wasn’t given. Add \`-- --tools ${ungranted.join(',')}\` to allow it.`,
214
- )
182
+ const { flags, grant } = await launchFlags(turn.config, options.claudeArgs)
183
+ for (const notice of withheldNotices(grant)) options.say(notice)
215
184
  const directory = await mkdtemp(`${tmpdir()}/abide-bridge-`)
216
185
  const config = `${directory}/mcp.json`
217
186
  await Bun.write(
218
187
  config,
219
188
  JSON.stringify({
220
189
  mcpServers: {
190
+ ...grant.servers,
221
191
  [SERVER_NAME]: { type: 'http', url: options.mcpUrl },
222
192
  },
223
193
  }),
package/src/desktop.ts ADDED
@@ -0,0 +1,164 @@
1
+ // WHAT THE LINK HANDLER SHOWS THE VISITOR, on each desktop it installs on: the question before a pairing
2
+ // (44.42) and a notification for each line the bridge says. Every question is passed as an argument or
3
+ // a variable, never written into a script, so nothing a site names is read as code.
4
+ //
5
+ // 44.64 — A QUESTION THAT CANNOT BE SHOWN IS A NO: a Linux desktop with neither `zenity` nor `kdialog`
6
+ // pairs nothing from a link.
7
+
8
+ /** What the visitor answered: don't pair, pair this once, or pair and stop asking for this site. */
9
+ export type Answer = 'deny' | 'once' | 'always'
10
+
11
+ const TITLE = 'abide bridge'
12
+ const DENY = 'Don’t Allow'
13
+ const ONCE = 'Allow'
14
+ const ALWAYS = 'Always Allow'
15
+
16
+ /** Runs `command`, answering its exit code and what it printed, or `undefined` where it could not start. */
17
+ async function ran(
18
+ command: string[],
19
+ env?: Record<string, string>,
20
+ ): Promise<{ code: number; printed: string } | undefined> {
21
+ try {
22
+ const child = Bun.spawn(command, {
23
+ stdout: 'pipe',
24
+ stderr: 'ignore',
25
+ env: { ...Bun.env, ...env },
26
+ })
27
+ const printed = (await new Response(child.stdout).text()).trim()
28
+ return { code: await child.exited, printed }
29
+ } catch {
30
+ return undefined
31
+ }
32
+ }
33
+
34
+ /** Runs one AppleScript with `argument` as `item 1 of argv`. */
35
+ function appleScript(
36
+ lines: string[],
37
+ argument: string,
38
+ ): ReturnType<typeof ran> {
39
+ const script: string[] = ['-e', 'on run argv']
40
+ for (const line of lines) script.push('-e', line)
41
+ script.push('-e', 'end run')
42
+ return ran(['osascript', ...script, argument])
43
+ }
44
+
45
+ /** A PowerShell script, run with `text` in `ABIDE_BRIDGE_TEXT`, answering what it printed. */
46
+ async function powerShell(script: string, text: string): Promise<string> {
47
+ const done = await ran(
48
+ ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', script],
49
+ { ABIDE_BRIDGE_TEXT: text },
50
+ )
51
+ return done?.code === 0 ? done.printed : ''
52
+ }
53
+
54
+ /**
55
+ * The command that shows `question` on a Linux desktop, by the first of `zenity` and `kdialog` it
56
+ * `has`, or `undefined` where it has neither.
57
+ */
58
+ export function linuxQuestion(
59
+ question: string,
60
+ offerAlways: boolean,
61
+ has: (tool: string) => boolean,
62
+ ): string[] | undefined {
63
+ if (has('zenity'))
64
+ return [
65
+ 'zenity',
66
+ '--question',
67
+ '--title',
68
+ TITLE,
69
+ '--text',
70
+ question,
71
+ '--no-markup',
72
+ '--ok-label',
73
+ ONCE,
74
+ '--cancel-label',
75
+ DENY,
76
+ ...(offerAlways ? ['--extra-button', ALWAYS] : []),
77
+ ]
78
+ if (has('kdialog'))
79
+ return [
80
+ 'kdialog',
81
+ '--title',
82
+ TITLE,
83
+ offerAlways ? '--yesnocancel' : '--yesno',
84
+ question,
85
+ '--yes-label',
86
+ ONCE,
87
+ ...(offerAlways
88
+ ? ['--no-label', ALWAYS, '--cancel-label', DENY]
89
+ : ['--no-label', DENY]),
90
+ ]
91
+ return undefined
92
+ }
93
+
94
+ /** Asks the visitor `question`, offering to always allow where `offerAlways`; closing it is a no. */
95
+ export async function ask(
96
+ question: string,
97
+ offerAlways: boolean,
98
+ ): Promise<Answer> {
99
+ const platform = process.platform
100
+ if (platform === 'darwin') {
101
+ const buttons = offerAlways
102
+ ? `{"${DENY}", "${ALWAYS}", "${ONCE}"}`
103
+ : `{"${DENY}", "${ONCE}"}`
104
+ const pressed = await appleScript(
105
+ [
106
+ `display dialog (item 1 of argv) with title "${TITLE}" buttons ${buttons} default button "${DENY}" cancel button "${DENY}" with icon caution`,
107
+ 'button returned of result',
108
+ ],
109
+ question,
110
+ )
111
+ if (pressed?.code !== 0) return 'deny'
112
+ return pressed.printed === ALWAYS
113
+ ? 'always'
114
+ : pressed.printed === ONCE
115
+ ? 'once'
116
+ : 'deny'
117
+ }
118
+ if (platform === 'win32') {
119
+ // A message box's buttons carry no labels of their own, so always is a second question.
120
+ const box = (buttons: string, text: string): Promise<string> =>
121
+ powerShell(
122
+ `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show($env:ABIDE_BRIDGE_TEXT, '${TITLE}', '${buttons}', 'Warning', 'Button2')`,
123
+ text,
124
+ )
125
+ if ((await box('YesNo', `${question}\n\nAllow it?`)) !== 'Yes')
126
+ return 'deny'
127
+ if (!offerAlways) return 'once'
128
+ return (await box(
129
+ 'YesNo',
130
+ 'Always allow this site, as the same account, without asking?',
131
+ )) === 'Yes'
132
+ ? 'always'
133
+ : 'once'
134
+ }
135
+ if (platform !== 'linux') return 'deny'
136
+ const command = linuxQuestion(
137
+ question,
138
+ offerAlways,
139
+ (tool) => Bun.which(tool) !== null,
140
+ )
141
+ if (command === undefined) return 'deny'
142
+ const shown = await ran(command)
143
+ if (shown === undefined) return 'deny'
144
+ if (command[0] === 'zenity')
145
+ return shown.code === 0
146
+ ? 'once'
147
+ : shown.printed === ALWAYS
148
+ ? 'always'
149
+ : 'deny'
150
+ // kdialog: yes is once, and no is always where always was offered.
151
+ if (shown.code === 0) return 'once'
152
+ return offerAlways && shown.code === 1 ? 'always' : 'deny'
153
+ }
154
+
155
+ /** Shows `line` as a notification, where this desktop has a way to. */
156
+ export async function notify(line: string): Promise<void> {
157
+ if (process.platform === 'darwin')
158
+ await appleScript(
159
+ [`display notification (item 1 of argv) with title "${TITLE}"`],
160
+ line,
161
+ )
162
+ else if (process.platform === 'linux' && Bun.which('notify-send') !== null)
163
+ await ran(['notify-send', TITLE, line])
164
+ }